WIP: bootstrap and partial real Solana watcher implementation

This commit is contained in:
2026-08-16 09:17:45 +00:00
commit dc23412c3f
7232 changed files with 1687637 additions and 0 deletions

View File

@@ -0,0 +1,273 @@
# ESLint Plugin Kit
## Description
A collection of utilities to help build ESLint plugins.
## Installation
For Node.js and compatible runtimes:
```shell
npm install @eslint/plugin-kit
# or
yarn add @eslint/plugin-kit
# or
pnpm install @eslint/plugin-kit
# or
bun add @eslint/plugin-kit
```
For Deno:
```shell
deno add @eslint/plugin-kit
```
## Usage
This package exports the following utilities:
- [`ConfigCommentParser`](#configcommentparser) - used to parse ESLint configuration comments (i.e., `/* eslint-disable rule */`)
- [`VisitNodeStep` and `CallMethodStep`](#visitnodestep-and-callmethodstep) - used to help implement `SourceCode#traverse()`
- [`Directive`](#directive) - used to help implement `SourceCode#getDisableDirectives()`
- [`TextSourceCodeBase`](#textsourcecodebase) - base class to help implement the `SourceCode` interface
### `ConfigCommentParser`
To use the `ConfigCommentParser` class, import it from the package and create a new instance, such as:
```js
import { ConfigCommentParser } from "@eslint/plugin-kit";
// create a new instance
const commentParser = new ConfigCommentParser();
// pass in a comment string without the comment delimiters
const directive = commentParser.parseDirective(
"eslint-disable prefer-const, no-var -- I don't want to use these.",
);
// will be undefined when a directive can't be parsed
if (directive) {
console.log(directive.label); // "eslint-disable"
console.log(directive.value); // "prefer-const, no-var"
console.log(directive.justification); // "I don't want to use these."
}
```
There are different styles of directive values that you'll need to parse separately to get the correct format:
```js
import { ConfigCommentParser } from "@eslint/plugin-kit";
// create a new instance
const commentParser = new ConfigCommentParser();
// list format
const list = commentParser.parseListConfig("prefer-const, no-var");
console.log(Object.entries(list)); // [["prefer-const", true], ["no-var", true]]
// string format
const strings = commentParser.parseStringConfig("foo:off, bar");
console.log(Object.entries(strings)); // [["foo", "off"], ["bar", null]]
// JSON-like config format
const jsonLike = commentParser.parseJSONLikeConfig(
"radix:[error, always], prefer-const: warn",
);
console.log(Object.entries(jsonLike.config)); // [["radix", ["error", "always"]], ["prefer-const", "warn"]]
```
### `VisitNodeStep` and `CallMethodStep`
The `VisitNodeStep` and `CallMethodStep` classes represent steps in the traversal of source code. They implement the correct interfaces to return from the `SourceCode#traverse()` method.
The `VisitNodeStep` class is the more common of the two, where you are describing a visit to a particular node during the traversal. The constructor accepts three arguments:
- `target` - the node being visited. This is used to determine the method to call inside of a rule. For instance, if the node's type is `Literal` then ESLint will call a method named `Literal()` on the rule (if present).
- `phase` - either 1 for enter or 2 for exit.
- `args` - an array of arguments to pass into the visitor method of a rule.
For example:
```js
import { VisitNodeStep } from "@eslint/plugin-kit";
class MySourceCode {
traverse() {
const steps = [];
for (const { node, parent, phase } of iterator(this.ast)) {
steps.push(
new VisitNodeStep({
target: node,
phase: phase === "enter" ? 1 : 2,
args: [node, parent],
}),
);
}
return steps;
}
}
```
The `CallMethodStep` class is less common and is used to tell ESLint to call a specific method on the rule. The constructor accepts two arguments:
- `target` - the name of the method to call, frequently beginning with `"on"` such as `"onCodePathStart"`.
- `args` - an array of arguments to pass to the method.
For example:
```js
import { VisitNodeStep, CallMethodStep } from "@eslint/plugin-kit";
class MySourceCode {
traverse() {
const steps = [];
for (const { node, parent, phase } of iterator(this.ast)) {
steps.push(
new VisitNodeStep({
target: node,
phase: phase === "enter" ? 1 : 2,
args: [node, parent],
}),
);
// call a method indicating how many times we've been through the loop
steps.push(
new CallMethodStep({
target: "onIteration",
args: [steps.length]
});
)
}
return steps;
}
}
```
### `Directive`
The `Directive` class represents a disable directive in the source code and implements the `Directive` interface from `@eslint/core`. You can tell ESLint about disable directives using the `SourceCode#getDisableDirectives()` method, where part of the return value is an array of `Directive` objects. Here's an example:
```js
import { Directive, ConfigCommentParser } from "@eslint/plugin-kit";
class MySourceCode {
getDisableDirectives() {
const directives = [];
const problems = [];
const commentParser = new ConfigCommentParser();
// read in the inline config nodes to check each one
this.getInlineConfigNodes().forEach(comment => {
// Step 1: Parse the directive
const { label, value, justification } =
commentParser.parseDirective(comment.value);
// Step 2: Extract the directive value and create the `Directive` object
switch (label) {
case "eslint-disable":
case "eslint-enable":
case "eslint-disable-next-line":
case "eslint-disable-line": {
const directiveType = label.slice("eslint-".length);
directives.push(
new Directive({
type: directiveType,
node: comment,
value,
justification,
}),
);
}
// ignore any comments that don't begin with known labels
}
});
return {
directives,
problems,
};
}
}
```
### `TextSourceCodeBase`
The `TextSourceCodeBase` class is intended to be a base class that has several of the common members found in `SourceCode` objects already implemented. Those members are:
- `lines` - an array of text lines that is created automatically when the constructor is called.
- `getLoc(nodeOrToken)` - gets the location of a node or token. Works for nodes that have the ESLint-style `loc` property and nodes that have the Unist-style [`position` property](https://github.com/syntax-tree/unist?tab=readme-ov-file#position). If you're using an AST with a different location format, you'll still need to implement this method yourself.
- `getLocFromIndex(index)` - Converts a source text index into a `{ line: number, column: number }` pair. (For this method to work, the root node should always cover the entire source code text, and the `getLoc()` method needs to be implemented correctly.)
- `getIndexFromLoc(loc)` - Converts a `{ line: number, column: number }` pair into a source text index. (For this method to work, the root node should always cover the entire source code text, and the `getLoc()` method needs to be implemented correctly.)
- `getRange(nodeOrToken)` - gets the range of a node or token within the source text. Works for nodes that have the ESLint-style `range` property and nodes that have the Unist-style [`position` property](https://github.com/syntax-tree/unist?tab=readme-ov-file#position). If you're using an AST with a different range format, you'll still need to implement this method yourself.
- `getText(node, beforeCount, afterCount)` - gets the source text for the given node that has range information attached. Optionally, can return additional characters before and after the given node. As long as `getRange()` is properly implemented, this method will just work.
- `getAncestors(node)` - returns the ancestry of the node. In order for this to work, you must implement the `getParent()` method yourself.
Here's an example:
```js
import { TextSourceCodeBase } from "@eslint/plugin-kit";
export class MySourceCode extends TextSourceCodeBase {
#parents = new Map();
constructor({ ast, text }) {
super({ ast, text });
}
getParent(node) {
return this.#parents.get(node);
}
traverse() {
const steps = [];
for (const { node, parent, phase } of iterator(this.ast)) {
//save the parent information
this.#parent.set(node, parent);
steps.push(
new VisitNodeStep({
target: node,
phase: phase === "enter" ? 1 : 2,
args: [node, parent],
}),
);
}
return steps;
}
}
```
In general, it's safe to collect the parent information during the `traverse()` method as `getParent()` and `getAncestor()` will only be called from rules once the AST has been traversed at least once.
## License
Apache 2.0
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
<!--sponsorsstart-->
## Sponsors
The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
to get your logo on our READMEs and [website](https://eslint.org/sponsors).
<h3>Platinum Sponsors</h3>
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/automattic/d0ef3e1/logo.png" alt="Automattic" height="128"></a></p><h3>Gold Sponsors</h3>
<p><a href="https://qlty.sh/"><img src="https://images.opencollective.com/qltysh/33d157d/logo.png" alt="Qlty Software" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://vite.dev/"><img src="https://images.opencollective.com/vite/d472863/logo.png" alt="Vite" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/2d6c3b6/logo.png" alt="Liftoff" height="64"></a> <a href="https://stackblitz.com"><img src="https://avatars.githubusercontent.com/u/28635252" alt="StackBlitz" height="64"></a></p><h3>Bronze Sponsors</h3>
<p><a href="https://cybozu.co.jp/"><img src="https://images.opencollective.com/cybozu/933e46d/logo.png" alt="Cybozu" height="32"></a> <a href="https://opensource.sap.com"><img src="https://avatars.githubusercontent.com/u/2531208" alt="SAP" height="32"></a> <a href="https://www.crawljobs.com/"><img src="https://images.opencollective.com/crawljobs-poland/fa43a17/logo.png" alt="CrawlJobs" height="32"></a> <a href="https://syntax.fm"><img src="https://github.com/syntaxfm.png" alt="Syntax" height="32"></a> <a href="https://depot.dev"><img src="https://images.opencollective.com/depot/39125a1/logo.png" alt="Depot" height="32"></a> <a href="https://icons8.com/"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://www.gitbook.com"><img src="https://avatars.githubusercontent.com/u/7111340" alt="GitBook" height="32"></a> <a href="https://herocoders.com"><img src="https://avatars.githubusercontent.com/u/37549774" alt="HeroCoders" height="32"></a> <a href="https://citadel.co.jp"><img src="https://avatars.githubusercontent.com/u/75781367" alt="Citadel AI" height="32"></a></p>
<h3>Technology Sponsors</h3>
Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work.
<p><a href="https://netlify.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/netlify-icon.svg" alt="Netlify" height="32"></a> <a href="https://algolia.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/algolia-icon.svg" alt="Algolia" height="32"></a> <a href="https://1password.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/1password-icon.svg" alt="1Password" height="32"></a></p>
<!--sponsorsend-->

View File

@@ -0,0 +1,11 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}
{{? !$isData }}
var schema{{=$lvl}} = validate.schema{{=$schemaPath}};
{{?}}
var {{=$valid}} = equal({{=$data}}, schema{{=$lvl}});
{{# def.checkError:'const' }}
{{? $breakOnError }} else { {{?}}

View File

@@ -0,0 +1,625 @@
'use strict'
const { hasOwnProperty } = Object.prototype
const stringify = configure()
// @ts-expect-error
stringify.configure = configure
// @ts-expect-error
stringify.stringify = stringify
// @ts-expect-error
stringify.default = stringify
// @ts-expect-error used for named export
exports.stringify = stringify
// @ts-expect-error used for named export
exports.configure = configure
module.exports = stringify
// eslint-disable-next-line no-control-regex
const strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]/
// Escape C0 control characters, double quotes, the backslash and every code
// unit with a numeric value in the inclusive range 0xD800 to 0xDFFF.
function strEscape (str) {
// Some magic numbers that worked out fine while benchmarking with v8 8.0
if (str.length < 5000 && !strEscapeSequencesRegExp.test(str)) {
return `"${str}"`
}
return JSON.stringify(str)
}
function sort (array, comparator) {
// Insertion sort is very efficient for small input sizes, but it has a bad
// worst case complexity. Thus, use native array sort for bigger values.
if (array.length > 2e2 || comparator) {
return array.sort(comparator)
}
for (let i = 1; i < array.length; i++) {
const currentValue = array[i]
let position = i
while (position !== 0 && array[position - 1] > currentValue) {
array[position] = array[position - 1]
position--
}
array[position] = currentValue
}
return array
}
const typedArrayPrototypeGetSymbolToStringTag =
Object.getOwnPropertyDescriptor(
Object.getPrototypeOf(
Object.getPrototypeOf(
new Int8Array()
)
),
Symbol.toStringTag
).get
function isTypedArrayWithEntries (value) {
return typedArrayPrototypeGetSymbolToStringTag.call(value) !== undefined && value.length !== 0
}
function stringifyTypedArray (array, separator, maximumBreadth) {
if (array.length < maximumBreadth) {
maximumBreadth = array.length
}
const whitespace = separator === ',' ? '' : ' '
let res = `"0":${whitespace}${array[0]}`
for (let i = 1; i < maximumBreadth; i++) {
res += `${separator}"${i}":${whitespace}${array[i]}`
}
return res
}
function getCircularValueOption (options) {
if (hasOwnProperty.call(options, 'circularValue')) {
const circularValue = options.circularValue
if (typeof circularValue === 'string') {
return `"${circularValue}"`
}
if (circularValue == null) {
return circularValue
}
if (circularValue === Error || circularValue === TypeError) {
return {
toString () {
throw new TypeError('Converting circular structure to JSON')
}
}
}
throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')
}
return '"[Circular]"'
}
function getDeterministicOption (options) {
let value
if (hasOwnProperty.call(options, 'deterministic')) {
value = options.deterministic
if (typeof value !== 'boolean' && typeof value !== 'function') {
throw new TypeError('The "deterministic" argument must be of type boolean or comparator function')
}
}
return value === undefined ? true : value
}
function getBooleanOption (options, key) {
let value
if (hasOwnProperty.call(options, key)) {
value = options[key]
if (typeof value !== 'boolean') {
throw new TypeError(`The "${key}" argument must be of type boolean`)
}
}
return value === undefined ? true : value
}
function getPositiveIntegerOption (options, key) {
let value
if (hasOwnProperty.call(options, key)) {
value = options[key]
if (typeof value !== 'number') {
throw new TypeError(`The "${key}" argument must be of type number`)
}
if (!Number.isInteger(value)) {
throw new TypeError(`The "${key}" argument must be an integer`)
}
if (value < 1) {
throw new RangeError(`The "${key}" argument must be >= 1`)
}
}
return value === undefined ? Infinity : value
}
function getItemCount (number) {
if (number === 1) {
return '1 item'
}
return `${number} items`
}
function getUniqueReplacerSet (replacerArray) {
const replacerSet = new Set()
for (const value of replacerArray) {
if (typeof value === 'string' || typeof value === 'number') {
replacerSet.add(String(value))
}
}
return replacerSet
}
function getStrictOption (options) {
if (hasOwnProperty.call(options, 'strict')) {
const value = options.strict
if (typeof value !== 'boolean') {
throw new TypeError('The "strict" argument must be of type boolean')
}
if (value) {
return (value) => {
let message = `Object can not safely be stringified. Received type ${typeof value}`
if (typeof value !== 'function') message += ` (${value.toString()})`
throw new Error(message)
}
}
}
}
function configure (options) {
options = { ...options }
const fail = getStrictOption(options)
if (fail) {
if (options.bigint === undefined) {
options.bigint = false
}
if (!('circularValue' in options)) {
options.circularValue = Error
}
}
const circularValue = getCircularValueOption(options)
const bigint = getBooleanOption(options, 'bigint')
const deterministic = getDeterministicOption(options)
const comparator = typeof deterministic === 'function' ? deterministic : undefined
const maximumDepth = getPositiveIntegerOption(options, 'maximumDepth')
const maximumBreadth = getPositiveIntegerOption(options, 'maximumBreadth')
function stringifyFnReplacer (key, parent, stack, replacer, spacer, indentation) {
let value = parent[key]
if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {
value = value.toJSON(key)
}
value = replacer.call(parent, key, value)
switch (typeof value) {
case 'string':
return strEscape(value)
case 'object': {
if (value === null) {
return 'null'
}
if (stack.indexOf(value) !== -1) {
return circularValue
}
let res = ''
let join = ','
const originalIndentation = indentation
if (Array.isArray(value)) {
if (value.length === 0) {
return '[]'
}
if (maximumDepth < stack.length + 1) {
return '"[Array]"'
}
stack.push(value)
if (spacer !== '') {
indentation += spacer
res += `\n${indentation}`
join = `,\n${indentation}`
}
const maximumValuesToStringify = Math.min(value.length, maximumBreadth)
let i = 0
for (; i < maximumValuesToStringify - 1; i++) {
const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)
res += tmp !== undefined ? tmp : 'null'
res += join
}
const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)
res += tmp !== undefined ? tmp : 'null'
if (value.length - 1 > maximumBreadth) {
const removedKeys = value.length - maximumBreadth - 1
res += `${join}"... ${getItemCount(removedKeys)} not stringified"`
}
if (spacer !== '') {
res += `\n${originalIndentation}`
}
stack.pop()
return `[${res}]`
}
let keys = Object.keys(value)
const keyLength = keys.length
if (keyLength === 0) {
return '{}'
}
if (maximumDepth < stack.length + 1) {
return '"[Object]"'
}
let whitespace = ''
let separator = ''
if (spacer !== '') {
indentation += spacer
join = `,\n${indentation}`
whitespace = ' '
}
const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)
if (deterministic && !isTypedArrayWithEntries(value)) {
keys = sort(keys, comparator)
}
stack.push(value)
for (let i = 0; i < maximumPropertiesToStringify; i++) {
const key = keys[i]
const tmp = stringifyFnReplacer(key, value, stack, replacer, spacer, indentation)
if (tmp !== undefined) {
res += `${separator}${strEscape(key)}:${whitespace}${tmp}`
separator = join
}
}
if (keyLength > maximumBreadth) {
const removedKeys = keyLength - maximumBreadth
res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`
separator = join
}
if (spacer !== '' && separator.length > 1) {
res = `\n${indentation}${res}\n${originalIndentation}`
}
stack.pop()
return `{${res}}`
}
case 'number':
return isFinite(value) ? String(value) : fail ? fail(value) : 'null'
case 'boolean':
return value === true ? 'true' : 'false'
case 'undefined':
return undefined
case 'bigint':
if (bigint) {
return String(value)
}
// fallthrough
default:
return fail ? fail(value) : undefined
}
}
function stringifyArrayReplacer (key, value, stack, replacer, spacer, indentation) {
if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {
value = value.toJSON(key)
}
switch (typeof value) {
case 'string':
return strEscape(value)
case 'object': {
if (value === null) {
return 'null'
}
if (stack.indexOf(value) !== -1) {
return circularValue
}
const originalIndentation = indentation
let res = ''
let join = ','
if (Array.isArray(value)) {
if (value.length === 0) {
return '[]'
}
if (maximumDepth < stack.length + 1) {
return '"[Array]"'
}
stack.push(value)
if (spacer !== '') {
indentation += spacer
res += `\n${indentation}`
join = `,\n${indentation}`
}
const maximumValuesToStringify = Math.min(value.length, maximumBreadth)
let i = 0
for (; i < maximumValuesToStringify - 1; i++) {
const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)
res += tmp !== undefined ? tmp : 'null'
res += join
}
const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)
res += tmp !== undefined ? tmp : 'null'
if (value.length - 1 > maximumBreadth) {
const removedKeys = value.length - maximumBreadth - 1
res += `${join}"... ${getItemCount(removedKeys)} not stringified"`
}
if (spacer !== '') {
res += `\n${originalIndentation}`
}
stack.pop()
return `[${res}]`
}
stack.push(value)
let whitespace = ''
if (spacer !== '') {
indentation += spacer
join = `,\n${indentation}`
whitespace = ' '
}
let separator = ''
for (const key of replacer) {
const tmp = stringifyArrayReplacer(key, value[key], stack, replacer, spacer, indentation)
if (tmp !== undefined) {
res += `${separator}${strEscape(key)}:${whitespace}${tmp}`
separator = join
}
}
if (spacer !== '' && separator.length > 1) {
res = `\n${indentation}${res}\n${originalIndentation}`
}
stack.pop()
return `{${res}}`
}
case 'number':
return isFinite(value) ? String(value) : fail ? fail(value) : 'null'
case 'boolean':
return value === true ? 'true' : 'false'
case 'undefined':
return undefined
case 'bigint':
if (bigint) {
return String(value)
}
// fallthrough
default:
return fail ? fail(value) : undefined
}
}
function stringifyIndent (key, value, stack, spacer, indentation) {
switch (typeof value) {
case 'string':
return strEscape(value)
case 'object': {
if (value === null) {
return 'null'
}
if (typeof value.toJSON === 'function') {
value = value.toJSON(key)
// Prevent calling `toJSON` again.
if (typeof value !== 'object') {
return stringifyIndent(key, value, stack, spacer, indentation)
}
if (value === null) {
return 'null'
}
}
if (stack.indexOf(value) !== -1) {
return circularValue
}
const originalIndentation = indentation
if (Array.isArray(value)) {
if (value.length === 0) {
return '[]'
}
if (maximumDepth < stack.length + 1) {
return '"[Array]"'
}
stack.push(value)
indentation += spacer
let res = `\n${indentation}`
const join = `,\n${indentation}`
const maximumValuesToStringify = Math.min(value.length, maximumBreadth)
let i = 0
for (; i < maximumValuesToStringify - 1; i++) {
const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)
res += tmp !== undefined ? tmp : 'null'
res += join
}
const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)
res += tmp !== undefined ? tmp : 'null'
if (value.length - 1 > maximumBreadth) {
const removedKeys = value.length - maximumBreadth - 1
res += `${join}"... ${getItemCount(removedKeys)} not stringified"`
}
res += `\n${originalIndentation}`
stack.pop()
return `[${res}]`
}
let keys = Object.keys(value)
const keyLength = keys.length
if (keyLength === 0) {
return '{}'
}
if (maximumDepth < stack.length + 1) {
return '"[Object]"'
}
indentation += spacer
const join = `,\n${indentation}`
let res = ''
let separator = ''
let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)
if (isTypedArrayWithEntries(value)) {
res += stringifyTypedArray(value, join, maximumBreadth)
keys = keys.slice(value.length)
maximumPropertiesToStringify -= value.length
separator = join
}
if (deterministic) {
keys = sort(keys, comparator)
}
stack.push(value)
for (let i = 0; i < maximumPropertiesToStringify; i++) {
const key = keys[i]
const tmp = stringifyIndent(key, value[key], stack, spacer, indentation)
if (tmp !== undefined) {
res += `${separator}${strEscape(key)}: ${tmp}`
separator = join
}
}
if (keyLength > maximumBreadth) {
const removedKeys = keyLength - maximumBreadth
res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`
separator = join
}
if (separator !== '') {
res = `\n${indentation}${res}\n${originalIndentation}`
}
stack.pop()
return `{${res}}`
}
case 'number':
return isFinite(value) ? String(value) : fail ? fail(value) : 'null'
case 'boolean':
return value === true ? 'true' : 'false'
case 'undefined':
return undefined
case 'bigint':
if (bigint) {
return String(value)
}
// fallthrough
default:
return fail ? fail(value) : undefined
}
}
function stringifySimple (key, value, stack) {
switch (typeof value) {
case 'string':
return strEscape(value)
case 'object': {
if (value === null) {
return 'null'
}
if (typeof value.toJSON === 'function') {
value = value.toJSON(key)
// Prevent calling `toJSON` again
if (typeof value !== 'object') {
return stringifySimple(key, value, stack)
}
if (value === null) {
return 'null'
}
}
if (stack.indexOf(value) !== -1) {
return circularValue
}
let res = ''
const hasLength = value.length !== undefined
if (hasLength && Array.isArray(value)) {
if (value.length === 0) {
return '[]'
}
if (maximumDepth < stack.length + 1) {
return '"[Array]"'
}
stack.push(value)
const maximumValuesToStringify = Math.min(value.length, maximumBreadth)
let i = 0
for (; i < maximumValuesToStringify - 1; i++) {
const tmp = stringifySimple(String(i), value[i], stack)
res += tmp !== undefined ? tmp : 'null'
res += ','
}
const tmp = stringifySimple(String(i), value[i], stack)
res += tmp !== undefined ? tmp : 'null'
if (value.length - 1 > maximumBreadth) {
const removedKeys = value.length - maximumBreadth - 1
res += `,"... ${getItemCount(removedKeys)} not stringified"`
}
stack.pop()
return `[${res}]`
}
let keys = Object.keys(value)
const keyLength = keys.length
if (keyLength === 0) {
return '{}'
}
if (maximumDepth < stack.length + 1) {
return '"[Object]"'
}
let separator = ''
let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)
if (hasLength && isTypedArrayWithEntries(value)) {
res += stringifyTypedArray(value, ',', maximumBreadth)
keys = keys.slice(value.length)
maximumPropertiesToStringify -= value.length
separator = ','
}
if (deterministic) {
keys = sort(keys, comparator)
}
stack.push(value)
for (let i = 0; i < maximumPropertiesToStringify; i++) {
const key = keys[i]
const tmp = stringifySimple(key, value[key], stack)
if (tmp !== undefined) {
res += `${separator}${strEscape(key)}:${tmp}`
separator = ','
}
}
if (keyLength > maximumBreadth) {
const removedKeys = keyLength - maximumBreadth
res += `${separator}"...":"${getItemCount(removedKeys)} not stringified"`
}
stack.pop()
return `{${res}}`
}
case 'number':
return isFinite(value) ? String(value) : fail ? fail(value) : 'null'
case 'boolean':
return value === true ? 'true' : 'false'
case 'undefined':
return undefined
case 'bigint':
if (bigint) {
return String(value)
}
// fallthrough
default:
return fail ? fail(value) : undefined
}
}
function stringify (value, replacer, space) {
if (arguments.length > 1) {
let spacer = ''
if (typeof space === 'number') {
spacer = ' '.repeat(Math.min(space, 10))
} else if (typeof space === 'string') {
spacer = space.slice(0, 10)
}
if (replacer != null) {
if (typeof replacer === 'function') {
return stringifyFnReplacer('', { '': value }, [], replacer, spacer, '')
}
if (Array.isArray(replacer)) {
return stringifyArrayReplacer('', value, [], getUniqueReplacerSet(replacer), spacer, '')
}
}
if (spacer.length !== 0) {
return stringifyIndent('', value, [], spacer, '')
}
}
return stringifySimple('', value, [])
}
return stringify
}

View File

@@ -0,0 +1,194 @@
{
"name": "vite",
"version": "8.2.1",
"description": "Native-ESM powered web dev build tool",
"keywords": [
"build-tool",
"dev-server",
"framework",
"frontend",
"hmr",
"vite"
],
"homepage": "https://vite.dev",
"bugs": {
"url": "https://github.com/vitejs/vite/issues"
},
"license": "MIT",
"author": "Evan You",
"repository": {
"type": "git",
"url": "git+https://github.com/vitejs/vite.git",
"directory": "packages/vite"
},
"funding": "https://github.com/vitejs/vite?sponsor=1",
"bin": {
"vite": "bin/vite.js"
},
"files": [
"bin",
"dist",
"misc/**/*.js",
"client.d.ts",
"types"
],
"type": "module",
"imports": {
"#module-sync-enabled": {
"module-sync": "./misc/true.js",
"default": "./misc/false.js"
},
"#types/*": "./types/*.d.ts",
"#dep-types/*": "./src/types/*.d.ts"
},
"exports": {
".": "./dist/node/index.js",
"./client": {
"types": "./client.d.ts"
},
"./module-runner": "./dist/node/module-runner.js",
"./internal": "./dist/node/internal.js",
"./dist/client/*": "./dist/client/*",
"./types/*": {
"types": "./types/*"
},
"./types/internal/*": null,
"./package.json": "./package.json"
},
"dependencies": {
"lightningcss": "^1.33.0",
"picomatch": "^4.0.5",
"postcss": "^8.5.25",
"rolldown": "~1.2.1",
"tinyglobby": "^0.2.17"
},
"devDependencies": {
"@babel/parser": "^7.29.8",
"@jridgewell/remapping": "^2.3.5",
"@jridgewell/trace-mapping": "^0.3.31",
"@polka/compression": "^1.0.0-next.25",
"@rollup/plugin-alias": "^6.0.0",
"@rollup/plugin-dynamic-import-vars": "2.1.4",
"@rollup/pluginutils": "^5.4.0",
"@types/escape-html": "^1.0.4",
"@types/pnpapi": "^0.0.5",
"@vercel/detect-agent": "^1.2.3",
"@vitejs/devtools": "^0.4.10",
"@vitest/utils": "4.1.10",
"@voidzero-dev/vite-task-client": "^0.2.0",
"artichokie": "^0.4.4",
"baseline-browser-mapping": "^2.11.10",
"cac": "^7.0.0",
"chokidar": "^3.6.0",
"connect": "^3.7.0",
"convert-source-map": "^2.0.0",
"cors": "^2.8.6",
"cross-spawn": "^7.0.6",
"dotenv-expand": "^13.0.0",
"es-module-lexer": "^2.3.1",
"esbuild": "^0.28.1",
"escape-html": "^1.0.3",
"estree-walker": "^3.0.3",
"etag": "^1.8.1",
"fresh-import": "^0.2.1",
"host-validation-middleware": "^0.1.4",
"http-proxy-3": "^1.23.3",
"launch-editor-middleware": "^2.14.1",
"magic-string": "^1.1.0",
"mlly": "^1.8.2",
"mrmime": "^2.0.1",
"nanoid": "^5.1.16",
"obug": "^1.0.2",
"open": "^10.2.0",
"parse5": "^8.0.1",
"pathe": "^2.0.3",
"periscopic": "^4.0.3",
"picocolors": "^1.1.1",
"postcss-import": "^16.1.1",
"postcss-load-config": "^6.0.1",
"postcss-modules": "^9.0.1",
"premove": "^4.0.0",
"resolve.exports": "^2.0.3",
"rolldown-plugin-dts": "^0.28.0",
"rollup": "^4.59.0",
"rollup-plugin-license": "^3.7.1",
"sass": "^1.102.0",
"sass-embedded": "^1.100.0",
"sirv": "^3.0.2",
"strip-literal": "^4.0.0",
"terser": "^5.49.0",
"ufo": "^1.6.4",
"ws": "^8.21.1"
},
"peerDependencies": {
"@types/node": "^20.19.0 || >=22.12.0",
"@vitejs/devtools": "^0.4.0",
"esbuild": "^0.27.0 || ^0.28.0",
"jiti": ">=1.21.0",
"less": "^4.0.0",
"sass": "^1.70.0",
"sass-embedded": "^1.70.0",
"stylus": ">=0.54.8",
"sugarss": "^5.0.0",
"terser": "^5.16.0",
"tsx": "^4.8.1",
"yaml": "^2.4.2"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
},
"@vitejs/devtools": {
"optional": true
},
"esbuild": {
"optional": true
},
"jiti": {
"optional": true
},
"sass": {
"optional": true
},
"sass-embedded": {
"optional": true
},
"stylus": {
"optional": true
},
"less": {
"optional": true
},
"sugarss": {
"optional": true
},
"terser": {
"optional": true
},
"tsx": {
"optional": true
},
"yaml": {
"optional": true
}
},
"optionalDependencies": {
"fsevents": "~2.3.3"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"//": "READ CONTRIBUTING.md to understand what to put under deps vs. devDeps!",
"scripts": {
"dev": "premove dist && pnpm build-bundle -w",
"build": "premove dist && pnpm build-bundle && pnpm build-types",
"build-bundle": "rolldown --config rolldown.config.ts",
"build-types": "pnpm build-types-roll && pnpm build-types-check",
"build-types-roll": "rolldown --config rolldown.dts.config.ts",
"build-types-check": "tsc --project tsconfig.check.json",
"typecheck": "tsc && tsc -p src/node && tsc -p src/client && tsc -p src/module-runner && tsc -p src/shared && tsc -p src/node/__tests_dts__ && tsc -p src/module-runner/__tests_dts__",
"lint": "eslint --cache --ext .ts src/**",
"format": "oxfmt",
"generate-target": "tsx scripts/generateTarget.ts"
}
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"blake2s.d.ts","sourceRoot":"","sources":["../src/blake2s.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,GAAG,IAAI,KAAK,EAAE,GAAG,IAAI,KAAK,EAAE,MAAM,aAAa,CAAC;AAEzD,OAAO,EAAE,OAAO,IAAI,GAAG,EAAE,OAAO,IAAI,GAAG,EAAE,QAAQ,IAAI,UAAU,EAAE,MAAM,aAAa,CAAC;AACrF,+DAA+D;AAC/D,eAAO,MAAM,MAAM,EAAE,WAAuB,CAAC;AAC7C,+DAA+D;AAC/D,eAAO,MAAM,GAAG,EAAE,OAAO,KAAa,CAAC;AACvC,+DAA+D;AAC/D,eAAO,MAAM,GAAG,EAAE,OAAO,KAAa,CAAC;AACvC,+DAA+D;AAC/D,eAAO,MAAM,QAAQ,EAAE,OAAO,UAAuB,CAAC;AACtD,+DAA+D;AAC/D,eAAO,MAAM,OAAO,EAAE,OAAO,GAAS,CAAC;AACvC,+DAA+D;AAC/D,eAAO,MAAM,OAAO,EAAE,OAAO,GAAS,CAAC"}

View File

@@ -0,0 +1,4 @@
function _checkPrivateRedeclaration(e, t) {
if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
}
module.exports = _checkPrivateRedeclaration, module.exports.__esModule = true, module.exports["default"] = module.exports;

View File

@@ -0,0 +1,133 @@
import { util } from "./helpers/util.js";
export const ZodIssueCode = util.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite",
]);
export const quotelessJson = (obj) => {
const json = JSON.stringify(obj, null, 2);
return json.replace(/"([^"]+)":/g, "$1:");
};
export class ZodError extends Error {
get errors() {
return this.issues;
}
constructor(issues) {
super();
this.issues = [];
this.addIssue = (sub) => {
this.issues = [...this.issues, sub];
};
this.addIssues = (subs = []) => {
this.issues = [...this.issues, ...subs];
};
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) {
// eslint-disable-next-line ban/ban
Object.setPrototypeOf(this, actualProto);
}
else {
this.__proto__ = actualProto;
}
this.name = "ZodError";
this.issues = issues;
}
format(_mapper) {
const mapper = _mapper ||
function (issue) {
return issue.message;
};
const fieldErrors = { _errors: [] };
const processError = (error) => {
for (const issue of error.issues) {
if (issue.code === "invalid_union") {
issue.unionErrors.map(processError);
}
else if (issue.code === "invalid_return_type") {
processError(issue.returnTypeError);
}
else if (issue.code === "invalid_arguments") {
processError(issue.argumentsError);
}
else if (issue.path.length === 0) {
fieldErrors._errors.push(mapper(issue));
}
else {
let curr = fieldErrors;
let i = 0;
while (i < issue.path.length) {
const el = issue.path[i];
const terminal = i === issue.path.length - 1;
if (!terminal) {
curr[el] = curr[el] || { _errors: [] };
// if (typeof el === "string") {
// curr[el] = curr[el] || { _errors: [] };
// } else if (typeof el === "number") {
// const errorArray: any = [];
// errorArray._errors = [];
// curr[el] = curr[el] || errorArray;
// }
}
else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i++;
}
}
}
};
processError(this);
return fieldErrors;
}
static assert(value) {
if (!(value instanceof ZodError)) {
throw new Error(`Not a ZodError: ${value}`);
}
}
toString() {
return this.message;
}
get message() {
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
}
get isEmpty() {
return this.issues.length === 0;
}
flatten(mapper = (issue) => issue.message) {
const fieldErrors = Object.create(null);
const formErrors = [];
for (const sub of this.issues) {
if (sub.path.length > 0) {
const firstEl = sub.path[0];
fieldErrors[firstEl] = fieldErrors[firstEl] || [];
fieldErrors[firstEl].push(mapper(sub));
}
else {
formErrors.push(mapper(sub));
}
}
return { formErrors, fieldErrors };
}
get formErrors() {
return this.flatten();
}
}
ZodError.create = (issues) => {
const error = new ZodError(issues);
return error;
};

View File

@@ -0,0 +1,66 @@
'use strict'
module.exports = formatTime
const {
DATE_FORMAT,
DATE_FORMAT_SIMPLE
} = require('../constants')
const dateformat = require('dateformat')
const createDate = require('./create-date')
const isValidDate = require('./is-valid-date')
/**
* Converts a given `epoch` to a desired display format.
*
* @param {number|string} epoch The time to convert. May be any value that is
* valid for `new Date()`.
* @param {boolean|string} [translateTime=false] When `false`, the given `epoch`
* will simply be returned. When `true`, the given `epoch` will be converted
* to a string at UTC using the `DATE_FORMAT_SIMPLE` constant. If `translateTime` is
* a string, the following rules are available:
*
* - `<format string>`: The string is a literal format string. This format
* string will be used to interpret the `epoch` and return a display string
* at UTC.
* - `SYS:STANDARD`: The returned display string will follow the `DATE_FORMAT`
* constant at the system's local timezone.
* - `SYS:<format string>`: The returned display string will follow the given
* `<format string>` at the system's local timezone.
* - `UTC:<format string>`: The returned display string will follow the given
* `<format string>` at UTC.
*
* @returns {number|string} The formatted time.
*/
function formatTime (epoch, translateTime = false) {
if (translateTime === false) {
return epoch
}
const instant = createDate(epoch)
// If the Date is invalid, do not attempt to format
if (!isValidDate(instant)) {
return epoch
}
if (translateTime === true) {
return dateformat(instant, DATE_FORMAT_SIMPLE)
}
const upperFormat = translateTime.toUpperCase()
if (upperFormat === 'SYS:STANDARD') {
return dateformat(instant, DATE_FORMAT)
}
const prefix = upperFormat.substr(0, 4)
if (prefix === 'SYS:' || prefix === 'UTC:') {
if (prefix === 'UTC:') {
return dateformat(instant, translateTime)
}
return dateformat(instant, translateTime.slice(4))
}
return dateformat(instant, `UTC:${translateTime}`)
}

View File

@@ -0,0 +1,2 @@
import { viteReactRefreshWrapperPlugin as reactRefreshWrapperPlugin } from "rolldown/experimental";
export { reactRefreshWrapperPlugin };

View File

@@ -0,0 +1,66 @@
import { Context, Struct, Validator } from '../struct.js';
import { Assign, ObjectSchema, ObjectType, PartialObjectSchema } from '../utils.js';
/**
* Create a new struct that combines the properties properties from multiple
* object or type structs. Its return type will match the first parameter's type.
*
* Like JavaScript's `Object.assign` utility.
*/
export declare function assign<A extends ObjectSchema, B extends ObjectSchema>(A: Struct<ObjectType<A>, A>, B: Struct<ObjectType<B>, B>): Struct<ObjectType<Assign<A, B>>, Assign<A, B>>;
export declare function assign<A extends ObjectSchema, B extends ObjectSchema, C extends ObjectSchema>(A: Struct<ObjectType<A>, A>, B: Struct<ObjectType<B>, B>, C: Struct<ObjectType<C>, C>): Struct<ObjectType<Assign<Assign<A, B>, C>>, Assign<Assign<A, B>, C>>;
export declare function assign<A extends ObjectSchema, B extends ObjectSchema, C extends ObjectSchema, D extends ObjectSchema>(A: Struct<ObjectType<A>, A>, B: Struct<ObjectType<B>, B>, C: Struct<ObjectType<C>, C>, D: Struct<ObjectType<D>, D>): Struct<ObjectType<Assign<Assign<Assign<A, B>, C>, D>>, Assign<Assign<Assign<A, B>, C>, D>>;
export declare function assign<A extends ObjectSchema, B extends ObjectSchema, C extends ObjectSchema, D extends ObjectSchema, E extends ObjectSchema>(A: Struct<ObjectType<A>, A>, B: Struct<ObjectType<B>, B>, C: Struct<ObjectType<C>, C>, D: Struct<ObjectType<D>, D>, E: Struct<ObjectType<E>, E>): Struct<ObjectType<Assign<Assign<Assign<Assign<A, B>, C>, D>, E>>, Assign<Assign<Assign<Assign<A, B>, C>, D>, E>>;
/**
* Define a new struct type with a custom validation function.
*/
export declare function define<T>(name: string, validator: Validator): Struct<T, null>;
/**
* Create a new struct based on an existing struct, but the value is allowed to
* be `undefined`. `log` will be called if the value is not `undefined`.
*/
export declare function deprecated<T>(struct: Struct<T>, log: (value: unknown, ctx: Context) => void): Struct<T>;
/**
* Create a struct with dynamic validation logic.
*
* The callback will receive the value currently being validated, and must
* return a struct object to validate it with. This can be useful to model
* validation logic that changes based on its input.
*/
export declare function dynamic<T>(fn: (value: unknown, ctx: Context) => Struct<T, any>): Struct<T, null>;
/**
* Create a struct with lazily evaluated validation logic.
*
* The first time validation is run with the struct, the callback will be called
* and must return a struct object to use. This is useful for cases where you
* want to have self-referential structs for nested data structures to avoid a
* circular definition problem.
*/
export declare function lazy<T>(fn: () => Struct<T, any>): Struct<T, null>;
/**
* Create a new struct based on an existing object struct, but excluding
* specific properties.
*
* Like TypeScript's `Omit` utility.
*/
export declare function omit<S extends ObjectSchema, K extends keyof S>(struct: Struct<ObjectType<S>, S>, keys: K[]): Struct<ObjectType<Omit<S, K>>, Omit<S, K>>;
/**
* Create a new struct based on an existing object struct, but with all of its
* properties allowed to be `undefined`.
*
* Like TypeScript's `Partial` utility.
*/
export declare function partial<S extends ObjectSchema>(struct: Struct<ObjectType<S>, S> | S): Struct<ObjectType<PartialObjectSchema<S>>, PartialObjectSchema<S>>;
/**
* Create a new struct based on an existing object struct, but only including
* specific properties.
*
* Like TypeScript's `Pick` utility.
*/
export declare function pick<S extends ObjectSchema, K extends keyof S>(struct: Struct<ObjectType<S>, S>, keys: K[]): Struct<ObjectType<Pick<S, K>>, Pick<S, K>>;
/**
* Define a new struct type with a custom validation function.
*
* @deprecated This function has been renamed to `define`.
*/
export declare function struct<T>(name: string, validator: Validator): Struct<T, null>;
//# sourceMappingURL=utilities.d.ts.map

View File

@@ -0,0 +1,15 @@
var log = require('./')
var net = require('net')
function createServer () {
var server = net.createServer()
setInterval(function () {}, 1000)
server.listen(0)
}
createServer()
createServer()
setTimeout(function () {
log()
}, 100)

View File

@@ -0,0 +1,4 @@
function _class_name_tdz_error(name) {
throw new ReferenceError("Class \"" + name + "\" cannot be referenced in computed property keys.");
}
export { _class_name_tdz_error as _ };

View File

@@ -0,0 +1,87 @@
/*
We purposely don't generate types for our plugin because TL;DR:
1) there's no real reason that anyone should do a typed import of our rules,
2) it would require us to change our code so there aren't as many inferred types
This type declaration exists as a hacky way to add a type to the export for our
internal packages that require it.
*** Long reason ***
When you turn on declaration files, TS requires all types to be "fully resolvable"
without changes to the code.
All of our lint rules `export default createRule(...)`, which means they all
implicitly reference the `TSESLint.Rule` type for the export.
TS wants to transpile each rule file to this `.d.ts` file:
```ts
import type { TSESLint } from '@typescript-eslint/utils';
declare const _default: TSESLint.RuleModule<TMessageIds, TOptions, TSESLint.RuleListener>;
export default _default;
```
Because we don't import `TSESLint` in most files, it means that TS would have to
insert a new import during the declaration emit to make this work.
However TS wants to avoid adding new imports to the file because a new module
could have type side-effects (like global augmentation) which could cause weird
type side-effects in the decl file that wouldn't exist in source TS file.
So TS errors on most of our rules with the following error:
```
The inferred type of 'default' cannot be named without a reference to
'../../../../node_modules/@typescript-eslint/utils/src/ts-eslint/Rule'.
This is likely not portable. A type annotation is necessary. ts(2742)
```
*/
/* eslint-disable no-restricted-syntax */
import type {
RuleModuleWithMetaDocs,
RuleRecommendation,
RuleRecommendationAcrossConfigs,
} from '@typescript-eslint/utils/ts-eslint';
interface ESLintPluginDocs {
/**
* Does the rule extend (or is it based off of) an ESLint code rule?
* Alternately accepts the name of the base rule, in case the rule has been renamed.
* This is only used for documentation purposes.
*/
extendsBaseRule?: boolean | string;
/**
* If a string config name, which starting config this rule is enabled in.
* If an object, which settings it has enabled in each of those configs.
*/
recommended?: RuleRecommendation | RuleRecommendationAcrossConfigs<unknown[]>;
/**
* Does the rule require us to create a full TypeScript Program in order for it
* to type-check code. This is only used for documentation purposes.
*/
requiresTypeChecking?: boolean;
}
type ESLintPluginRuleModule = RuleModuleWithMetaDocs<
string,
readonly unknown[],
ESLintPluginDocs
>;
type TypeScriptESLintRules = Record<
string,
RuleModuleWithMetaDocs<string, unknown[], ESLintPluginDocs>
>;
declare const rules: TypeScriptESLintRules;
declare namespace rules {
export type {
ESLintPluginDocs,
ESLintPluginRuleModule,
TypeScriptESLintRules,
};
}
export = rules;

View File

@@ -0,0 +1,62 @@
'use strict'
const bench = require('fastbench')
const pino = require('../')
const bunyan = require('bunyan')
const bole = require('bole')('bench')('child')
const fs = require('node:fs')
const dest = fs.createWriteStream('/dev/null')
const plogNodeStream = pino(dest).child({ a: 'property' })
delete require.cache[require.resolve('../')]
const plogDest = require('../')(pino.destination('/dev/null')).child({ a: 'property' })
delete require.cache[require.resolve('../')]
const plogMinLength = require('../')(pino.destination({ dest: '/dev/null', sync: false, minLength: 4096 }))
const max = 10
const blog = bunyan.createLogger({
name: 'myapp',
streams: [{
level: 'trace',
stream: dest
}]
}).child({ a: 'property' })
require('bole').output({
level: 'info',
stream: dest
}).setFastTime(true)
const run = bench([
function benchBunyanChild (cb) {
for (var i = 0; i < max; i++) {
blog.info({ hello: 'world' })
}
setImmediate(cb)
},
function benchBoleChild (cb) {
for (var i = 0; i < max; i++) {
bole.info({ hello: 'world' })
}
setImmediate(cb)
},
function benchPinoChild (cb) {
for (var i = 0; i < max; i++) {
plogDest.info({ hello: 'world' })
}
setImmediate(cb)
},
function benchPinoMinLengthChild (cb) {
for (var i = 0; i < max; i++) {
plogMinLength.info({ hello: 'world' })
}
setImmediate(cb)
},
function benchPinoNodeStreamChild (cb) {
for (var i = 0; i < max; i++) {
plogNodeStream.info({ hello: 'world' })
}
setImmediate(cb)
}
], 10000)
run(run)

View File

@@ -0,0 +1,23 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABILITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
interface RegExp {
/**
* Returns a Boolean value indicating the state of the unicodeSets flag (v) used with a regular expression.
* Default is false. Read-only.
*/
readonly unicodeSets: boolean;
}

View File

@@ -0,0 +1,20 @@
declare const _default: {
extends: string[];
rules: {
'@typescript-eslint/adjacent-overload-signatures': "error";
'@typescript-eslint/array-type': "error";
'@typescript-eslint/ban-tslint-comment': "error";
'@typescript-eslint/class-literal-property-style': "error";
'@typescript-eslint/consistent-generic-constructors': "error";
'@typescript-eslint/consistent-indexed-object-style': "error";
'@typescript-eslint/consistent-type-assertions': "error";
'@typescript-eslint/consistent-type-definitions': "error";
'@typescript-eslint/no-confusing-non-null-assertion': "error";
'no-empty-function': "off";
'@typescript-eslint/no-empty-function': "error";
'@typescript-eslint/no-inferrable-types': "error";
'@typescript-eslint/prefer-for-of': "error";
'@typescript-eslint/prefer-function-type': "error";
};
};
export = _default;

View File

@@ -0,0 +1,101 @@
/**
* @fileoverview Rule to flag when initializing to undefined
* @author Ilya Volodin
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const CONSTANT_BINDINGS = new Set(["const", "using", "await using"]);
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Disallow initializing variables to `undefined`",
recommended: false,
frozen: true,
url: "https://eslint.org/docs/latest/rules/no-undef-init",
},
schema: [],
fixable: "code",
messages: {
unnecessaryUndefinedInit:
"It's not necessary to initialize '{{name}}' to undefined.",
},
},
create(context) {
const sourceCode = context.sourceCode;
return {
VariableDeclarator(node) {
const name = sourceCode.getText(node.id),
init = node.init && node.init.name,
scope = sourceCode.getScope(node),
undefinedVar = astUtils.getVariableByName(
scope,
"undefined",
),
shadowed = undefinedVar && undefinedVar.defs.length > 0,
lastToken = sourceCode.getLastToken(node);
if (
init === "undefined" &&
!CONSTANT_BINDINGS.has(node.parent.kind) &&
!shadowed
) {
context.report({
node,
messageId: "unnecessaryUndefinedInit",
data: { name },
fix(fixer) {
if (node.parent.kind === "var") {
return null;
}
if (
node.id.type === "ArrayPattern" ||
node.id.type === "ObjectPattern"
) {
// Don't fix destructuring assignment to `undefined`.
return null;
}
if (
sourceCode.commentsExistBetween(
node.id,
lastToken,
)
) {
return null;
}
return fixer.removeRange([
node.id.range[1],
node.range[1],
]);
},
});
}
},
};
},
};

View File

@@ -0,0 +1,9 @@
import * as ts from 'typescript';
/**
* @param type Type being checked by name.
* @param allowAny Whether to consider `any` and `unknown` to match.
* @param allowedNames Symbol names checking on the type.
* @param matchAnyInstead Whether to instead just check if any parts match, rather than all parts.
* @returns Whether the type is, extends, or contains the allowed names (or all matches the allowed names, if mustMatchAll is true).
*/
export declare function containsAllTypesByName(type: ts.Type, allowAny: boolean, allowedNames: Set<string>, matchAnyInstead?: boolean): boolean;

View File

@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright 2017 Andrey Sitnik <andrey@sitnik.ru>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,8 @@
export default function (
condition: unknown,
message?: string,
): asserts condition {
if (!condition) {
throw new Error(message || 'Assertion failed');
}
}