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,73 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isHash = exports.validateObject = exports.memoized = exports.notImplemented = exports.createHmacDrbg = exports.bitMask = exports.bitSet = exports.bitGet = exports.bitLen = exports.aInRange = exports.inRange = exports.asciiToBytes = exports.copyBytes = exports.equalBytes = exports.ensureBytes = exports.numberToVarBytesBE = exports.numberToBytesLE = exports.numberToBytesBE = exports.bytesToNumberLE = exports.bytesToNumberBE = exports.hexToNumber = exports.numberToHexUnpadded = exports.abool = exports.utf8ToBytes = exports.randomBytes = exports.isBytes = exports.hexToBytes = exports.concatBytes = exports.bytesToUtf8 = exports.bytesToHex = exports.anumber = exports.abytes = void 0;
/**
* Deprecated module: moved from curves/abstract/utils.js to curves/utils.js
* @module
*/
const u = require("../utils.js");
/** @deprecated moved to `@noble/curves/utils.js` */
exports.abytes = u.abytes;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.anumber = u.anumber;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.bytesToHex = u.bytesToHex;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.bytesToUtf8 = u.bytesToUtf8;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.concatBytes = u.concatBytes;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.hexToBytes = u.hexToBytes;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.isBytes = u.isBytes;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.randomBytes = u.randomBytes;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.utf8ToBytes = u.utf8ToBytes;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.abool = u.abool;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.numberToHexUnpadded = u.numberToHexUnpadded;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.hexToNumber = u.hexToNumber;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.bytesToNumberBE = u.bytesToNumberBE;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.bytesToNumberLE = u.bytesToNumberLE;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.numberToBytesBE = u.numberToBytesBE;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.numberToBytesLE = u.numberToBytesLE;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.numberToVarBytesBE = u.numberToVarBytesBE;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.ensureBytes = u.ensureBytes;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.equalBytes = u.equalBytes;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.copyBytes = u.copyBytes;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.asciiToBytes = u.asciiToBytes;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.inRange = u.inRange;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.aInRange = u.aInRange;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.bitLen = u.bitLen;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.bitGet = u.bitGet;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.bitSet = u.bitSet;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.bitMask = u.bitMask;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.createHmacDrbg = u.createHmacDrbg;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.notImplemented = u.notImplemented;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.memoized = u.memoized;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.validateObject = u.validateObject;
/** @deprecated moved to `@noble/curves/utils.js` */
exports.isHash = u.isHash;
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1,15 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
import { util } from "../helpers/util.js";
test("void", () => {
const v = z.void();
v.parse(undefined);
expect(() => v.parse(null)).toThrow();
expect(() => v.parse("")).toThrow();
type v = z.infer<typeof v>;
util.assertEqual<v, void>(true);
});

View File

@@ -0,0 +1,595 @@
/*! *****************************************************************************
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 Array<T> {
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find<S extends T>(predicate: (value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined;
find(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): number;
/**
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: T, start?: number, end?: number): this;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions & Intl.DateTimeFormatOptions): string;
}
interface ArrayConstructor {
/**
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
*/
from<T>(arrayLike: ArrayLike<T>): T[];
/**
* Creates an array from an iterable object.
* @param arrayLike An array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): U[];
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of<T>(...items: T[]): T[];
}
interface DateConstructor {
new (value: number | string | Date): Date;
}
interface Function {
/**
* Returns the name of the function. Function names are read-only and can not be changed.
*/
readonly name: string;
}
interface Math {
/**
* Returns the number of leading zero bits in the 32-bit binary representation of a number.
* @param x A numeric expression.
*/
clz32(x: number): number;
/**
* Returns the result of 32-bit multiplication of two numbers.
* @param x First number
* @param y Second number
*/
imul(x: number, y: number): number;
/**
* Returns the sign of x, indicating whether x is positive, negative, or zero.
* @param x The numeric expression to test
*/
sign(x: number): number;
/**
* Returns the base 10 logarithm of a number.
* @param x A numeric expression.
*/
log10(x: number): number;
/**
* Returns the base 2 logarithm of a number.
* @param x A numeric expression.
*/
log2(x: number): number;
/**
* Returns the natural logarithm of 1 + x.
* @param x A numeric expression.
*/
log1p(x: number): number;
/**
* Returns the result of (e^x - 1), which is an implementation-dependent approximation to
* subtracting 1 from the exponential function of x (e raised to the power of x, where e
* is the base of the natural logarithms).
* @param x A numeric expression.
*/
expm1(x: number): number;
/**
* Returns the hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
cosh(x: number): number;
/**
* Returns the hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
sinh(x: number): number;
/**
* Returns the hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
tanh(x: number): number;
/**
* Returns the inverse hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
acosh(x: number): number;
/**
* Returns the inverse hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
asinh(x: number): number;
/**
* Returns the inverse hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
atanh(x: number): number;
/**
* Returns the square root of the sum of squares of its arguments.
* @param values Values to compute the square root for.
* If no arguments are passed, the result is +0.
* If there is only one argument, the result is the absolute value.
* If any argument is +Infinity or -Infinity, the result is +Infinity.
* If any argument is NaN, the result is NaN.
* If all arguments are either +0 or 0, the result is +0.
*/
hypot(...values: number[]): number;
/**
* Returns the integral part of the numeric expression x, removing any fractional digits.
* If x is already an integer, the result is x.
* @param x A numeric expression.
*/
trunc(x: number): number;
/**
* Returns the nearest single precision float representation of a number.
* @param x A numeric expression.
*/
fround(x: number): number;
/**
* Returns an implementation-dependent approximation to the cube root of number.
* @param x A numeric expression.
*/
cbrt(x: number): number;
}
interface NumberConstructor {
/**
* The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1
* that is representable as a Number value, which is approximately:
* 2.2204460492503130808472633361816 x 1016.
*/
readonly EPSILON: number;
/**
* Returns true if passed value is finite.
* Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
isFinite(number: unknown): boolean;
/**
* Returns true if the value passed is an integer, false otherwise.
* @param number A numeric value.
*/
isInteger(number: unknown): boolean;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
* number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
*/
isNaN(number: unknown): boolean;
/**
* Returns true if the value passed is a safe integer.
* @param number A numeric value.
*/
isSafeInteger(number: unknown): boolean;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
* a Number value.
* The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 1.
*/
readonly MAX_SAFE_INTEGER: number;
/**
* The value of the smallest integer n such that n and n 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 ((2^53 1)).
*/
readonly MIN_SAFE_INTEGER: number;
/**
* Converts a string to a floating-point number.
* @param string A string that contains a floating-point number.
*/
parseFloat(string: string): number;
/**
* Converts A string to an integer.
* @param string A string to convert into a number.
* @param radix A value between 2 and 36 that specifies the base of the number in `string`.
* If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.
* All other strings are considered decimal.
*/
parseInt(string: string, radix?: number): number;
}
interface ObjectConstructor {
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source The source object from which to copy properties.
*/
assign<T extends {}, U>(target: T, source: U): T & U;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
*/
assign<T extends {}, U, V>(target: T, source1: U, source2: V): T & U & V;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
* @param source3 The third source object from which to copy properties.
*/
assign<T extends {}, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param sources One or more source objects from which to copy properties
*/
assign(target: object, ...sources: any[]): any;
/**
* Returns an array of all symbol properties found directly on object o.
* @param o Object to retrieve the symbols from.
*/
getOwnPropertySymbols(o: any): symbol[];
/**
* Returns the names of the enumerable string properties and methods of an object.
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
keys(o: {}): string[];
/**
* Returns true if the values are the same value, false otherwise.
* @param value1 The first value.
* @param value2 The second value.
*/
is(value1: any, value2: any): boolean;
/**
* Sets the prototype of a specified object o to object proto or null. Returns the object o.
* @param o The object to change its prototype.
* @param proto The value of the new prototype or null.
*/
setPrototypeOf(o: any, proto: object | null): any;
}
interface ReadonlyArray<T> {
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find<S extends T>(predicate: (value: T, index: number, obj: readonly T[]) => value is S, thisArg?: any): S | undefined;
find(predicate: (value: T, index: number, obj: readonly T[]) => unknown, thisArg?: any): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: T, index: number, obj: readonly T[]) => unknown, thisArg?: any): number;
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions & Intl.DateTimeFormatOptions): string;
}
interface RegExp {
/**
* Returns a string indicating the flags of the regular expression in question. This field is read-only.
* The characters in this string are sequenced and concatenated in the following order:
*
* - "g" for global
* - "i" for ignoreCase
* - "m" for multiline
* - "u" for unicode
* - "y" for sticky
*
* If no flags are set, the value is the empty string.
*/
readonly flags: string;
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
*/
readonly sticky: boolean;
/**
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
*/
readonly unicode: boolean;
}
interface RegExpConstructor {
new (pattern: RegExp | string, flags?: string): RegExp;
(pattern: RegExp | string, flags?: string): RegExp;
}
interface String {
/**
* Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point
* value of the UTF-16 encoded code point starting at the string element at position pos in
* the String resulting from converting this object to a String.
* If there is no element at that position, the result is undefined.
* If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.
*/
codePointAt(pos: number): number | undefined;
/**
* Returns true if searchString appears as a substring of the result of converting this
* object to a String, at one or more positions that are
* greater than or equal to position; otherwise, returns false.
* @param searchString search string
* @param position If position is undefined, 0 is assumed, so as to search all of the String.
*/
includes(searchString: string, position?: number): boolean;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* endPosition length(this). Otherwise returns false.
*/
endsWith(searchString: string, endPosition?: number): boolean;
/**
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string;
/**
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
normalize(form?: string): string;
/**
* Returns a String value that is made from count copies appended together. If count is 0,
* the empty string is returned.
* @param count number of copies to append
*/
repeat(count: number): string;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* position. Otherwise returns false.
*/
startsWith(searchString: string, position?: number): boolean;
/**
* Returns an `<a>` HTML anchor element and sets the name attribute to the text value
* @deprecated A legacy feature for browser compatibility
* @param name
*/
anchor(name: string): string;
/**
* Returns a `<big>` HTML element
* @deprecated A legacy feature for browser compatibility
*/
big(): string;
/**
* Returns a `<blink>` HTML element
* @deprecated A legacy feature for browser compatibility
*/
blink(): string;
/**
* Returns a `<b>` HTML element
* @deprecated A legacy feature for browser compatibility
*/
bold(): string;
/**
* Returns a `<tt>` HTML element
* @deprecated A legacy feature for browser compatibility
*/
fixed(): string;
/**
* Returns a `<font>` HTML element and sets the color attribute value
* @deprecated A legacy feature for browser compatibility
*/
fontcolor(color: string): string;
/**
* Returns a `<font>` HTML element and sets the size attribute value
* @deprecated A legacy feature for browser compatibility
*/
fontsize(size: number): string;
/**
* Returns a `<font>` HTML element and sets the size attribute value
* @deprecated A legacy feature for browser compatibility
*/
fontsize(size: string): string;
/**
* Returns an `<i>` HTML element
* @deprecated A legacy feature for browser compatibility
*/
italics(): string;
/**
* Returns an `<a>` HTML element and sets the href attribute value
* @deprecated A legacy feature for browser compatibility
*/
link(url: string): string;
/**
* Returns a `<small>` HTML element
* @deprecated A legacy feature for browser compatibility
*/
small(): string;
/**
* Returns a `<strike>` HTML element
* @deprecated A legacy feature for browser compatibility
*/
strike(): string;
/**
* Returns a `<sub>` HTML element
* @deprecated A legacy feature for browser compatibility
*/
sub(): string;
/**
* Returns a `<sup>` HTML element
* @deprecated A legacy feature for browser compatibility
*/
sup(): string;
}
interface StringConstructor {
/**
* Return the String value whose elements are, in order, the elements in the List elements.
* If length is 0, the empty string is returned.
*/
fromCodePoint(...codePoints: number[]): string;
/**
* String.raw is usually used as a tag function of a Tagged Template String. When called as
* such, the first argument will be a well formed template call site object and the rest
* parameter will contain the substitution values. It can also be called directly, for example,
* to interleave strings and values from your own tag function, and in this case the only thing
* it needs from the first argument is the raw property.
* @param template A well-formed template string call site representation.
* @param substitutions A set of substitution values.
*/
raw(template: { raw: readonly string[] | ArrayLike<string>; }, ...substitutions: any[]): string;
}
interface Int8Array<TArrayBuffer extends ArrayBufferLike> {
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
}
interface Uint8Array<TArrayBuffer extends ArrayBufferLike> {
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
}
interface Uint8ClampedArray<TArrayBuffer extends ArrayBufferLike> {
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
}
interface Int16Array<TArrayBuffer extends ArrayBufferLike> {
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
}
interface Uint16Array<TArrayBuffer extends ArrayBufferLike> {
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
}
interface Int32Array<TArrayBuffer extends ArrayBufferLike> {
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
}
interface Uint32Array<TArrayBuffer extends ArrayBufferLike> {
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
}
interface Float32Array<TArrayBuffer extends ArrayBufferLike> {
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
}
interface Float64Array<TArrayBuffer extends ArrayBufferLike> {
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"ed25519.d.ts","sourceRoot":"","sources":["../src/ed25519.ts"],"names":[],"mappings":"AAUA,OAAO,EAAa,KAAK,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,EACL,iBAAiB,EAEjB,KAAK,OAAO,EAEZ,KAAK,YAAY,EAClB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAIL,KAAK,SAAS,EACd,KAAK,aAAa,EAClB,KAAK,SAAS,EACd,KAAK,YAAY,EAClB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAOL,KAAK,MAAM,EACZ,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAc,KAAK,cAAc,IAAI,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACvF,OAAO,EAA4C,KAAK,GAAG,EAAE,MAAM,YAAY,CAAC;AA+FhF;;;;;;;;;GASG;AACH,eAAO,MAAM,OAAO,EAAE,OAAmE,CAAC;AAY1F,8DAA8D;AAC9D,eAAO,MAAM,UAAU,EAAE,OAIlB,CAAC;AAER,4FAA4F;AAC5F,eAAO,MAAM,SAAS,EAAE,OAMlB,CAAC;AAEP;;;;;;;;;GASG;AACH,eAAO,MAAM,MAAM,EAAE,QAYjB,CAAC;AA0EL,2DAA2D;AAC3D,eAAO,MAAM,cAAc,EAAE,SAAS,CAAC,MAAM,CAavC,CAAC;AA6BP,KAAK,aAAa,GAAG,YAAY,CAAC;AAsClC;;;;;;;;GAQG;AACH,cAAM,eAAgB,SAAQ,iBAAiB,CAAC,eAAe,CAAC;IAI9D,MAAM,CAAC,IAAI,EAAE,eAAe,CACwC;IAEpE,MAAM,CAAC,IAAI,EAAE,eAAe,CACwC;IAEpE,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,CACM;IAE/B,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,CACM;gBAEnB,EAAE,EAAE,aAAa;IAI7B,MAAM,CAAC,UAAU,CAAC,EAAE,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,eAAe;IAI3D,SAAS,CAAC,UAAU,CAAC,KAAK,EAAE,eAAe,GAAG,IAAI;IAIlD,SAAS,CAAC,IAAI,CAAC,EAAE,EAAE,YAAY,GAAG,eAAe;IAIjD,wFAAwF;IACxF,MAAM,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,GAAG,eAAe;IAI7C,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,UAAU,GAAG,eAAe;IA4BpD;;;;OAIG;IACH,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,eAAe;IAIzC,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,eAAe,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,eAAe;IAIzE;;;OAGG;IACH,OAAO,IAAI,UAAU;IA4BrB;;;OAGG;IACH,MAAM,CAAC,KAAK,EAAE,eAAe,GAAG,OAAO;IAWvC,GAAG,IAAI,OAAO;CAGf;AAED,eAAO,MAAM,YAAY,EAAE;IACzB,KAAK,EAAE,OAAO,eAAe,CAAC;CACF,CAAC;AAE/B,gEAAgE;AAChE,eAAO,MAAM,mBAAmB,EAAE,aAAa,CAAC,MAAM,CAUrD,CAAC;AAUF;;;;;GAKG;AACH,eAAO,MAAM,wBAAwB,EAAE,MAAM,EAS5C,CAAC;AAEF,mDAAmD;AACnD,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,GAAG,GAAG,UAAU,CAElE;AACD,mDAAmD;AACnD,eAAO,MAAM,mBAAmB,EAAE,OAAO,sBAA+C,CAAC;AAEzF,yDAAyD;AACzD,wBAAgB,uBAAuB,CAAC,WAAW,EAAE,UAAU,GAAG,UAAU,CAE3E;AAED,2CAA2C;AAC3C,eAAO,MAAM,cAAc,EAAE,OAAO,eAAiC,CAAC;AACtE,mFAAmF;AACnF,eAAO,MAAM,WAAW,EAAE,SAAS,CAAC,MAAM,CAAwD,CAAC;AACnG,mFAAmF;AACnF,eAAO,MAAM,aAAa,EAAE,SAAS,CAAC,MAAM,CACX,CAAC;AAClC,KAAK,UAAU,GAAG,CAAC,GAAG,EAAE,UAAU,EAAE,OAAO,EAAE,YAAY,KAAK,eAAe,CAAC;AAC9E,wFAAwF;AACxF,eAAO,MAAM,kBAAkB,EAAE,UACiB,CAAC;AACnD,wFAAwF;AACxF,eAAO,MAAM,oBAAoB,EAAE,UACe,CAAC"}

View File

@@ -0,0 +1 @@
{"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../../../src/api/node/node.ts"],"names":[],"mappings":"AAAA,OAAO,EAEH,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACrB,KAAK,IAAI,EAET,KAAK,IAAI,EACT,UAAU,EAEb,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAEpD,OAAO,EACH,UAAU,EACV,cAAc,EACjB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEH,KAAK,cAAc,EACnB,KAAK,WAAW,EACnB,MAAM,0BAA0B,CAAC;AAelC,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAQnG,qBAAa,gBAAiB,SAAQ,UAAW,YAAW,cAAc;IACtE,QAAQ,CAAC,KAAK,EAAE,CAAC,UAAU,GAAG,cAAc,CAAC,EAAE,CAAC;IAChD,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,yBAAyB,EAAE,MAAM,CAAC;IAC3C,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;IACpC,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC;IACrC,QAAQ,CAAC,qBAAqB,EAAE,MAAM,CAAC;IACvC,QAAQ,CAAC,QAAQ,EAAE,WAAW,CAAC;IAC/B,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,SAAS,CAAC;IAC9C,OAAO,CAAC,WAAW,CAAgC;IACnD,OAAO,CAAC,WAAW,CAAqB;IACxC,OAAO,CAAC,sBAAsB,CAAuC;IACrE,OAAO,CAAC,8BAA8B,CAAuC;IAC7E,OAAO,CAAC,6BAA6B,CAAuC;IAC5E,OAAO,CAAC,cAAc,CAA8B;IACpD,OAAO,CAAC,0BAA0B,CAA8B;IAChE,OAAO,CAAC,yBAAyB,CAAgC;gBAErD,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,CAAC,EAAE,eAAe;IAmB5E,kBAAkB,CAAC,oBAAoB,EAAE,MAAM,GAAG,SAAS,aAAa,EAAE;IAoB1E,kBAAkB,CAAC,oBAAoB,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE;IAejE,eAAe,CAAC,oBAAoB,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE;IAchE,gBAAgB;IAChB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IA0B3C,OAAO,KAAK,kBAAkB,GAE7B;IAED,IAAI,QAAQ,IAAI,MAAM,CAGrB;IAED,IAAI,IAAI,IAAI,MAAM,CAGjB;IAED,IAAI,eAAe,IAAI,MAAM,CAE5B;IAED,IAAI,UAAU,IAAI,MAAM,CAEvB;IAED,IAAI,eAAe,IAAI,SAAS,aAAa,EAAE,CAM9C;IAED,IAAI,uBAAuB,IAAI,SAAS,aAAa,EAAE,CAMtD;IAED,IAAI,sBAAsB,IAAI,SAAS,aAAa,EAAE,CAMrD;IAED,IAAI,OAAO,IAAI,SAAS,IAAI,EAAE,CAM7B;IAED,IAAI,mBAAmB,IAAI,SAAS,IAAI,EAAE,CAMzC;IAED,IAAI,kBAAkB,IAAI,SAAS,MAAM,EAAE,CAM1C;IAED,IAAI,uBAAuB,IAAI,IAAI,GAAG,IAAI,GAAG,SAAS,CAKrD;IAED,IAAI,iBAAiB,IAAI,OAAO,CAE/B;IAED,IAAI,IAAI,IAAI,MAAM,CAKjB;IAID,aAAa,IAAI,SAAS,MAAM,EAAE;IAIlC,6BAA6B,CAAC,QAAQ,EAAE,MAAM,GAAG,gBAAgB;IAMjE,6BAA6B,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM;CAOzE;AAyBD;;GAEG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,GAAG,IAAI,GAAG,SAAS,CAiBvG;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,UAAU,CAAC;IACjB,IAAI,EAAE,IAAI,CAAC;CACd;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,gBAAgB,CAehE;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,UAAU,GAAG,IAAI,CAGjD;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,CAK5C"}

View File

@@ -0,0 +1,601 @@
/**
* @fileoverview Flat config schema
* @author Nicholas C. Zakas
*/
"use strict";
//-----------------------------------------------------------------------------
// Requirements
//-----------------------------------------------------------------------------
const { normalizeSeverityToNumber } = require("../shared/severity");
//-----------------------------------------------------------------------------
// Type Definitions
//-----------------------------------------------------------------------------
/**
* @typedef ObjectPropertySchema
* @property {Function|string} merge The function or name of the function to call
* to merge multiple objects with this property.
* @property {Function|string} validate The function or name of the function to call
* to validate the value of this property.
*/
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
const ruleSeverities = new Map([
[0, 0],
["off", 0],
[1, 1],
["warn", 1],
[2, 2],
["error", 2],
]);
/**
* Check if a value is a non-null object.
* @param {any} value The value to check.
* @returns {boolean} `true` if the value is a non-null object.
*/
function isNonNullObject(value) {
return typeof value === "object" && value !== null;
}
/**
* Check if a value is a non-null non-array object.
* @param {any} value The value to check.
* @returns {boolean} `true` if the value is a non-null non-array object.
*/
function isNonArrayObject(value) {
return isNonNullObject(value) && !Array.isArray(value);
}
/**
* Check if a value is undefined.
* @param {any} value The value to check.
* @returns {boolean} `true` if the value is undefined.
*/
function isUndefined(value) {
return typeof value === "undefined";
}
/**
* Deeply merges two non-array objects.
* @param {Object} first The base object.
* @param {Object} second The overrides object.
* @param {Map<string, Map<string, Object>>} [mergeMap] Maps the combination of first and second arguments to a merged result.
* @returns {Object} An object with properties from both first and second.
*/
function deepMerge(first, second, mergeMap = new Map()) {
let secondMergeMap = mergeMap.get(first);
if (secondMergeMap) {
const result = secondMergeMap.get(second);
if (result) {
// If this combination of first and second arguments has been already visited, return the previously created result.
return result;
}
} else {
secondMergeMap = new Map();
mergeMap.set(first, secondMergeMap);
}
/*
* First create a result object where properties from the second object
* overwrite properties from the first. This sets up a baseline to use
* later rather than needing to inspect and change every property
* individually.
*/
const result = {
...first,
...second,
};
delete result.__proto__; // eslint-disable-line no-proto -- don't merge own property "__proto__"
// Store the pending result for this combination of first and second arguments.
secondMergeMap.set(second, result);
for (const key of Object.keys(second)) {
// avoid hairy edge case
if (
key === "__proto__" ||
!Object.prototype.propertyIsEnumerable.call(first, key)
) {
continue;
}
const firstValue = first[key];
const secondValue = second[key];
if (isNonArrayObject(firstValue) && isNonArrayObject(secondValue)) {
result[key] = deepMerge(firstValue, secondValue, mergeMap);
} else if (isUndefined(secondValue)) {
result[key] = firstValue;
}
}
return result;
}
/**
* Normalizes the rule options config for a given rule by ensuring that
* it is an array and that the first item is 0, 1, or 2.
* @param {Array|string|number} ruleOptions The rule options config.
* @returns {Array} An array of rule options.
*/
function normalizeRuleOptions(ruleOptions) {
const finalOptions = Array.isArray(ruleOptions)
? ruleOptions.slice(0)
: [ruleOptions];
finalOptions[0] = ruleSeverities.get(finalOptions[0]);
return structuredClone(finalOptions);
}
/**
* Determines if an object has any methods.
* @param {Object} object The object to check.
* @returns {boolean} `true` if the object has any methods.
*/
function hasMethod(object) {
for (const key of Object.keys(object)) {
if (typeof object[key] === "function") {
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Assertions
//-----------------------------------------------------------------------------
/**
* The error type when a rule's options are configured with an invalid type.
*/
class InvalidRuleOptionsError extends Error {
/**
* @param {string} ruleId Rule name being configured.
* @param {any} value The invalid value.
*/
constructor(ruleId, value) {
super(
`Key "${ruleId}": Expected severity of "off", 0, "warn", 1, "error", or 2.`,
);
this.messageTemplate = "invalid-rule-options";
this.messageData = { ruleId, value };
}
}
/**
* Validates that a value is a valid rule options entry.
* @param {string} ruleId Rule name being configured.
* @param {any} value The value to check.
* @returns {void}
* @throws {InvalidRuleOptionsError} If the value isn't a valid rule options.
*/
function assertIsRuleOptions(ruleId, value) {
if (
typeof value !== "string" &&
typeof value !== "number" &&
!Array.isArray(value)
) {
throw new InvalidRuleOptionsError(ruleId, value);
}
}
/**
* The error type when a rule's severity is invalid.
*/
class InvalidRuleSeverityError extends Error {
/**
* @param {string} ruleId Rule name being configured.
* @param {any} value The invalid value.
*/
constructor(ruleId, value) {
super(
`Key "${ruleId}": Expected severity of "off", 0, "warn", 1, "error", or 2.`,
);
this.messageTemplate = "invalid-rule-severity";
this.messageData = { ruleId, value };
}
}
/**
* Validates that a value is valid rule severity.
* @param {string} ruleId Rule name being configured.
* @param {any} value The value to check.
* @returns {void}
* @throws {InvalidRuleSeverityError} If the value isn't a valid rule severity.
*/
function assertIsRuleSeverity(ruleId, value) {
const severity = ruleSeverities.get(value);
if (typeof severity === "undefined") {
throw new InvalidRuleSeverityError(ruleId, value);
}
}
/**
* Validates that a given string matches the "pluginName/memberPlaceholder" pattern.
* @param {string} value The string to check.
* @param {string} memberPlaceholder The placeholder for the member portion of the expected format in the error message.
* @returns {void}
* @throws {TypeError} If the string doesn't match the expected pattern.
*/
function assertIsPluginMemberName(value, memberPlaceholder) {
if (!/[\w\-@$]+(?:\/[\w\-$]+)+$/iu.test(value)) {
throw new TypeError(
`Expected string in the form "pluginName/${memberPlaceholder}" but found "${value}".`,
);
}
}
/**
* Validates that a value is an object.
* @param {any} value The value to check.
* @returns {void}
* @throws {TypeError} If the value isn't an object.
*/
function assertIsObject(value) {
if (!isNonNullObject(value)) {
throw new TypeError("Expected an object.");
}
}
/**
* The error type when there's an eslintrc-style options in a flat config.
*/
class IncompatibleKeyError extends Error {
/**
* @param {string} key The invalid key.
*/
constructor(key) {
super(
"This appears to be in eslintrc format rather than flat config format.",
);
this.messageTemplate = "eslintrc-incompat";
this.messageData = { key };
}
}
/**
* The error type when there's an eslintrc-style plugins array found.
*/
class IncompatiblePluginsError extends Error {
/**
* Creates a new instance.
* @param {Array<string>} plugins The plugins array.
*/
constructor(plugins) {
super(
"This appears to be in eslintrc format (array of strings) rather than flat config format (object).",
);
this.messageTemplate = "eslintrc-plugins";
this.messageData = { plugins };
}
}
//-----------------------------------------------------------------------------
// Low-Level Schemas
//-----------------------------------------------------------------------------
/** @type {ObjectPropertySchema} */
const booleanSchema = {
merge: "replace",
validate: "boolean",
};
const ALLOWED_SEVERITIES = new Set(["error", "warn", "off", 2, 1, 0]);
/** @type {ObjectPropertySchema} */
const disableDirectiveSeveritySchema = {
merge(first, second) {
const value = second === void 0 ? first : second;
if (typeof value === "boolean") {
return value ? "warn" : "off";
}
return normalizeSeverityToNumber(value);
},
validate(value) {
if (!(ALLOWED_SEVERITIES.has(value) || typeof value === "boolean")) {
throw new TypeError(
'Expected one of: "error", "warn", "off", 0, 1, 2, or a boolean.',
);
}
},
};
/** @type {ObjectPropertySchema} */
const unusedInlineConfigsSeveritySchema = {
merge(first, second) {
const value = second === void 0 ? first : second;
return normalizeSeverityToNumber(value);
},
validate(value) {
if (!ALLOWED_SEVERITIES.has(value)) {
throw new TypeError(
'Expected one of: "error", "warn", "off", 0, 1, or 2.',
);
}
},
};
/** @type {ObjectPropertySchema} */
const deepObjectAssignSchema = {
merge(first = {}, second = {}) {
return deepMerge(first, second);
},
validate: "object",
};
//-----------------------------------------------------------------------------
// High-Level Schemas
//-----------------------------------------------------------------------------
/** @type {ObjectPropertySchema} */
const languageOptionsSchema = {
merge(first = {}, second = {}) {
const result = deepMerge(first, second);
for (const [key, value] of Object.entries(result)) {
/*
* Special case: Because the `parser` property is an object, it should
* not be deep merged. Instead, it should be replaced if it exists in
* the second object. To make this more generic, we just check for
* objects with methods and replace them if they exist in the second
* object.
*/
if (isNonArrayObject(value)) {
if (hasMethod(value)) {
result[key] = second[key] ?? first[key];
continue;
}
// for other objects, make sure we aren't reusing the same object
result[key] = { ...result[key] };
continue;
}
}
return result;
},
validate: "object",
};
/** @type {ObjectPropertySchema} */
const languageSchema = {
merge: "replace",
validate(value) {
assertIsPluginMemberName(value, "languageName");
},
};
/** @type {ObjectPropertySchema} */
const pluginsSchema = {
merge(first = {}, second = {}) {
const keys = new Set([...Object.keys(first), ...Object.keys(second)]);
const result = {};
// manually validate that plugins are not redefined
for (const key of keys) {
// avoid hairy edge case
if (key === "__proto__") {
continue;
}
if (key in first && key in second && first[key] !== second[key]) {
throw new TypeError(`Cannot redefine plugin "${key}".`);
}
result[key] = second[key] || first[key];
}
return result;
},
validate(value) {
// first check the value to be sure it's an object
if (value === null || typeof value !== "object") {
throw new TypeError("Expected an object.");
}
// make sure it's not an array, which would mean eslintrc-style is used
if (Array.isArray(value)) {
throw new IncompatiblePluginsError(value);
}
// second check the keys to make sure they are objects
for (const key of Object.keys(value)) {
// avoid hairy edge case
if (key === "__proto__") {
continue;
}
if (value[key] === null || typeof value[key] !== "object") {
throw new TypeError(`Key "${key}": Expected an object.`);
}
}
},
};
/** @type {ObjectPropertySchema} */
const processorSchema = {
merge: "replace",
validate(value) {
if (typeof value === "string") {
assertIsPluginMemberName(value, "processorName");
} else if (value && typeof value === "object") {
if (
typeof value.preprocess !== "function" ||
typeof value.postprocess !== "function"
) {
throw new TypeError(
"Object must have a preprocess() and a postprocess() method.",
);
}
} else {
throw new TypeError("Expected an object or a string.");
}
},
};
/** @type {ObjectPropertySchema} */
const rulesSchema = {
merge(first = {}, second = {}) {
const result = {
...first,
...second,
};
for (const ruleId of Object.keys(result)) {
try {
// avoid hairy edge case
if (ruleId === "__proto__") {
/* eslint-disable-next-line no-proto -- Though deprecated, may still be present */
delete result.__proto__;
continue;
}
result[ruleId] = normalizeRuleOptions(result[ruleId]);
/*
* If either rule config is missing, then the correct
* config is already present and we just need to normalize
* the severity.
*/
if (!(ruleId in first) || !(ruleId in second)) {
continue;
}
const firstRuleOptions = normalizeRuleOptions(first[ruleId]);
const secondRuleOptions = normalizeRuleOptions(second[ruleId]);
/*
* If the second rule config only has a severity (length of 1),
* then use that severity and keep the rest of the options from
* the first rule config.
*/
if (secondRuleOptions.length === 1) {
result[ruleId] = [
secondRuleOptions[0],
...firstRuleOptions.slice(1),
];
continue;
}
/*
* In any other situation, then the second rule config takes
* precedence. That means the value at `result[ruleId]` is
* already correct and no further work is necessary.
*/
} catch (ex) {
throw new Error(`Key "${ruleId}": ${ex.message}`, {
cause: ex,
});
}
}
return result;
},
validate(value) {
assertIsObject(value);
/*
* We are not checking the rule schema here because there is no
* guarantee that the rule definition is present at this point. Instead
* we wait and check the rule schema during the finalization step
* of calculating a config.
*/
for (const ruleId of Object.keys(value)) {
// avoid hairy edge case
if (ruleId === "__proto__") {
continue;
}
const ruleOptions = value[ruleId];
assertIsRuleOptions(ruleId, ruleOptions);
if (Array.isArray(ruleOptions)) {
assertIsRuleSeverity(ruleId, ruleOptions[0]);
} else {
assertIsRuleSeverity(ruleId, ruleOptions);
}
}
},
};
/**
* Creates a schema that always throws an error. Useful for warning
* about eslintrc-style keys.
* @param {string} key The eslintrc key to create a schema for.
* @returns {ObjectPropertySchema} The schema.
*/
function createEslintrcErrorSchema(key) {
return {
merge: "replace",
validate() {
throw new IncompatibleKeyError(key);
},
};
}
const eslintrcKeys = [
"env",
"extends",
"globals",
"ignorePatterns",
"noInlineConfig",
"overrides",
"parser",
"parserOptions",
"reportUnusedDisableDirectives",
"root",
];
//-----------------------------------------------------------------------------
// Full schema
//-----------------------------------------------------------------------------
const flatConfigSchema = {
// eslintrc-style keys that should always error
...Object.fromEntries(
eslintrcKeys.map(key => [key, createEslintrcErrorSchema(key)]),
),
// flat config keys
settings: deepObjectAssignSchema,
linterOptions: {
schema: {
noInlineConfig: booleanSchema,
reportUnusedDisableDirectives: disableDirectiveSeveritySchema,
reportUnusedInlineConfigs: unusedInlineConfigsSeveritySchema,
},
},
language: languageSchema,
languageOptions: languageOptionsSchema,
processor: processorSchema,
plugins: pluginsSchema,
rules: rulesSchema,
};
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
module.exports = {
flatConfigSchema,
hasMethod,
assertIsRuleSeverity,
};

View File

@@ -0,0 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assert = assert;
// the base assert module doesn't use ts assertion syntax
function assert(value, message) {
if (value == null) {
throw new Error(message);
}
}

View File

@@ -0,0 +1,6 @@
"use strict";
function _class_check_private_static_access(receiver, classConstructor) {
if (receiver !== classConstructor) throw new TypeError("Private static access of wrong provenance");
}
exports._ = _class_check_private_static_access;

View File

@@ -0,0 +1,264 @@
declare module "node:inspector" {
import { EventEmitter } from "node:events";
/**
* The `inspector.Session` is used for dispatching messages to the V8 inspector
* back-end and receiving message responses and notifications.
*/
class Session extends EventEmitter {
/**
* Create a new instance of the inspector.Session class.
* The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend.
*/
constructor();
/**
* Connects a session to the inspector back-end.
*/
connect(): void;
/**
* Connects a session to the inspector back-end.
* An exception will be thrown if this API was not called on a Worker thread.
* @since v12.11.0
*/
connectToMainThread(): void;
/**
* Immediately close the session. All pending message callbacks will be called with an error.
* `session.connect()` will need to be called to be able to send messages again.
* Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints.
*/
disconnect(): void;
}
/**
* Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has
* started.
*
* If wait is `true`, will block until a client has connected to the inspect port
* and flow control has been passed to the debugger client.
*
* See the [security warning](https://nodejs.org/docs/latest-v26.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure)
* regarding the `host` parameter usage.
* @param port Port to listen on for inspector connections. Defaults to what was specified on the CLI.
* @param host Host to listen on for inspector connections. Defaults to what was specified on the CLI.
* @param wait Block until a client has connected. Defaults to what was specified on the CLI.
* @returns Disposable that calls `inspector.close()`.
*/
function open(port?: number, host?: string, wait?: boolean): Disposable;
/**
* Deactivate the inspector. Blocks until there are no active connections.
*/
function close(): void;
/**
* Return the URL of the active inspector, or `undefined` if there is none.
*
* ```console
* $ node --inspect -p 'inspector.url()'
* Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
* For help, see: https://nodejs.org/en/docs/inspector
* ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
*
* $ node --inspect=localhost:3000 -p 'inspector.url()'
* Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
* For help, see: https://nodejs.org/en/docs/inspector
* ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
*
* $ node -p 'inspector.url()'
* undefined
* ```
*/
function url(): string | undefined;
/**
* Blocks until a client (existing or connected later) has sent `Runtime.runIfWaitingForDebugger` command.
*
* An exception will be thrown if there is no active inspector.
* @since v12.7.0
*/
function waitForDebugger(): void;
// These methods are exposed by the V8 inspector console API (inspector/v8-console.h).
// The method signatures differ from those of the Node.js console, and are deliberately
// typed permissively.
interface InspectorConsole {
debug(...data: any[]): void;
error(...data: any[]): void;
info(...data: any[]): void;
log(...data: any[]): void;
warn(...data: any[]): void;
dir(...data: any[]): void;
dirxml(...data: any[]): void;
table(...data: any[]): void;
trace(...data: any[]): void;
group(...data: any[]): void;
groupCollapsed(...data: any[]): void;
groupEnd(...data: any[]): void;
clear(...data: any[]): void;
count(label?: any): void;
countReset(label?: any): void;
assert(value?: any, ...data: any[]): void;
profile(label?: any): void;
profileEnd(label?: any): void;
time(label?: any): void;
timeLog(label?: any): void;
timeStamp(label?: any): void;
}
/**
* An object to send messages to the remote inspector console.
* @since v11.0.0
*/
const console: InspectorConsole;
// DevTools protocol event broadcast methods
namespace Network {
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.requestWillBeSent` event to connected frontends. This event indicates that
* the application is about to send an HTTP request.
* @since v22.6.0
*/
function requestWillBeSent(params: RequestWillBeSentEventDataType): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.dataReceived` event to connected frontends, or buffers the data if
* `Network.streamResourceContent` command was not invoked for the given request yet.
*
* Also enables `Network.getResponseBody` command to retrieve the response data.
* @since v24.2.0
*/
function dataReceived(params: DataReceivedEventDataType): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Enables `Network.getRequestPostData` command to retrieve the request data.
* @since v24.3.0
*/
function dataSent(params: unknown): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.responseReceived` event to connected frontends. This event indicates that
* HTTP response is available.
* @since v22.6.0
*/
function responseReceived(params: ResponseReceivedEventDataType): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.loadingFinished` event to connected frontends. This event indicates that
* HTTP request has finished loading.
* @since v22.6.0
*/
function loadingFinished(params: LoadingFinishedEventDataType): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.loadingFailed` event to connected frontends. This event indicates that
* HTTP request has failed to load.
* @since v22.7.0
*/
function loadingFailed(params: LoadingFailedEventDataType): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.webSocketCreated` event to connected frontends. This event indicates that
* a WebSocket connection has been initiated.
* @since v24.7.0
*/
function webSocketCreated(params: WebSocketCreatedEventDataType): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.webSocketHandshakeResponseReceived` event to connected frontends.
* This event indicates that the WebSocket handshake response has been received.
* @since v24.7.0
*/
function webSocketHandshakeResponseReceived(params: WebSocketHandshakeResponseReceivedEventDataType): void;
/**
* This feature is only available with the `--experimental-network-inspection` flag enabled.
*
* Broadcasts the `Network.webSocketClosed` event to connected frontends.
* This event indicates that a WebSocket connection has been closed.
* @since v24.7.0
*/
function webSocketClosed(params: WebSocketClosedEventDataType): void;
}
namespace NetworkResources {
/**
* This feature is only available with the `--experimental-inspector-network-resource` flag enabled.
*
* The inspector.NetworkResources.put method is used to provide a response for a loadNetworkResource
* request issued via the Chrome DevTools Protocol (CDP).
* This is typically triggered when a source map is specified by URL, and a DevTools frontend—such as
* Chrome—requests the resource to retrieve the source map.
*
* This method allows developers to predefine the resource content to be served in response to such CDP requests.
*
* ```js
* const inspector = require('node:inspector');
* // By preemptively calling put to register the resource, a source map can be resolved when
* // a loadNetworkResource request is made from the frontend.
* async function setNetworkResources() {
* const mapUrl = 'http://localhost:3000/dist/app.js.map';
* const tsUrl = 'http://localhost:3000/src/app.ts';
* const distAppJsMap = await fetch(mapUrl).then((res) => res.text());
* const srcAppTs = await fetch(tsUrl).then((res) => res.text());
* inspector.NetworkResources.put(mapUrl, distAppJsMap);
* inspector.NetworkResources.put(tsUrl, srcAppTs);
* };
* setNetworkResources().then(() => {
* require('./dist/app');
* });
* ```
*
* For more details, see the official CDP documentation: [Network.loadNetworkResource](https://chromedevtools.github.io/devtools-protocol/tot/Network/#method-loadNetworkResource)
* @since v24.5.0
* @experimental
*/
function put(url: string, data: string): void;
}
namespace DOMStorage {
/**
* This feature is only available with the
* `--experimental-storage-inspection` flag enabled.
*
* Broadcasts the `DOMStorage.domStorageItemAdded` event to connected frontends.
* This event indicates that a new item has been added to the storage.
* @since v25.5.0
*/
function domStorageItemAdded(params: DomStorageItemAddedEventDataType): void;
/**
* This feature is only available with the
* `--experimental-storage-inspection` flag enabled.
*
* Broadcasts the `DOMStorage.domStorageItemRemoved` event to connected frontends.
* This event indicates that an item has been removed from the storage.
* @since v25.5.0
*/
function domStorageItemRemoved(params: DomStorageItemRemovedEventDataType): void;
/**
* This feature is only available with the
* `--experimental-storage-inspection` flag enabled.
* Broadcasts the `DOMStorage.domStorageItemUpdated` event to connected frontends.
* This event indicates that a storage item has been updated.
* @since v25.5.0
*/
function domStorageItemUpdated(params: DomStorageItemUpdatedEventDataType): void;
/**
* This feature is only available with the
* `--experimental-storage-inspection` flag enabled.
*
* Broadcasts the `DOMStorage.domStorageItemsCleared` event to connected
* frontends. This event indicates that all items have been cleared from the
* storage.
* @since v25.5.0
*/
function domStorageItemsCleared(params: DomStorageItemsClearedEventDataType): void;
/**
* This feature is only available with the
* `--experimental-storage-inspection` flag enabled.
* @since v25.5.0
*/
function registerStorage(params: unknown): void;
}
}
declare module "inspector" {
export * from "node:inspector";
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/api/sync/client.ts"],"names":[],"mappings":"AACA,OAAO,EACH,KAAK,aAAa,EAClB,KAAK,mBAAmB,EACxB,KAAK,kBAAkB,EAG1B,MAAM,eAAe,CAAC;AAEvB,OAAO,EAIH,eAAe,EACf,KAAK,UAAU,EAClB,MAAM,cAAc,CAAC;AAEtB,YAAY,EAAE,aAAa,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,CAAC;AAEvE,qBAAa,MAAM;IACf,OAAO,CAAC,OAAO,CAAiB;IAChC,OAAO,CAAC,OAAO,CAAqB;IACpC,OAAO,CAAC,MAAM,CAA8B;gBAEhC,OAAO,EAAE,aAAa;IAmDlC,UAAU,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,CAAC;IAWlD,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,UAAU,GAAG,SAAS;IAQ1E,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM;IAI7B,UAAU,CAAC,OAAO,EAAE,UAAU,GAAG,UAAU;IAI3C;;;;OAIG;IACH,aAAa,IAAI,UAAU;IAW3B,eAAe,IAAI,IAAI;IAOvB;;;;;OAKG;IACH,kBAAkB,IAAI,eAAe,GAAG,SAAS;IAIjD,OAAO,CAAC,YAAY;IAUpB,KAAK,IAAI,IAAI;CAGhB"}

View File

@@ -0,0 +1,4 @@
{
"main": "../../cjs/_tagged_template_literal.cjs",
"module": "../../esm/_tagged_template_literal.js"
}

View File

@@ -0,0 +1,4 @@
{
"main": "../../cjs/_possible_constructor_return.cjs",
"module": "../../esm/_possible_constructor_return.js"
}

View File

@@ -0,0 +1,15 @@
# prelude.ls [![Build Status](https://travis-ci.org/gkz/prelude-ls.png?branch=master)](https://travis-ci.org/gkz/prelude-ls)
is a functionally oriented utility library. It is powerful and flexible. Almost all of its functions are curried. It is written in, and is the recommended base library for, <a href="http://livescript.net">LiveScript</a>.
See **[the prelude.ls site](http://preludels.com)** for examples, a reference, and more.
You can install via npm `npm install prelude-ls`
### Development
`make test` to test
`make build` to build `lib` from `src`
`make build-browser` to build browser versions

View File

@@ -0,0 +1,109 @@
import { expect, test } from "vitest";
test("placeholder test", () => {
expect(2).toBe(2);
});
// test("overload types", () => {
// const schema = z.string().json();
// util.assertEqual<typeof schema, z.ZodString>(true);
// const schema2 = z.string().json(z.number());
// util.assertEqual<typeof schema2, z.ZodPipe<z.ZodTransform<any, string>, z.ZodNumber>>(true);
// const r2 = schema2.parse("12");
// util.assertEqual<number, typeof r2>(true);
// });
// test("parse string to json", async () => {
// const Env = z.object({
// myJsonConfig: z.string().jsonString(z.object({ foo: z.number() })),
// someOtherValue: z.string(),
// });
// expect(
// Env.parse({
// myJsonConfig: '{ "foo": 123 }',
// someOtherValue: "abc",
// })
// ).toEqual({
// myJsonConfig: { foo: 123 },
// someOtherValue: "abc",
// });
// const invalidValues = Env.safeParse({
// myJsonConfig: '{"foo": "not a number!"}',
// someOtherValue: null,
// });
// expect(JSON.parse(JSON.stringify(invalidValues))).toEqual({
// success: false,
// error: {
// name: "ZodError",
// issues: [
// {
// code: "invalid_type",
// expected: "number",
// input: "not a number!",
// received: "string",
// path: ["myJsonConfig", "foo"],
// message: "Expected number, received string",
// },
// {
// code: "invalid_type",
// expected: "string",
// input: null,
// received: "null",
// path: ["someOtherValue"],
// message: "Expected string, received null",
// },
// ],
// },
// });
// const invalidJsonSyntax = Env.safeParse({
// myJsonConfig: "This is not valid json",
// someOtherValue: null,
// });
// expect(JSON.parse(JSON.stringify(invalidJsonSyntax))).toMatchObject({
// success: false,
// error: {
// name: "ZodError",
// issues: [
// {
// code: "invalid_string",
// input: {
// _def: {
// catchall: {
// _def: {
// typeName: "ZodNever",
// },
// },
// typeName: "ZodObject",
// unknownKeys: "strip",
// },
// },
// validation: "json",
// message: "Invalid json",
// path: ["myJsonConfig"],
// },
// {
// code: "invalid_type",
// expected: "string",
// input: null,
// received: "null",
// path: ["someOtherValue"],
// message: "Expected string, received null",
// },
// ],
// },
// });
// });
// test("no argument", () => {
// const schema = z.string().json();
// util.assertEqual<typeof schema, z.ZodString>(true);
// z.string().json().parse(`{}`);
// z.string().json().parse(`null`);
// z.string().json().parse(`12`);
// z.string().json().parse(`{ "test": "test"}`);
// expect(() => z.string().json().parse(`asdf`)).toThrow();
// expect(() => z.string().json().parse(`{ "test": undefined }`)).toThrow();
// expect(() => z.string().json().parse(`{ "test": 12n }`)).toThrow();
// expect(() => z.string().json().parse(`{ test: "test" }`)).toThrow();
// });

View File

@@ -0,0 +1,7 @@
import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint';
export default _default;
/**
* A utility ruleset that will disable type-aware linting and all type-aware rules available in our project.
* @see {@link https://typescript-eslint.io/users/configs#disable-type-checked}
*/
declare function _default(_plugin: FlatConfig.Plugin, _parser: FlatConfig.Parser): FlatConfig.Config;

View File

@@ -0,0 +1,30 @@
/**
* @fileoverview Provides helper functions to start/stop the time measurements
* that are provided by the ESLint 'stats' option.
* @author Mara Kiefer <http://github.com/mnkiefer>
*/
"use strict";
/**
* Start time measurement
* @returns {[number, number]} t variable for tracking time
*/
function startTime() {
return process.hrtime();
}
/**
* End time measurement
* @param {[number, number]} t Variable for tracking time
* @returns {number} The measured time in milliseconds
*/
function endTime(t) {
const time = process.hrtime(t);
return time[0] * 1e3 + time[1] / 1e6;
}
module.exports = {
startTime,
endTime,
};

View File

@@ -0,0 +1,7 @@
import type { TSESLint } from '@typescript-eslint/utils';
export type MessageIds = 'preferIndexSignature' | 'preferIndexSignatureSuggestion' | 'preferRecord' | 'preferRecordSuggestion';
export type Options = ['index-signature' | 'record'];
declare const _default: TSESLint.RuleModule<MessageIds, Options, import("../../rules").ESLintPluginDocs, TSESLint.RuleListener> & {
name: string;
};
export default _default;

View File

@@ -0,0 +1,87 @@
import { FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';
import { NumberCodecConfig } from './common';
/**
* Returns an encoder for 32-bit floating-point numbers (`f32`).
*
* This encoder serializes `f32` values using 4 bytes.
* Floating-point values may lose precision when encoded.
*
* For more details, see {@link getF32Codec}.
*
* @param config - Optional configuration to specify endianness (little by default).
* @returns A `FixedSizeEncoder<number, 4>` for encoding `f32` values.
*
* @example
* Encoding an `f32` value.
* ```ts
* const encoder = getF32Encoder();
* const bytes = encoder.encode(-1.5); // 0x0000c0bf
* ```
*
* @see {@link getF32Codec}
*/
export declare const getF32Encoder: (config?: NumberCodecConfig) => FixedSizeEncoder<bigint | number, 4>;
/**
* Returns a decoder for 32-bit floating-point numbers (`f32`).
*
* This decoder deserializes `f32` values from 4 bytes.
* Some precision may be lost during decoding due to floating-point representation.
*
* For more details, see {@link getF32Codec}.
*
* @param config - Optional configuration to specify endianness (little by default).
* @returns A `FixedSizeDecoder<number, 4>` for decoding `f32` values.
*
* @example
* Decoding an `f32` value.
* ```ts
* const decoder = getF32Decoder();
* const value = decoder.decode(new Uint8Array([0x00, 0x00, 0xc0, 0xbf])); // -1.5
* ```
*
* @see {@link getF32Codec}
*/
export declare const getF32Decoder: (config?: NumberCodecConfig) => FixedSizeDecoder<number, 4>;
/**
* Returns a codec for encoding and decoding 32-bit floating-point numbers (`f32`).
*
* This codec serializes `f32` values using 4 bytes.
* Due to the IEEE 754 floating-point representation, some precision loss may occur.
*
* @param config - Optional configuration to specify endianness (little by default).
* @returns A `FixedSizeCodec<number, number, 4>` for encoding and decoding `f32` values.
*
* @example
* Encoding and decoding an `f32` value.
* ```ts
* const codec = getF32Codec();
* const bytes = codec.encode(-1.5); // 0x0000c0bf
* const value = codec.decode(bytes); // -1.5
* ```
*
* @example
* Using big-endian encoding.
* ```ts
* const codec = getF32Codec({ endian: Endian.Big });
* const bytes = codec.encode(-1.5); // 0xbfc00000
* ```
*
* @remarks
* `f32` values follow the IEEE 754 single-precision floating-point standard.
* Precision loss may occur for certain values.
*
* - If you need higher precision, consider using {@link getF64Codec}.
* - If you need integer values, consider using {@link getI32Codec} or {@link getU32Codec}.
*
* Separate {@link getF32Encoder} and {@link getF32Decoder} functions are available.
*
* ```ts
* const bytes = getF32Encoder().encode(-1.5);
* const value = getF32Decoder().decode(bytes);
* ```
*
* @see {@link getF32Encoder}
* @see {@link getF32Decoder}
*/
export declare const getF32Codec: (config?: NumberCodecConfig) => FixedSizeCodec<bigint | number, number, 4>;
//# sourceMappingURL=f32.d.ts.map

View File

@@ -0,0 +1,74 @@
{
"name": "secure-json-parse",
"version": "4.1.0",
"description": "JSON parse with prototype poisoning protection",
"main": "index.js",
"type": "commonjs",
"types": "types/index.d.ts",
"scripts": {
"benchmark": "cd benchmarks && npm install && npm run all",
"lint": "eslint",
"lint:fix": "eslint --fix",
"test": "nyc npm run test:unit && npm run test:typescript",
"test:unit": "tape \"test/*.test.js\"",
"test:typescript": "tsd",
"test:browser": "airtap test/*.test.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/fastify/secure-json-parse.git"
},
"author": "Eran Hammer <eran@sideway.com>",
"contributors": [
{
"name": "Matteo Collina",
"email": "hello@matteocollina.com"
},
{
"name": "Tomas Della Vedova",
"url": "http://delved.org"
},
{
"name": "Aras Abbasi",
"email": "aras.abbasi@gmail.com"
},
{
"name": "Frazer Smith",
"email": "frazer.dev@icloud.com",
"url": "https://github.com/fdawgs"
}
],
"keywords": [
"JSON",
"parse",
"safe",
"security",
"prototype",
"pollution"
],
"license": "BSD-3-Clause",
"bugs": {
"url": "https://github.com/fastify/secure-json-parse/issues"
},
"homepage": "https://github.com/fastify/secure-json-parse#readme",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fastify"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fastify"
}
],
"devDependencies": {
"airtap": "^5.0.0",
"airtap-playwright": "^1.0.1",
"eslint": "^9.17.0",
"neostandard": "^0.12.0",
"nyc": "^17.0.0",
"playwright": "^1.43.1",
"tape": "^5.7.5",
"tsd": "^0.33.0"
}
}

View File

@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ForScope = void 0;
const ScopeBase_1 = require("./ScopeBase");
const ScopeType_1 = require("./ScopeType");
class ForScope extends ScopeBase_1.ScopeBase {
constructor(scopeManager, upperScope, block) {
super(scopeManager, ScopeType_1.ScopeType.for, upperScope, block, false);
}
}
exports.ForScope = ForScope;

View File

@@ -0,0 +1,798 @@
'use strict';
var fs = require('node:fs');
var path = require('node:path');
/**
* @fileoverview defineConfig helper
* @author Nicholas C. Zakas
*/
//-----------------------------------------------------------------------------
// Type Definitions
//-----------------------------------------------------------------------------
/** @import * as $eslintcore from "@eslint/core"; */
/** @typedef {$eslintcore.ConfigObject} ConfigObject */
/** @typedef {$eslintcore.LegacyConfigObject} LegacyConfig */
/** @typedef {$eslintcore.Plugin} Plugin */
/** @typedef {$eslintcore.RuleConfig} RuleConfig */
/** @import * as $typests from "./types.ts"; */
/** @typedef {$typests.Config} Config */
/** @typedef {$typests.ExtendsElement} ExtendsElement */
/** @typedef {$typests.ExtensionConfigObject} ExtensionConfigObject */
/** @typedef {$typests.SimpleExtendsElement} SimpleExtendsElement */
/** @typedef {$typests.ConfigWithExtends} ConfigWithExtends */
/** @typedef {$typests.InfiniteArray<ConfigObject>} InfiniteConfigArray */
/** @typedef {$typests.ConfigWithExtendsArray} ConfigWithExtendsArray */
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
const eslintrcKeys = [
"env",
"extends",
"globals",
"ignorePatterns",
"noInlineConfig",
"overrides",
"parser",
"parserOptions",
"reportUnusedDisableDirectives",
"root",
];
const allowedGlobalIgnoreKeys = new Set(["basePath", "ignores", "name"]);
/**
* Gets the name of a config object.
* @param {ConfigObject} config The config object.
* @param {string} indexPath The index path of the config object.
* @return {string} The name of the config object.
*/
function getConfigName(config, indexPath) {
if (config.name) {
return config.name;
}
return `UserConfig${indexPath}`;
}
/**
* Gets the name of an extension.
* @param {SimpleExtendsElement} extension The extension.
* @param {string} indexPath The index of the extension.
* @return {string} The name of the extension.
*/
function getExtensionName(extension, indexPath) {
if (typeof extension === "string") {
return extension;
}
if (extension.name) {
return extension.name;
}
return `ExtendedConfig${indexPath}`;
}
/**
* Determines if a config object is a legacy config.
* @param {ConfigObject|LegacyConfig} config The config object to check.
* @return {config is LegacyConfig} `true` if the config object is a legacy config.
*/
function isLegacyConfig(config) {
// eslintrc's plugins must be an array; while flat config's must be an object.
if (Array.isArray(config.plugins)) {
return true;
}
for (const key of eslintrcKeys) {
if (key in config) {
return true;
}
}
return false;
}
/**
* Determines if a config object is a global ignores config.
* @param {ConfigObject} config The config object to check.
* @return {boolean} `true` if the config object is a global ignores config.
*/
function isGlobalIgnores(config) {
return Object.keys(config).every(key => allowedGlobalIgnoreKeys.has(key));
}
/**
* Parses a plugin member ID (rule, processor, etc.) and returns
* the namespace and member name.
* @param {string} id The ID to parse.
* @returns {{namespace:string, name:string}} The namespace and member name.
*/
function getPluginMember(id) {
const firstSlashIndex = id.indexOf("/");
if (firstSlashIndex === -1) {
return { namespace: "", name: id };
}
let namespace = id.slice(0, firstSlashIndex);
/*
* Special cases:
* 1. The namespace is `@`, that means it's referring to the
* core plugin so `@` is the full namespace.
* 2. The namespace starts with `@`, that means it's referring to
* an npm scoped package. That means the namespace is the scope
* and the package name (i.e., `@eslint/core`).
*/
if (namespace[0] === "@" && namespace !== "@") {
const secondSlashIndex = id.indexOf("/", firstSlashIndex + 1);
if (secondSlashIndex !== -1) {
namespace = id.slice(0, secondSlashIndex);
return { namespace, name: id.slice(secondSlashIndex + 1) };
}
}
const name = id.slice(firstSlashIndex + 1);
return { namespace, name };
}
/**
* Normalizes the plugin config by replacing the namespace with the plugin namespace.
* @param {string} userNamespace The namespace of the plugin.
* @param {Plugin} plugin The plugin config object.
* @param {ConfigObject} config The config object to normalize.
* @return {ConfigObject} The normalized config object.
*/
function normalizePluginConfig(userNamespace, plugin, config) {
const pluginNamespace = plugin.meta?.namespace;
// don't do anything if the plugin doesn't have a namespace or rules
if (
!pluginNamespace ||
pluginNamespace === userNamespace ||
(!config.rules && !config.processor && !config.language)
) {
return config;
}
const result = { ...config };
// update the rules
if (result.rules) {
const ruleIds = Object.keys(result.rules);
/** @type {Record<string,RuleConfig|undefined>} */
const newRules = {};
for (let i = 0; i < ruleIds.length; i++) {
const ruleId = ruleIds[i];
const { namespace: ruleNamespace, name: ruleName } =
getPluginMember(ruleId);
if (ruleNamespace === pluginNamespace) {
newRules[`${userNamespace}/${ruleName}`] = result.rules[ruleId];
} else {
newRules[ruleId] = result.rules[ruleId];
}
}
result.rules = newRules;
}
// update the processor
if (typeof result.processor === "string") {
const { namespace: processorNamespace, name: processorName } =
getPluginMember(result.processor);
if (processorNamespace) {
if (processorNamespace === pluginNamespace) {
result.processor = `${userNamespace}/${processorName}`;
}
}
}
// update the language
if (typeof result.language === "string") {
const { namespace: languageNamespace, name: languageName } =
getPluginMember(result.language);
if (languageNamespace === pluginNamespace) {
result.language = `${userNamespace}/${languageName}`;
}
}
return result;
}
/**
* Deeply normalizes a plugin config, traversing recursively into an arrays.
* @param {string} userPluginNamespace The namespace of the plugin.
* @param {Plugin} plugin The plugin object.
* @param {ConfigObject|LegacyConfig|(ConfigObject|LegacyConfig)[]} pluginConfig The plugin config to normalize.
* @param {string} pluginConfigName The name of the plugin config.
* @return {InfiniteConfigArray} The normalized plugin config.
* @throws {TypeError} If the plugin config is a legacy config.
*/
function deepNormalizePluginConfig(
userPluginNamespace,
plugin,
pluginConfig,
pluginConfigName,
) {
// if it's an array then it's definitely a new config
if (Array.isArray(pluginConfig)) {
return pluginConfig.map(pluginSubConfig =>
deepNormalizePluginConfig(
userPluginNamespace,
plugin,
pluginSubConfig,
pluginConfigName,
),
);
}
// if it's a legacy config, throw an error
if (isLegacyConfig(pluginConfig)) {
throw new TypeError(
`Plugin config "${pluginConfigName}" is an eslintrc config and cannot be used in this context.`,
);
}
return normalizePluginConfig(userPluginNamespace, plugin, pluginConfig);
}
/**
* Finds a plugin config by name in the given config.
* @param {ConfigObject} config The config object.
* @param {string} pluginConfigName The name of the plugin config.
* @return {InfiniteConfigArray} The plugin config.
* @throws {TypeError} If the plugin config is not found or is a legacy config.
*/
function findPluginConfig(config, pluginConfigName) {
const { namespace: userPluginNamespace, name: configName } =
getPluginMember(pluginConfigName);
const plugin = config.plugins?.[userPluginNamespace];
if (!plugin) {
throw new TypeError(`Plugin "${userPluginNamespace}" not found.`);
}
const directConfig = plugin.configs?.[configName];
// Prefer direct config, but fall back to flat config if available
if (directConfig) {
// Arrays are always flat configs, and non-legacy configs can be used directly
if (Array.isArray(directConfig) || !isLegacyConfig(directConfig)) {
return deepNormalizePluginConfig(
userPluginNamespace,
plugin,
directConfig,
pluginConfigName,
);
}
}
// If it's a legacy config, or the config does not exist => look for the flat version
const flatConfig = plugin.configs?.[`flat/${configName}`];
if (
flatConfig &&
(Array.isArray(flatConfig) || !isLegacyConfig(flatConfig))
) {
return deepNormalizePluginConfig(
userPluginNamespace,
plugin,
flatConfig,
pluginConfigName,
);
}
// If we get here, then the config was either not found or is a legacy config
const message =
directConfig || flatConfig
? `Plugin config "${configName}" in plugin "${userPluginNamespace}" is an eslintrc config and cannot be used in this context.`
: `Plugin config "${configName}" not found in plugin "${userPluginNamespace}".`;
throw new TypeError(message);
}
/**
* Flattens an array while keeping track of the index path.
* @param {any[]} configList The array to traverse.
* @param {string} indexPath The index path of the value in a multidimensional array.
* @return {IterableIterator<{indexPath:string, value:any}>} The flattened list of values.
*/
function* flatTraverse(configList, indexPath = "") {
for (let i = 0; i < configList.length; i++) {
const newIndexPath = indexPath ? `${indexPath}[${i}]` : `[${i}]`;
// if it's an array then traverse it as well
if (Array.isArray(configList[i])) {
yield* flatTraverse(configList[i], newIndexPath);
continue;
}
yield { indexPath: newIndexPath, value: configList[i] };
}
}
/**
* Extends a list of config files by creating every combination of base and extension files.
* @param {(string|string[])[]} [baseFiles] The base files.
* @param {(string|string[])[]} [extensionFiles] The extension files.
* @return {(string|string[])[]} The extended files.
*/
function extendConfigFiles(baseFiles = [], extensionFiles = []) {
if (!extensionFiles.length) {
return baseFiles.concat();
}
if (!baseFiles.length) {
return extensionFiles.concat();
}
/** @type {(string|string[])[]} */
const result = [];
for (const baseFile of baseFiles) {
for (const extensionFile of extensionFiles) {
/*
* Each entry can be a string or array of strings. The end result
* needs to be an array of strings, so we need to be sure to include
* all of the items when there's an array.
*/
const entry = [];
if (Array.isArray(baseFile)) {
entry.push(...baseFile);
} else {
entry.push(baseFile);
}
if (Array.isArray(extensionFile)) {
entry.push(...extensionFile);
} else {
entry.push(extensionFile);
}
result.push(entry);
}
}
return result;
}
/**
* Extends a config object with another config object.
* @param {ConfigObject} baseConfig The base config object.
* @param {string} baseConfigName The name of the base config object.
* @param {ConfigObject} extension The extension config object.
* @param {string} extensionName The index of the extension config object.
* @return {ConfigObject} The extended config object.
*/
function extendConfig(baseConfig, baseConfigName, extension, extensionName) {
const result = { ...extension };
// for global ignores there is no further work to be done, we just keep everything
if (!isGlobalIgnores(extension)) {
// for files we need to create every combination of base and extension files
if (baseConfig.files) {
result.files = extendConfigFiles(baseConfig.files, extension.files);
}
// for ignores we just concatenation the extension ignores onto the base ignores
if (baseConfig.ignores) {
result.ignores = baseConfig.ignores.concat(extension.ignores ?? []);
}
}
result.name = `${baseConfigName} > ${extensionName}`;
if (baseConfig.basePath) {
result.basePath = baseConfig.basePath;
}
return result;
}
/**
* Processes a list of extends elements.
* @param {ConfigWithExtends} config The config object.
* @param {WeakMap<ConfigObject, string>} configNames The map of config objects to their names.
* @return {ConfigObject[]} The flattened list of config objects.
* @throws {TypeError} If the `extends` property is not an array or if nested `extends` is found.
*/
function processExtends(config, configNames) {
if (!config.extends) {
return [config];
}
if (!Array.isArray(config.extends)) {
throw new TypeError("The `extends` property must be an array.");
}
const {
/** @type {ConfigObject[]} */
extends: extendsList,
/** @type {ConfigObject} */
...configObject
} = config;
const extensionNames = new WeakMap();
// replace strings with the actual configs
const objectExtends = extendsList.map(extendsElement => {
if (typeof extendsElement === "string") {
const pluginConfig = findPluginConfig(config, extendsElement);
// assign names
if (Array.isArray(pluginConfig)) {
pluginConfig.forEach((pluginConfigElement, index) => {
extensionNames.set(
pluginConfigElement,
`${extendsElement}[${index}]`,
);
});
} else {
extensionNames.set(pluginConfig, extendsElement);
}
return pluginConfig;
}
return /** @type {ConfigObject} */ (extendsElement);
});
const result = [];
for (const { indexPath, value: extendsElement } of flatTraverse(
objectExtends,
)) {
const extension = /** @type {ConfigObject} */ (extendsElement);
if ("basePath" in extension) {
throw new TypeError("'basePath' in `extends` is not allowed.");
}
if ("extends" in extension) {
throw new TypeError("Nested 'extends' is not allowed.");
}
const baseConfigName = /** @type {string} */ (configNames.get(config));
const extensionName =
extensionNames.get(extendsElement) ??
getExtensionName(extendsElement, indexPath);
result.push(
extendConfig(
configObject,
baseConfigName,
extension,
extensionName,
),
);
}
/*
* If the base config object has only `ignores` and `extends`, then
* removing `extends` turns it into a global ignores, which is not what
* we want. So we need to check if the base config object is a global ignores
* and if so, we don't add it to the array.
*
* (The other option would be to add a `files` entry, but that would result
* in a config that didn't actually do anything because there are no
* other keys in the config.)
*/
if (!isGlobalIgnores(configObject)) {
result.push(configObject);
}
return result.flat();
}
/**
* Processes a list of config objects and arrays.
* @param {ConfigWithExtends[]} configList The list of config objects and arrays.
* @param {WeakMap<ConfigObject, string>} configNames The map of config objects to their names.
* @return {ConfigObject[]} The flattened list of config objects.
*/
function processConfigList(configList, configNames) {
return configList.flatMap(config => processExtends(config, configNames));
}
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* Helper function to define a config array.
* @param {ConfigWithExtendsArray} args The arguments to the function.
* @returns {ConfigObject[]} The config array.
* @throws {TypeError} If no arguments are provided or if an argument is not an object.
*/
function defineConfig(...args) {
const configNames = new WeakMap();
const configs = [];
if (args.length === 0) {
throw new TypeError("Expected one or more arguments.");
}
// first flatten the list of configs and get the names
for (const { indexPath, value } of flatTraverse(args)) {
if (typeof value !== "object" || value === null) {
throw new TypeError(
`Expected an object but received ${String(value)}.`,
);
}
const config = /** @type {ConfigWithExtends} */ (value);
// save config name for easy reference later
configNames.set(config, getConfigName(config, indexPath));
configs.push(config);
}
return processConfigList(configs, configNames);
}
/**
* @fileoverview Global ignores helper function.
* @author Nicholas C. Zakas
*/
//-----------------------------------------------------------------------------
// Type Definitions
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
let globalIgnoreCount = 0;
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* Creates a global ignores config with the given patterns.
* @param {string[]} ignorePatterns The ignore patterns.
* @param {string} [name] The name of the global ignores config.
* @returns {ConfigObject} The global ignores config.
* @throws {TypeError} If ignorePatterns is not an array or if it is empty.
*/
function globalIgnores(ignorePatterns, name) {
if (!Array.isArray(ignorePatterns)) {
throw new TypeError("ignorePatterns must be an array");
}
if (ignorePatterns.length === 0) {
throw new TypeError("ignorePatterns must contain at least one pattern");
}
const id = globalIgnoreCount++;
return {
name: name || `globalIgnores ${id}`,
ignores: ignorePatterns,
};
}
/**
* @fileoverview Ignore file utilities for the config-helpers package.
* This file was forked from the source code for the compat package.
*
* @author Nicholas C. Zakas
* @author Kirk Waiblinger
*/
//-----------------------------------------------------------------------------
// Types
//-----------------------------------------------------------------------------
/**
* @typedef {object} IncludeIgnoreFileOptionsObject
* @property {boolean} [gitignoreResolution] Whether to interpret the contents of an ignore file relative to the config file or the ignore file.
* - gitignoreResolution: false (default): Interprets ignore patterns relative to the config file
* - gitignoreResolution: true: Interprets the ignore patterns in a file relative to the ignore file
* @property {string} [name] The name to give the output config object(s).
*/
/**
* Options for `includeIgnoreFile()`. May be provided as an object or, for
* legacy compatibility with `@eslint/compat`, as a string which is treated as
* the `name` option.
* @typedef {IncludeIgnoreFileOptionsObject | string} IncludeIgnoreFileOptions
*/
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* Converts an ESLint ignore pattern to a minimatch pattern.
* @param {string} pattern The .eslintignore or .gitignore pattern to convert.
* @returns {string} The converted pattern.
*/
function convertIgnorePatternToMinimatch(pattern) {
const isNegated = pattern.startsWith("!");
const negatedPrefix = isNegated ? "!" : "";
const patternToTest = (isNegated ? pattern.slice(1) : pattern).trimEnd();
// special cases
if (["", "**", "/**", "**/"].includes(patternToTest)) {
return `${negatedPrefix}${patternToTest}`;
}
const firstIndexOfSlash = patternToTest.indexOf("/");
const matchEverywherePrefix =
firstIndexOfSlash < 0 || firstIndexOfSlash === patternToTest.length - 1
? "**/"
: "";
const patternWithoutLeadingSlash =
firstIndexOfSlash === 0 ? patternToTest.slice(1) : patternToTest;
/*
* Escape `{` and `(` because in gitignore patterns they are just
* literal characters without any specific syntactic meaning,
* while in minimatch patterns they can form brace expansion or extglob syntax.
*
* For example, gitignore pattern `src/{a,b}.js` ignores file `src/{a,b}.js`.
* But, the same minimatch pattern `src/{a,b}.js` ignores files `src/a.js` and `src/b.js`.
* Minimatch pattern `src/\{a,b}.js` is equivalent to gitignore pattern `src/{a,b}.js`.
*/
const escapedPatternWithoutLeadingSlash =
patternWithoutLeadingSlash.replaceAll(
// eslint-disable-next-line regexp/no-empty-lookarounds-assertion -- False positive
/(?=((?:\\.|[^{(])*))\1([{(])/guy,
"$1\\$2",
);
const matchInsideSuffix = patternToTest.endsWith("/**") ? "/*" : "";
return `${negatedPrefix}${matchEverywherePrefix}${escapedPatternWithoutLeadingSlash}${matchInsideSuffix}`;
}
/**
* @param {string} ignoreFilePath
* @returns {string[]}
*/
function ignoreFilePathToPatterns(ignoreFilePath) {
const ignoreFile = fs.readFileSync(ignoreFilePath, "utf8");
const lines = ignoreFile.split(/\r?\n/u);
return lines
.map(line => line.trim())
.filter(line => line && !line.startsWith("#"))
.map(convertIgnorePatternToMinimatch);
}
/**
* Helper to parse and validate the options to `includeIgnoreFile()`
*
* @param {string | { gitignoreResolution?: unknown, name?: unknown } | undefined} options
* @returns {{ gitignoreResolution: boolean, name: string }}
*/
function parseOptions(options) {
// legacy compatibility with @eslint/compat's `includeIgnoreFile`
if (typeof options === "string") {
return { gitignoreResolution: false, name: options };
}
const optionsObject = options ?? {};
if (typeof optionsObject !== "object" || Array.isArray(optionsObject)) {
throw new TypeError(
"The options argument to `includeIgnoreFile()` should be an object or a string.",
);
}
const gitignoreResolution = optionsObject.gitignoreResolution ?? false;
if (typeof gitignoreResolution !== "boolean") {
throw new TypeError(
"The `gitignoreResolution` option must be specified a boolean or omitted",
);
}
const name = optionsObject.name ?? `Imported .gitignore patterns`;
if (typeof name !== "string") {
throw new TypeError(
"The `name` option must be specified as a string or omitted.",
);
}
return { gitignoreResolution, name };
}
/**
* @overload
*
* Reads ignore files and returns objects with the ignore patterns.
*
* @param {string[]} ignoreFilePathArg The paths of ignore files to include.
* @param {IncludeIgnoreFileOptions} [options]
* @returns {ConfigObject[]}
*/
/**
* @overload
*
* Reads an ignore file and returns an object with the ignore patterns.
*
* @param {string} ignoreFilePathArg The path of the ignore file to include.
* @param {IncludeIgnoreFileOptions} [options]
* @returns {ConfigObject}
*/
/**
* @overload
*
* Reads an ignore file(s) and returns an object(s) with the ignore patterns.
*
* @param {string[] | string} ignoreFilePathArg The path(s) of the ignore file(s) to include.
* @param {IncludeIgnoreFileOptions} [options]
* @returns {ConfigObject[] | ConfigObject}
*/
/**
* Reads an ignore file(s) and returns an object(s) with the ignore patterns.
*
* @param {string[] | string} ignoreFilePathArg The path(s) of the ignore file(s) to include.
* @param {IncludeIgnoreFileOptions} [options]
* @returns {ConfigObject[] | ConfigObject}
*/
function includeIgnoreFile(ignoreFilePathArg, options) {
const returnSingleObject = !Array.isArray(ignoreFilePathArg);
const ignoreFilePaths = Array.isArray(ignoreFilePathArg)
? ignoreFilePathArg
: [ignoreFilePathArg];
for (const ignorePath of ignoreFilePaths) {
if (typeof ignorePath !== "string") {
throw new TypeError(
"The first argument to `includeIgnoreFile()` should be a string or array of strings",
);
}
if (!path.isAbsolute(ignorePath)) {
throw new Error(
`The ignore file location must be an absolute path. Received ${ignorePath}`,
);
}
}
const { gitignoreResolution, name } = parseOptions(options);
if (returnSingleObject) {
return {
name,
ignores: ignoreFilePathToPatterns(ignoreFilePathArg),
...(gitignoreResolution
? { basePath: path.dirname(ignoreFilePathArg) }
: {}),
};
}
return ignoreFilePaths.map((ignoreFilePath, i) => ({
name: `${name} (${i})`,
ignores: ignoreFilePathToPatterns(ignoreFilePath),
...(gitignoreResolution
? { basePath: path.dirname(ignoreFilePath) }
: {}),
}));
}
exports.convertIgnorePatternToMinimatch = convertIgnorePatternToMinimatch;
exports.defineConfig = defineConfig;
exports.globalIgnores = globalIgnores;
exports.includeIgnoreFile = includeIgnoreFile;

View File

@@ -0,0 +1,262 @@
export type Mode = 'text' | 'binary'
export type MessageName =
| 'parseComplete'
| 'bindComplete'
| 'closeComplete'
| 'noData'
| 'portalSuspended'
| 'replicationStart'
| 'emptyQuery'
| 'copyDone'
| 'copyData'
| 'rowDescription'
| 'parameterDescription'
| 'parameterStatus'
| 'backendKeyData'
| 'notification'
| 'readyForQuery'
| 'commandComplete'
| 'dataRow'
| 'copyInResponse'
| 'copyOutResponse'
| 'authenticationOk'
| 'authenticationMD5Password'
| 'authenticationCleartextPassword'
| 'authenticationSASL'
| 'authenticationSASLContinue'
| 'authenticationSASLFinal'
| 'error'
| 'notice'
export interface BackendMessage {
name: MessageName
length: number
}
export const parseComplete: BackendMessage = {
name: 'parseComplete',
length: 5,
}
export const bindComplete: BackendMessage = {
name: 'bindComplete',
length: 5,
}
export const closeComplete: BackendMessage = {
name: 'closeComplete',
length: 5,
}
export const noData: BackendMessage = {
name: 'noData',
length: 5,
}
export const portalSuspended: BackendMessage = {
name: 'portalSuspended',
length: 5,
}
export const replicationStart: BackendMessage = {
name: 'replicationStart',
length: 4,
}
export const emptyQuery: BackendMessage = {
name: 'emptyQuery',
length: 4,
}
export const copyDone: BackendMessage = {
name: 'copyDone',
length: 4,
}
interface NoticeOrError {
message: string | undefined
severity: string | undefined
code: string | undefined
detail: string | undefined
hint: string | undefined
position: string | undefined
internalPosition: string | undefined
internalQuery: string | undefined
where: string | undefined
schema: string | undefined
table: string | undefined
column: string | undefined
dataType: string | undefined
constraint: string | undefined
file: string | undefined
line: string | undefined
routine: string | undefined
}
export class DatabaseError extends Error implements NoticeOrError {
public severity: string | undefined
public code: string | undefined
public detail: string | undefined
public hint: string | undefined
public position: string | undefined
public internalPosition: string | undefined
public internalQuery: string | undefined
public where: string | undefined
public schema: string | undefined
public table: string | undefined
public column: string | undefined
public dataType: string | undefined
public constraint: string | undefined
public file: string | undefined
public line: string | undefined
public routine: string | undefined
constructor(
message: string,
public readonly length: number,
public readonly name: MessageName
) {
super(message)
}
}
export class CopyDataMessage {
public readonly name = 'copyData'
constructor(
public readonly length: number,
public readonly chunk: Buffer
) {}
}
export class CopyResponse {
public readonly columnTypes: number[]
constructor(
public readonly length: number,
public readonly name: MessageName,
public readonly binary: boolean,
columnCount: number
) {
this.columnTypes = new Array(columnCount)
}
}
export class Field {
constructor(
public readonly name: string,
public readonly tableID: number,
public readonly columnID: number,
public readonly dataTypeID: number,
public readonly dataTypeSize: number,
public readonly dataTypeModifier: number,
public readonly format: Mode
) {}
}
export class RowDescriptionMessage {
public readonly name: MessageName = 'rowDescription'
public readonly fields: Field[]
constructor(
public readonly length: number,
public readonly fieldCount: number
) {
this.fields = new Array(this.fieldCount)
}
}
export class ParameterDescriptionMessage {
public readonly name: MessageName = 'parameterDescription'
public readonly dataTypeIDs: number[]
constructor(
public readonly length: number,
public readonly parameterCount: number
) {
this.dataTypeIDs = new Array(this.parameterCount)
}
}
export class ParameterStatusMessage {
public readonly name: MessageName = 'parameterStatus'
constructor(
public readonly length: number,
public readonly parameterName: string,
public readonly parameterValue: string
) {}
}
export class AuthenticationMD5Password implements BackendMessage {
public readonly name: MessageName = 'authenticationMD5Password'
constructor(
public readonly length: number,
public readonly salt: Buffer
) {}
}
export class BackendKeyDataMessage {
public readonly name: MessageName = 'backendKeyData'
constructor(
public readonly length: number,
public readonly processID: number,
public readonly secretKey: number
) {}
}
export class NotificationResponseMessage {
public readonly name: MessageName = 'notification'
constructor(
public readonly length: number,
public readonly processId: number,
public readonly channel: string,
public readonly payload: string
) {}
}
export class ReadyForQueryMessage {
public readonly name: MessageName = 'readyForQuery'
constructor(
public readonly length: number,
public readonly status: string
) {}
}
export class CommandCompleteMessage {
public readonly name: MessageName = 'commandComplete'
constructor(
public readonly length: number,
public readonly text: string
) {}
}
export class DataRowMessage {
public readonly fieldCount: number
public readonly name: MessageName = 'dataRow'
constructor(
public length: number,
public fields: any[]
) {
this.fieldCount = fields.length
}
}
export class NoticeMessage implements BackendMessage, NoticeOrError {
constructor(
public readonly length: number,
public readonly message: string | undefined
) {}
public readonly name = 'notice'
public severity: string | undefined
public code: string | undefined
public detail: string | undefined
public hint: string | undefined
public position: string | undefined
public internalPosition: string | undefined
public internalQuery: string | undefined
public where: string | undefined
public schema: string | undefined
public table: string | undefined
public column: string | undefined
public dataType: string | undefined
public constraint: string | undefined
public file: string | undefined
public line: string | undefined
public routine: string | undefined
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"b.js","sourceRoot":"","sources":["../src/b.ts"],"names":[],"mappings":";AAAA,6BAA6B;;AAE7B,mDAA8C;AAE9C,MAAM,KAAK,GAAG,IAAI,CAAA;AAClB,IAAI,KAAK,GAAG,CAAC,CAAA;AACb,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE,CAAA;AAE/B,MAAM,MAAM,GAAG,IAAI,4BAAY,EAAE,CAAA;AACjC,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAA;AAE3D,MAAM,GAAG,GAAG,GAAG,EAAE;IACf,IAAI,KAAK,GAAG,KAAK,EAAE,CAAC;QAClB,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,CAAA;QACtC,OAAM;IACR,CAAC;IACD,KAAK,EAAE,CAAA;IACP,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC;QAC/B,MAAM,CAAC,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,CAAA;QAC3B,MAAM,CAAC,OAAO,EAAE,CAAA;IAClB,CAAC;IACD,YAAY,CAAC,GAAG,CAAC,CAAA;AACnB,CAAC,CAAA;AAED,GAAG,EAAE,CAAA"}

View File

@@ -0,0 +1,220 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import { z } from "zod/v3";
import { util } from "../helpers/util.js";
test("basic catch", () => {
expect(z.string().catch("default").parse(undefined)).toBe("default");
});
test("catch fn does not run when parsing succeeds", () => {
let isCalled = false;
const cb = () => {
isCalled = true;
return "asdf";
};
expect(z.string().catch(cb).parse("test")).toBe("test");
expect(isCalled).toEqual(false);
});
test("basic catch async", async () => {
const result = await z.string().catch("default").parseAsync(1243);
expect(result).toBe("default");
});
test("catch replace wrong types", () => {
expect(z.string().catch("default").parse(true)).toBe("default");
expect(z.string().catch("default").parse(true)).toBe("default");
expect(z.string().catch("default").parse(15)).toBe("default");
expect(z.string().catch("default").parse([])).toBe("default");
expect(z.string().catch("default").parse(new Map())).toBe("default");
expect(z.string().catch("default").parse(new Set())).toBe("default");
expect(z.string().catch("default").parse({})).toBe("default");
});
test("catch with transform", () => {
const stringWithDefault = z
.string()
.transform((val) => val.toUpperCase())
.catch("default");
expect(stringWithDefault.parse(undefined)).toBe("default");
expect(stringWithDefault.parse(15)).toBe("default");
expect(stringWithDefault).toBeInstanceOf(z.ZodCatch);
expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodEffects);
expect(stringWithDefault._def.innerType._def.schema).toBeInstanceOf(z.ZodSchema);
type inp = z.input<typeof stringWithDefault>;
util.assertEqual<inp, unknown>(true);
type out = z.output<typeof stringWithDefault>;
util.assertEqual<out, string>(true);
});
test("catch on existing optional", () => {
const stringWithDefault = z.string().optional().catch("asdf");
expect(stringWithDefault.parse(undefined)).toBe(undefined);
expect(stringWithDefault.parse(15)).toBe("asdf");
expect(stringWithDefault).toBeInstanceOf(z.ZodCatch);
expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodOptional);
expect(stringWithDefault._def.innerType._def.innerType).toBeInstanceOf(z.ZodString);
type inp = z.input<typeof stringWithDefault>;
util.assertEqual<inp, unknown>(true);
type out = z.output<typeof stringWithDefault>;
util.assertEqual<out, string | undefined>(true);
});
test("optional on catch", () => {
const stringWithDefault = z.string().catch("asdf").optional();
type inp = z.input<typeof stringWithDefault>;
util.assertEqual<inp, unknown>(true);
type out = z.output<typeof stringWithDefault>;
util.assertEqual<out, string | undefined>(true);
});
test("complex chain example", () => {
const complex = z
.string()
.catch("asdf")
.transform((val) => val + "!")
.transform((val) => val.toUpperCase())
.catch("qwer")
.removeCatch()
.optional()
.catch("asdfasdf");
expect(complex.parse("qwer")).toBe("QWER!");
expect(complex.parse(15)).toBe("ASDF!");
expect(complex.parse(true)).toBe("ASDF!");
});
test("removeCatch", () => {
const stringWithRemovedDefault = z.string().catch("asdf").removeCatch();
type out = z.output<typeof stringWithRemovedDefault>;
util.assertEqual<out, string>(true);
});
test("nested", () => {
const inner = z.string().catch("asdf");
const outer = z.object({ inner }).catch({
inner: "asdf",
});
type input = z.input<typeof outer>;
util.assertEqual<input, unknown>(true);
type out = z.output<typeof outer>;
util.assertEqual<out, { inner: string }>(true);
expect(outer.parse(undefined)).toEqual({ inner: "asdf" });
expect(outer.parse({})).toEqual({ inner: "asdf" });
expect(outer.parse({ inner: undefined })).toEqual({ inner: "asdf" });
});
test("chained catch", () => {
const stringWithDefault = z.string().catch("inner").catch("outer");
const result = stringWithDefault.parse(undefined);
expect(result).toEqual("inner");
const resultDiff = stringWithDefault.parse(5);
expect(resultDiff).toEqual("inner");
});
test("factory", () => {
z.ZodCatch.create(z.string(), {
catch: "asdf",
}).parse(undefined);
});
test("native enum", () => {
enum Fruits {
apple = "apple",
orange = "orange",
}
const schema = z.object({
fruit: z.nativeEnum(Fruits).catch(Fruits.apple),
});
expect(schema.parse({})).toEqual({ fruit: Fruits.apple });
expect(schema.parse({ fruit: 15 })).toEqual({ fruit: Fruits.apple });
});
test("enum", () => {
const schema = z.object({
fruit: z.enum(["apple", "orange"]).catch("apple"),
});
expect(schema.parse({})).toEqual({ fruit: "apple" });
expect(schema.parse({ fruit: true })).toEqual({ fruit: "apple" });
expect(schema.parse({ fruit: 15 })).toEqual({ fruit: "apple" });
});
test("reported issues with nested usage", () => {
const schema = z.object({
string: z.string(),
obj: z.object({
sub: z.object({
lit: z.literal("a"),
subCatch: z.number().catch(23),
}),
midCatch: z.number().catch(42),
}),
number: z.number().catch(0),
bool: z.boolean(),
});
try {
schema.parse({
string: {},
obj: {
sub: {
lit: "b",
subCatch: "24",
},
midCatch: 444,
},
number: "",
bool: "yes",
});
} catch (error) {
const issues = (error as z.ZodError).issues;
expect(issues.length).toEqual(3);
expect(issues[0].message).toMatch("string");
expect(issues[1].message).toMatch("literal");
expect(issues[2].message).toMatch("boolean");
}
});
test("catch error", () => {
let catchError: z.ZodError | undefined = undefined;
const schema = z.object({
age: z.number(),
name: z.string().catch((ctx) => {
catchError = ctx.error;
return "John Doe";
}),
});
const result = schema.safeParse({
age: null,
name: null,
});
expect(result.success).toEqual(false);
expect(!result.success && result.error.issues.length).toEqual(1);
expect(!result.success && result.error.issues[0].message).toMatch("number");
expect(catchError).toBeInstanceOf(z.ZodError);
expect(catchError !== undefined && (catchError as z.ZodError).issues.length).toEqual(1);
expect(catchError !== undefined && (catchError as z.ZodError).issues[0].message).toMatch("string");
});
test("ctx.input", () => {
const schema = z.string().catch((ctx) => {
return String(ctx.input);
});
expect(schema.parse(123)).toEqual("123");
});

View File

@@ -0,0 +1 @@
{"version":3,"file":"message-formatter.d.ts","sourceRoot":"","sources":["../../src/message-formatter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAgB1C,wBAAgB,4BAA4B,CAAC,UAAU,SAAS,eAAe,EAC3E,IAAI,EAAE,UAAU,EAChB,OAAO,GAAE,MAAW,GACrB,MAAM,CAiER;AAED,wBAAgB,eAAe,CAAC,UAAU,SAAS,eAAe,EAC9D,IAAI,EAAE,UAAU,EAChB,OAAO,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GACtC,MAAM,CAeR"}

View File

@@ -0,0 +1,998 @@
## 8.18.0 (2026-07-28)
### New features
The new `startLocation` option can now be used to tell the parser the line and column the parse starts at (mostly useful with `parseExpressionAt`).
### Bug fixes
Reject uses of `**` with a non-parenthesized arrow function as left-hand side.
Avoid computing the start line in `parseExpressionAt` when locations aren't used.
## 8.17.0 (2026-06-11)
### New features
The new `strict` option can be used to start script sources in strict mode.
### Bug fixes
Fix a number of corner case bugs when `using` or `await using` appear in `for` loop specs.
Disallow `new super()` expressions.
Don't allow the conditional in a ternary expression to be a (naked) arrow function.
## 8.16.0 (2026-02-19)
### New features
The `sourceType` option can now be set to `"commonjs"` to have the parser treat the top level scope as a function scope.
Add support for Unicode 17.
### Bug fixes
Don't recognize `await using` as contextual keywords when followed directly by a backslash.
Fix an issue where the parser would allow `return` statements in `static` blocks when `allowReturnOutsideFunction` was enabled.
Properly reject `using` declarations that appear directly in `switch` or `for` head scopes.
Fix some corner case issues in the recognition of `using` syntax.
## 8.15.0 (2025-06-08)
### New features
Support `using` and `await using` syntax.
The `AnyNode` type is now defined in such a way that plugins can extend it.
### Bug fixes
Fix an issue where the `bigint` property of literal nodes for non-decimal bigints had the wrong format.
The `acorn` CLI tool no longer crashes when emitting a tree that contains a bigint.
## 8.14.1 (2025-03-05)
### Bug fixes
Fix an issue where `await` expressions in class field initializers were inappropriately allowed.
Properly allow await inside an async arrow function inside a class field initializer.
Mention the source file name in syntax error messages when given.
Properly add an empty `attributes` property to every form of `ExportNamedDeclaration`.
## 8.14.0 (2024-10-27)
### New features
Support ES2025 import attributes.
Support ES2025 RegExp modifiers.
### Bug fixes
Support some missing Unicode properties.
## 8.13.0 (2024-10-16)
### New features
Upgrade to Unicode 16.0.
## 8.12.1 (2024-07-03)
### Bug fixes
Fix a regression that caused Acorn to no longer run on Node versions <8.10.
## 8.12.0 (2024-06-14)
### New features
Support ES2025 duplicate capture group names in regular expressions.
### Bug fixes
Include `VariableDeclarator` in the `AnyNode` type so that walker objects can refer to it without getting a type error.
Properly raise a parse error for invalid `for`/`of` statements using `async` as binding name.
Properly recognize \"use strict\" when preceded by a string with an escaped newline.
Mark the `Parser` constructor as protected, not private, so plugins can extend it without type errors.
Fix a bug where some invalid `delete` expressions were let through when the operand was parenthesized and `preserveParens` was enabled.
Properly normalize line endings in raw strings of invalid template tokens.
Properly track line numbers for escaped newlines in strings.
Fix a bug that broke line number accounting after a template literal with invalid escape sequences.
## 8.11.3 (2023-12-29)
### Bug fixes
Add `Function` and `Class` to the `AggregateType` type, so that they can be used in walkers without raising a type error.
Make sure `onToken` get an `import` keyword token when parsing `import.meta`.
Fix a bug where `.loc.start` could be undefined for `new.target` `meta` nodes.
## 8.11.2 (2023-10-27)
### Bug fixes
Fix a bug that caused regular expressions after colon tokens to not be properly tokenized in some circumstances.
## 8.11.1 (2023-10-26)
### Bug fixes
Fix a regression where `onToken` would receive 'name' tokens for 'new' keyword tokens.
## 8.11.0 (2023-10-26)
### Bug fixes
Fix an issue where tokenizing (without parsing) an object literal with a property named `class` or `function` could, in some circumstance, put the tokenizer into an invalid state.
Fix an issue where a slash after a call to a propery named the same as some keywords would be tokenized as a regular expression.
### New features
Upgrade to Unicode 15.1.
Use a set of new, much more precise, TypeScript types.
## 8.10.0 (2023-07-05)
### New features
Add a `checkPrivateFields` option that disables strict checking of private property use.
## 8.9.0 (2023-06-16)
### Bug fixes
Forbid dynamic import after `new`, even when part of a member expression.
### New features
Add Unicode properties for ES2023.
Add support for the `v` flag to regular expressions.
## 8.8.2 (2023-01-23)
### Bug fixes
Fix a bug that caused `allowHashBang` to be set to false when not provided, even with `ecmaVersion >= 14`.
Fix an exception when passing no option object to `parse` or `new Parser`.
Fix incorrect parse error on `if (0) let\n[astral identifier char]`.
## 8.8.1 (2022-10-24)
### Bug fixes
Make type for `Comment` compatible with estree types.
## 8.8.0 (2022-07-21)
### Bug fixes
Allow parentheses around spread args in destructuring object assignment.
Fix an issue where the tree contained `directive` properties in when parsing with a language version that doesn't support them.
### New features
Support hashbang comments by default in ECMAScript 2023 and later.
## 8.7.1 (2021-04-26)
### Bug fixes
Stop handling `"use strict"` directives in ECMAScript versions before 5.
Fix an issue where duplicate quoted export names in `export *` syntax were incorrectly checked.
Add missing type for `tokTypes`.
## 8.7.0 (2021-12-27)
### New features
Support quoted export names.
Upgrade to Unicode 14.
Add support for Unicode 13 properties in regular expressions.
### Bug fixes
Use a loop to find line breaks, because the existing regexp search would overrun the end of the searched range and waste a lot of time in minified code.
## 8.6.0 (2021-11-18)
### Bug fixes
Fix a bug where an object literal with multiple `__proto__` properties would incorrectly be accepted if a later property value held an assigment.
### New features
Support class private fields with the `in` operator.
## 8.5.0 (2021-09-06)
### Bug fixes
Improve context-dependent tokenization in a number of corner cases.
Fix location tracking after a 0x2028 or 0x2029 character in a string literal (which before did not increase the line number).
Fix an issue where arrow function bodies in for loop context would inappropriately consume `in` operators.
Fix wrong end locations stored on SequenceExpression nodes.
Implement restriction that `for`/`of` loop LHS can't start with `let`.
### New features
Add support for ES2022 class static blocks.
Allow multiple input files to be passed to the CLI tool.
## 8.4.1 (2021-06-24)
### Bug fixes
Fix a bug where `allowAwaitOutsideFunction` would allow `await` in class field initializers, and setting `ecmaVersion` to 13 or higher would allow top-level await in non-module sources.
## 8.4.0 (2021-06-11)
### New features
A new option, `allowSuperOutsideMethod`, can be used to suppress the error when `super` is used in the wrong context.
## 8.3.0 (2021-05-31)
### New features
Default `allowAwaitOutsideFunction` to true for ECMAScript 2022 an higher.
Add support for the `d` ([indices](https://github.com/tc39/proposal-regexp-match-indices)) regexp flag.
## 8.2.4 (2021-05-04)
### Bug fixes
Fix spec conformity in corner case 'for await (async of ...)'.
## 8.2.3 (2021-05-04)
### Bug fixes
Fix an issue where the library couldn't parse 'for (async of ...)'.
Fix a bug in UTF-16 decoding that would read characters incorrectly in some circumstances.
## 8.2.2 (2021-04-29)
### Bug fixes
Fix a bug where a class field initialized to an async arrow function wouldn't allow await inside it. Same issue existed for generator arrow functions with yield.
## 8.2.1 (2021-04-24)
### Bug fixes
Fix a regression introduced in 8.2.0 where static or async class methods with keyword names fail to parse.
## 8.2.0 (2021-04-24)
### New features
Add support for ES2022 class fields and private methods.
## 8.1.1 (2021-04-12)
### Various
Stop shipping source maps in the NPM package.
## 8.1.0 (2021-03-09)
### Bug fixes
Fix a spurious error in nested destructuring arrays.
### New features
Expose `allowAwaitOutsideFunction` in CLI interface.
Make `allowImportExportAnywhere` also apply to `import.meta`.
## 8.0.5 (2021-01-25)
### Bug fixes
Adjust package.json to work with Node 12.16.0 and 13.0-13.6.
## 8.0.4 (2020-10-05)
### Bug fixes
Make `await x ** y` an error, following the spec.
Fix potentially exponential regular expression.
## 8.0.3 (2020-10-02)
### Bug fixes
Fix a wasteful loop during `Parser` creation when setting `ecmaVersion` to `"latest"`.
## 8.0.2 (2020-09-30)
### Bug fixes
Make the TypeScript types reflect the current allowed values for `ecmaVersion`.
Fix another regexp/division tokenizer issue.
## 8.0.1 (2020-08-12)
### Bug fixes
Provide the correct value in the `version` export.
## 8.0.0 (2020-08-12)
### Bug fixes
Disallow expressions like `(a = b) = c`.
Make non-octal escape sequences a syntax error in strict mode.
### New features
The package can now be loaded directly as an ECMAScript module in node 13+.
Update to the set of Unicode properties from ES2021.
### Breaking changes
The `ecmaVersion` option is now required. For the moment, omitting it will still work with a warning, but that will change in a future release.
Some changes to method signatures that may be used by plugins.
## 7.4.0 (2020-08-03)
### New features
Add support for logical assignment operators.
Add support for numeric separators.
## 7.3.1 (2020-06-11)
### Bug fixes
Make the string in the `version` export match the actual library version.
## 7.3.0 (2020-06-11)
### Bug fixes
Fix a bug that caused parsing of object patterns with a property named `set` that had a default value to fail.
### New features
Add support for optional chaining (`?.`).
## 7.2.0 (2020-05-09)
### Bug fixes
Fix precedence issue in parsing of async arrow functions.
### New features
Add support for nullish coalescing.
Add support for `import.meta`.
Support `export * as ...` syntax.
Upgrade to Unicode 13.
## 6.4.1 (2020-03-09)
### Bug fixes
More carefully check for valid UTF16 surrogate pairs in regexp validator.
## 7.1.1 (2020-03-01)
### Bug fixes
Treat `\8` and `\9` as invalid escapes in template strings.
Allow unicode escapes in property names that are keywords.
Don't error on an exponential operator expression as argument to `await`.
More carefully check for valid UTF16 surrogate pairs in regexp validator.
## 7.1.0 (2019-09-24)
### Bug fixes
Disallow trailing object literal commas when ecmaVersion is less than 5.
### New features
Add a static `acorn` property to the `Parser` class that contains the entire module interface, to allow plugins to access the instance of the library that they are acting on.
## 7.0.0 (2019-08-13)
### Breaking changes
Changes the node format for dynamic imports to use the `ImportExpression` node type, as defined in [ESTree](https://github.com/estree/estree/blob/master/es2020.md#importexpression).
Makes 10 (ES2019) the default value for the `ecmaVersion` option.
## 6.3.0 (2019-08-12)
### New features
`sourceType: "module"` can now be used even when `ecmaVersion` is less than 6, to parse module-style code that otherwise conforms to an older standard.
## 6.2.1 (2019-07-21)
### Bug fixes
Fix bug causing Acorn to treat some characters as identifier characters that shouldn't be treated as such.
Fix issue where setting the `allowReserved` option to `"never"` allowed reserved words in some circumstances.
## 6.2.0 (2019-07-04)
### Bug fixes
Improve valid assignment checking in `for`/`in` and `for`/`of` loops.
Disallow binding `let` in patterns.
### New features
Support bigint syntax with `ecmaVersion` >= 11.
Support dynamic `import` syntax with `ecmaVersion` >= 11.
Upgrade to Unicode version 12.
## 6.1.1 (2019-02-27)
### Bug fixes
Fix bug that caused parsing default exports of with names to fail.
## 6.1.0 (2019-02-08)
### Bug fixes
Fix scope checking when redefining a `var` as a lexical binding.
### New features
Split up `parseSubscripts` to use an internal `parseSubscript` method to make it easier to extend with plugins.
## 6.0.7 (2019-02-04)
### Bug fixes
Check that exported bindings are defined.
Don't treat `\u180e` as a whitespace character.
Check for duplicate parameter names in methods.
Don't allow shorthand properties when they are generators or async methods.
Forbid binding `await` in async arrow function's parameter list.
## 6.0.6 (2019-01-30)
### Bug fixes
The content of class declarations and expressions is now always parsed in strict mode.
Don't allow `let` or `const` to bind the variable name `let`.
Treat class declarations as lexical.
Don't allow a generator function declaration as the sole body of an `if` or `else`.
Ignore `"use strict"` when after an empty statement.
Allow string line continuations with special line terminator characters.
Treat `for` bodies as part of the `for` scope when checking for conflicting bindings.
Fix bug with parsing `yield` in a `for` loop initializer.
Implement special cases around scope checking for functions.
## 6.0.5 (2019-01-02)
### Bug fixes
Fix TypeScript type for `Parser.extend` and add `allowAwaitOutsideFunction` to options type.
Don't treat `let` as a keyword when the next token is `{` on the next line.
Fix bug that broke checking for parentheses around an object pattern in a destructuring assignment when `preserveParens` was on.
## 6.0.4 (2018-11-05)
### Bug fixes
Further improvements to tokenizing regular expressions in corner cases.
## 6.0.3 (2018-11-04)
### Bug fixes
Fix bug in tokenizing an expression-less return followed by a function followed by a regular expression.
Remove stray symlink in the package tarball.
## 6.0.2 (2018-09-26)
### Bug fixes
Fix bug where default expressions could fail to parse inside an object destructuring assignment expression.
## 6.0.1 (2018-09-14)
### Bug fixes
Fix wrong value in `version` export.
## 6.0.0 (2018-09-14)
### Bug fixes
Better handle variable-redefinition checks for catch bindings and functions directly under if statements.
Forbid `new.target` in top-level arrow functions.
Fix issue with parsing a regexp after `yield` in some contexts.
### New features
The package now comes with TypeScript definitions.
### Breaking changes
The default value of the `ecmaVersion` option is now 9 (2018).
Plugins work differently, and will have to be rewritten to work with this version.
The loose parser and walker have been moved into separate packages (`acorn-loose` and `acorn-walk`).
## 5.7.3 (2018-09-10)
### Bug fixes
Fix failure to tokenize regexps after expressions like `x.of`.
Better error message for unterminated template literals.
## 5.7.2 (2018-08-24)
### Bug fixes
Properly handle `allowAwaitOutsideFunction` in for statements.
Treat function declarations at the top level of modules like let bindings.
Don't allow async function declarations as the only statement under a label.
## 5.7.0 (2018-06-15)
### New features
Upgraded to Unicode 11.
## 5.6.0 (2018-05-31)
### New features
Allow U+2028 and U+2029 in string when ECMAVersion >= 10.
Allow binding-less catch statements when ECMAVersion >= 10.
Add `allowAwaitOutsideFunction` option for parsing top-level `await`.
## 5.5.3 (2018-03-08)
### Bug fixes
A _second_ republish of the code in 5.5.1, this time with yarn, to hopefully get valid timestamps.
## 5.5.2 (2018-03-08)
### Bug fixes
A republish of the code in 5.5.1 in an attempt to solve an issue with the file timestamps in the npm package being 0.
## 5.5.1 (2018-03-06)
### Bug fixes
Fix misleading error message for octal escapes in template strings.
## 5.5.0 (2018-02-27)
### New features
The identifier character categorization is now based on Unicode version 10.
Acorn will now validate the content of regular expressions, including new ES9 features.
## 5.4.0 (2018-02-01)
### Bug fixes
Disallow duplicate or escaped flags on regular expressions.
Disallow octal escapes in strings in strict mode.
### New features
Add support for async iteration.
Add support for object spread and rest.
## 5.3.0 (2017-12-28)
### Bug fixes
Fix parsing of floating point literals with leading zeroes in loose mode.
Allow duplicate property names in object patterns.
Don't allow static class methods named `prototype`.
Disallow async functions directly under `if` or `else`.
Parse right-hand-side of `for`/`of` as an assignment expression.
Stricter parsing of `for`/`in`.
Don't allow unicode escapes in contextual keywords.
### New features
Parsing class members was factored into smaller methods to allow plugins to hook into it.
## 5.2.1 (2017-10-30)
### Bug fixes
Fix a token context corruption bug.
## 5.2.0 (2017-10-30)
### Bug fixes
Fix token context tracking for `class` and `function` in property-name position.
Make sure `%*` isn't parsed as a valid operator.
Allow shorthand properties `get` and `set` to be followed by default values.
Disallow `super` when not in callee or object position.
### New features
Support [`directive` property](https://github.com/estree/estree/compare/b3de58c9997504d6fba04b72f76e6dd1619ee4eb...1da8e603237144f44710360f8feb7a9977e905e0) on directive expression statements.
## 5.1.2 (2017-09-04)
### Bug fixes
Disable parsing of legacy HTML-style comments in modules.
Fix parsing of async methods whose names are keywords.
## 5.1.1 (2017-07-06)
### Bug fixes
Fix problem with disambiguating regexp and division after a class.
## 5.1.0 (2017-07-05)
### Bug fixes
Fix tokenizing of regexps in an object-desctructuring `for`/`of` loop and after `yield`.
Parse zero-prefixed numbers with non-octal digits as decimal.
Allow object/array patterns in rest parameters.
Don't error when `yield` is used as a property name.
Allow `async` as a shorthand object property.
### New features
Implement the [template literal revision proposal](https://github.com/tc39/proposal-template-literal-revision) for ES9.
## 5.0.3 (2017-04-01)
### Bug fixes
Fix spurious duplicate variable definition errors for named functions.
## 5.0.2 (2017-03-30)
### Bug fixes
A binary operator after a parenthesized arrow expression is no longer incorrectly treated as an error.
## 5.0.0 (2017-03-28)
### Bug fixes
Raise an error for duplicated lexical bindings.
Fix spurious error when an assignement expression occurred after a spread expression.
Accept regular expressions after `of` (in `for`/`of`), `yield` (in a generator), and braced arrow functions.
Allow labels in front or `var` declarations, even in strict mode.
### Breaking changes
Parse declarations following `export default` as declaration nodes, not expressions. This means that class and function declarations nodes can now have `null` as their `id`.
## 4.0.11 (2017-02-07)
### Bug fixes
Allow all forms of member expressions to be parenthesized as lvalue.
## 4.0.10 (2017-02-07)
### Bug fixes
Don't expect semicolons after default-exported functions or classes, even when they are expressions.
Check for use of `'use strict'` directives in non-simple parameter functions, even when already in strict mode.
## 4.0.9 (2017-02-06)
### Bug fixes
Fix incorrect error raised for parenthesized simple assignment targets, so that `(x) = 1` parses again.
## 4.0.8 (2017-02-03)
### Bug fixes
Solve spurious parenthesized pattern errors by temporarily erring on the side of accepting programs that our delayed errors don't handle correctly yet.
## 4.0.7 (2017-02-02)
### Bug fixes
Accept invalidly rejected code like `(x).y = 2` again.
Don't raise an error when a function _inside_ strict code has a non-simple parameter list.
## 4.0.6 (2017-02-02)
### Bug fixes
Fix exponential behavior (manifesting itself as a complete hang for even relatively small source files) introduced by the new 'use strict' check.
## 4.0.5 (2017-02-02)
### Bug fixes
Disallow parenthesized pattern expressions.
Allow keywords as export names.
Don't allow the `async` keyword to be parenthesized.
Properly raise an error when a keyword contains a character escape.
Allow `"use strict"` to appear after other string literal expressions.
Disallow labeled declarations.
## 4.0.4 (2016-12-19)
### Bug fixes
Fix crash when `export` was followed by a keyword that can't be
exported.
## 4.0.3 (2016-08-16)
### Bug fixes
Allow regular function declarations inside single-statement `if` branches in loose mode. Forbid them entirely in strict mode.
Properly parse properties named `async` in ES2017 mode.
Fix bug where reserved words were broken in ES2017 mode.
## 4.0.2 (2016-08-11)
### Bug fixes
Don't ignore period or 'e' characters after octal numbers.
Fix broken parsing for call expressions in default parameter values of arrow functions.
## 4.0.1 (2016-08-08)
### Bug fixes
Fix false positives in duplicated export name errors.
## 4.0.0 (2016-08-07)
### Breaking changes
The default `ecmaVersion` option value is now 7.
A number of internal method signatures changed, so plugins might need to be updated.
### Bug fixes
The parser now raises errors on duplicated export names.
`arguments` and `eval` can now be used in shorthand properties.
Duplicate parameter names in non-simple argument lists now always produce an error.
### New features
The `ecmaVersion` option now also accepts year-style version numbers
(2015, etc).
Support for `async`/`await` syntax when `ecmaVersion` is >= 8.
Support for trailing commas in call expressions when `ecmaVersion` is >= 8.
## 3.3.0 (2016-07-25)
### Bug fixes
Fix bug in tokenizing of regexp operator after a function declaration.
Fix parser crash when parsing an array pattern with a hole.
### New features
Implement check against complex argument lists in functions that enable strict mode in ES7.
## 3.2.0 (2016-06-07)
### Bug fixes
Improve handling of lack of unicode regexp support in host
environment.
Properly reject shorthand properties whose name is a keyword.
### New features
Visitors created with `visit.make` now have their base as _prototype_, rather than copying properties into a fresh object.
## 3.1.0 (2016-04-18)
### Bug fixes
Properly tokenize the division operator directly after a function expression.
Allow trailing comma in destructuring arrays.
## 3.0.4 (2016-02-25)
### Fixes
Allow update expressions as left-hand-side of the ES7 exponential operator.
## 3.0.2 (2016-02-10)
### Fixes
Fix bug that accidentally made `undefined` a reserved word when parsing ES7.
## 3.0.0 (2016-02-10)
### Breaking changes
The default value of the `ecmaVersion` option is now 6 (used to be 5).
Support for comprehension syntax (which was dropped from the draft spec) has been removed.
### Fixes
`let` and `yield` are now “contextual keywords”, meaning you can mostly use them as identifiers in ES5 non-strict code.
A parenthesized class or function expression after `export default` is now parsed correctly.
### New features
When `ecmaVersion` is set to 7, Acorn will parse the exponentiation operator (`**`).
The identifier character ranges are now based on Unicode 8.0.0.
Plugins can now override the `raiseRecoverable` method to override the way non-critical errors are handled.
## 2.7.0 (2016-01-04)
### Fixes
Stop allowing rest parameters in setters.
Disallow `y` rexexp flag in ES5.
Disallow `\00` and `\000` escapes in strict mode.
Raise an error when an import name is a reserved word.
## 2.6.2 (2015-11-10)
### Fixes
Don't crash when no options object is passed.
## 2.6.0 (2015-11-09)
### Fixes
Add `await` as a reserved word in module sources.
Disallow `yield` in a parameter default value for a generator.
Forbid using a comma after a rest pattern in an array destructuring.
### New features
Support parsing stdin in command-line tool.
## 2.5.0 (2015-10-27)
### Fixes
Fix tokenizer support in the command-line tool.
Stop allowing `new.target` outside of functions.
Remove legacy `guard` and `guardedHandler` properties from try nodes.
Stop allowing multiple `__proto__` properties on an object literal in strict mode.
Don't allow rest parameters to be non-identifier patterns.
Check for duplicate paramter names in arrow functions.

View File

@@ -0,0 +1,13 @@
'use strict'
import pino from '../../pino.js'
import { join } from 'node:path'
const log = pino({
transport: {
target: join(import.meta.dirname, 'to-file-transport.js'),
options: { destination: process.argv[2] }
}
})
export { log }

View File

@@ -0,0 +1,20 @@
"use strict";
module.exports.mixin = function mixin(target, source) {
const keys = Object.getOwnPropertyNames(source);
for (let i = 0; i < keys.length; ++i) {
Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i]));
}
};
module.exports.wrapperSymbol = Symbol("wrapper");
module.exports.implSymbol = Symbol("impl");
module.exports.wrapperForImpl = function (impl) {
return impl[module.exports.wrapperSymbol];
};
module.exports.implForWrapper = function (wrapper) {
return wrapper[module.exports.implSymbol];
};

View File

@@ -0,0 +1,177 @@
'use strict';
var parse = require('../');
var test = require('tape');
test('flag boolean default false', function (t) {
var argv = parse(['moo'], {
boolean: ['t', 'verbose'],
default: { verbose: false, t: false },
});
t.deepEqual(argv, {
verbose: false,
t: false,
_: ['moo'],
});
t.deepEqual(typeof argv.verbose, 'boolean');
t.deepEqual(typeof argv.t, 'boolean');
t.end();
});
test('boolean groups', function (t) {
var argv = parse(['-x', '-z', 'one', 'two', 'three'], {
boolean: ['x', 'y', 'z'],
});
t.deepEqual(argv, {
x: true,
y: false,
z: true,
_: ['one', 'two', 'three'],
});
t.deepEqual(typeof argv.x, 'boolean');
t.deepEqual(typeof argv.y, 'boolean');
t.deepEqual(typeof argv.z, 'boolean');
t.end();
});
test('boolean and alias with chainable api', function (t) {
var aliased = ['-h', 'derp'];
var regular = ['--herp', 'derp'];
var aliasedArgv = parse(aliased, {
boolean: 'herp',
alias: { h: 'herp' },
});
var propertyArgv = parse(regular, {
boolean: 'herp',
alias: { h: 'herp' },
});
var expected = {
herp: true,
h: true,
_: ['derp'],
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.end();
});
test('boolean and alias with options hash', function (t) {
var aliased = ['-h', 'derp'];
var regular = ['--herp', 'derp'];
var opts = {
alias: { h: 'herp' },
boolean: 'herp',
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
var expected = {
herp: true,
h: true,
_: ['derp'],
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.end();
});
test('boolean and alias array with options hash', function (t) {
var aliased = ['-h', 'derp'];
var regular = ['--herp', 'derp'];
var alt = ['--harp', 'derp'];
var opts = {
alias: { h: ['herp', 'harp'] },
boolean: 'h',
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
var altPropertyArgv = parse(alt, opts);
var expected = {
harp: true,
herp: true,
h: true,
_: ['derp'],
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.same(altPropertyArgv, expected);
t.end();
});
test('boolean and alias using explicit true', function (t) {
var aliased = ['-h', 'true'];
var regular = ['--herp', 'true'];
var opts = {
alias: { h: 'herp' },
boolean: 'h',
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
var expected = {
herp: true,
h: true,
_: [],
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.end();
});
// regression, see https://github.com/substack/node-optimist/issues/71
test('boolean and --x=true', function (t) {
var parsed = parse(['--boool', '--other=true'], {
boolean: 'boool',
});
t.same(parsed.boool, true);
t.same(parsed.other, 'true');
parsed = parse(['--boool', '--other=false'], {
boolean: 'boool',
});
t.same(parsed.boool, true);
t.same(parsed.other, 'false');
t.end();
});
test('boolean --boool=true', function (t) {
var parsed = parse(['--boool=true'], {
default: {
boool: false,
},
boolean: ['boool'],
});
t.same(parsed.boool, true);
t.end();
});
test('boolean --boool=false', function (t) {
var parsed = parse(['--boool=false'], {
default: {
boool: true,
},
boolean: ['boool'],
});
t.same(parsed.boool, false);
t.end();
});
test('boolean using something similar to true', function (t) {
var opts = { boolean: 'h' };
var result = parse(['-h', 'true.txt'], opts);
var expected = {
h: true,
_: ['true.txt'],
};
t.same(result, expected);
t.end();
});

View File

@@ -0,0 +1,39 @@
'use strict'
const nullTime = () => ''
const epochTime = () => `,"time":${Date.now()}`
const unixTime = () => `,"time":${Math.round(Date.now() / 1000.0)}`
const isoTime = () => `,"time":"${new Date(Date.now()).toISOString()}"` // using Date.now() for testability
const NS_PER_MS = 1_000_000n
const NS_PER_SEC = 1_000_000_000n
const startWallTimeNs = BigInt(Date.now()) * NS_PER_MS
const startHrTime = process.hrtime.bigint()
const isoTimeNano = () => {
const elapsedNs = process.hrtime.bigint() - startHrTime
const currentTimeNs = startWallTimeNs + elapsedNs
const secondsSinceEpoch = currentTimeNs / NS_PER_SEC
const nanosWithinSecond = currentTimeNs % NS_PER_SEC
const msSinceEpoch = Number(secondsSinceEpoch * 1000n + nanosWithinSecond / 1_000_000n)
const date = new Date(msSinceEpoch)
const year = date.getUTCFullYear()
const month = (date.getUTCMonth() + 1).toString().padStart(2, '0')
const day = date.getUTCDate().toString().padStart(2, '0')
const hours = date.getUTCHours().toString().padStart(2, '0')
const minutes = date.getUTCMinutes().toString().padStart(2, '0')
const seconds = date.getUTCSeconds().toString().padStart(2, '0')
return `,"time":"${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${nanosWithinSecond
.toString()
.padStart(9, '0')}Z"`
}
module.exports = { nullTime, epochTime, unixTime, isoTime, isoTimeNano }