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,96 @@
/**
* @fileoverview Enforce a maximum number of classes per file
* @author James Garbutt <https://github.com/43081j>
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Enforce a maximum number of classes per file",
recommended: false,
url: "https://eslint.org/docs/latest/rules/max-classes-per-file",
},
schema: [
{
oneOf: [
{
type: "integer",
minimum: 1,
},
{
type: "object",
properties: {
ignoreExpressions: {
type: "boolean",
},
max: {
type: "integer",
minimum: 1,
},
},
additionalProperties: false,
},
],
},
],
defaultOptions: [1],
messages: {
maximumExceeded:
"File has too many classes ({{ classCount }}). Maximum allowed is {{ max }}.",
},
},
create(context) {
const option = context.options[0];
const [ignoreExpressions, max] =
typeof option === "number"
? [false, option]
: [option.ignoreExpressions, option.max || 1];
let classCount = 0;
return {
Program() {
classCount = 0;
},
"Program:exit"(node) {
if (classCount > max) {
context.report({
node,
loc: {
start: node.body[0].loc.start,
end: node.body.at(-1).loc.end,
},
messageId: "maximumExceeded",
data: {
classCount,
max,
},
});
}
},
ClassDeclaration() {
classCount++;
},
ClassExpression() {
if (!ignoreExpressions) {
classCount++;
}
},
};
},
};

View File

@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = rng;
var _crypto = _interopRequireDefault(require("crypto"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate
let poolPtr = rnds8Pool.length;
function rng() {
if (poolPtr > rnds8Pool.length - 16) {
_crypto.default.randomFillSync(rnds8Pool);
poolPtr = 0;
}
return rnds8Pool.slice(poolPtr, poolPtr += 16);
}

View File

@@ -0,0 +1,10 @@
import { URISchemeHandler, URIComponents, URIOptions } from "../uri";
export interface URNComponents extends URIComponents {
nid?: string;
nss?: string;
}
export interface URNOptions extends URIOptions {
nid?: string;
}
declare const handler: URISchemeHandler<URNComponents, URNOptions>;
export default handler;

View File

@@ -0,0 +1,22 @@
import type { MinimatchOptions, MMRegExp } from './index.js';
export type ExtglobType = '!' | '?' | '+' | '*' | '@';
export declare class AST {
#private;
type: ExtglobType | null;
id: number;
get depth(): number;
constructor(type: ExtglobType | null, parent?: AST, options?: MinimatchOptions);
get hasMagic(): boolean | undefined;
toString(): string;
push(...parts: (string | AST)[]): void;
toJSON(): unknown[];
isStart(): boolean;
isEnd(): boolean;
copyIn(part: AST | string): void;
clone(parent: AST): AST;
static fromGlob(pattern: string, options?: MinimatchOptions): AST;
toMMPattern(): MMRegExp | string;
get options(): MinimatchOptions;
toRegExpSource(allowDot?: boolean): [re: string, body: string, hasMagic: boolean, uflag: boolean];
}
//# sourceMappingURL=ast.d.ts.map

View File

@@ -0,0 +1,210 @@
/**
* Negates a boolean type.
*/
export type Not<T extends boolean> = T extends true ? false : true;
/**
* Returns `true` if at least one of the types in the
* {@linkcode Types} array is `true`, otherwise returns `false`.
*/
export type Or<Types extends boolean[]> = Types[number] extends false ? false : true;
/**
* Checks if all the boolean types in the {@linkcode Types} array are `true`.
*/
export type And<Types extends boolean[]> = Types[number] extends true ? true : false;
/**
* Represents an equality type that returns {@linkcode Right} if
* {@linkcode Left} is `true`,
* otherwise returns the negation of {@linkcode Right}.
*/
export type Eq<Left extends boolean, Right extends boolean> = Left extends true ? Right : Not<Right>;
/**
* Represents the exclusive OR operation on a tuple of boolean types.
* Returns `true` if exactly one of the boolean types is `true`,
* otherwise returns `false`.
*/
export type Xor<Types extends [boolean, boolean]> = Not<Eq<Types[0], Types[1]>>;
/**
* @internal
*/
declare const secret: unique symbol;
/**
* @internal
*/
type Secret = typeof secret;
/**
* Checks if the given type is `never`.
*/
export type IsNever<T> = [T] extends [never] ? true : false;
/**
* Checks if the given type is `any`.
*/
export type IsAny<T> = [T] extends [Secret] ? Not<IsNever<T>> : false;
/**
* Determines if the given type is `unknown`.
*/
export type IsUnknown<T> = [unknown] extends [T] ? Not<IsAny<T>> : false;
/**
* Determines if a type is either `never` or `any`.
*/
export type IsNeverOrAny<T> = Or<[IsNever<T>, IsAny<T>]>;
/**
* Subjective "useful" keys from a type. For objects it's just `keyof` but for
* tuples/arrays it's the number keys.
*
* @example
* ```ts
* UsefulKeys<{ a: 1; b: 2 }> // 'a' | 'b'
*
* UsefulKeys<['a', 'b']> // '0' | '1'
*
* UsefulKeys<string[]> // number
* ```
*/
export type UsefulKeys<T> = T extends any[] ? {
[K in keyof T]: K;
}[number] : keyof T;
/**
* Extracts the keys from a type that are required (not optional).
*/
export type RequiredKeys<T> = Extract<{
[K in keyof T]-?: {} extends Pick<T, K> ? never : K;
}[keyof T], keyof T>;
/**
* Gets the keys of an object type that are optional.
*/
export type OptionalKeys<T> = Exclude<keyof T, RequiredKeys<T>>;
/**
* Extracts the keys from a type that are not `readonly`.
*/
export type ReadonlyKeys<T> = Extract<{
[K in keyof T]-?: ReadonlyEquivalent<{
[_K in K]: T[K];
}, {
-readonly [_K in K]: T[K];
}> extends true ? never : K;
}[keyof T], keyof T>;
/**
* Determines if two types, are equivalent in a `readonly` manner.
*
* @internal
*/
type ReadonlyEquivalent<X, Y> = Extends<(<T>() => T extends X ? true : false), (<T>() => T extends Y ? true : false)>;
/**
* Checks if one type extends another. Note: this is not quite the same as `Left extends Right` because:
* 1. If either type is `never`, the result is `true` iff the other type is also `never`.
* 2. Types are wrapped in a 1-tuple so that union types are not distributed - instead we consider `string | number` to _not_ extend `number`. If we used `Left extends Right` directly you would get `Extends<string | number, number>` => `false | true` => `boolean`.
*/
export type Extends<Left, Right> = IsNever<Left> extends true ? IsNever<Right> : [Left] extends [Right] ? true : false;
/**
* Checks if the {@linkcode Left} type extends the {@linkcode Right} type,
* excluding `any` or `never`.
*/
export type ExtendsExcludingAnyOrNever<Left, Right> = IsAny<Left> extends true ? IsAny<Right> : Extends<Left, Right>;
/**
* Checks if two types are strictly equal using
* the TypeScript internal identical-to operator.
*
* @see {@link https://github.com/microsoft/TypeScript/issues/55188#issuecomment-1656328122 | much history}
*/
export type StrictEqualUsingTSInternalIdenticalToOperator<L, R> = (<T>() => T extends (L & T) | T ? true : false) extends <T>() => T extends (R & T) | T ? true : false ? IsNever<L> extends IsNever<R> ? true : false : false;
/**
* Checks that {@linkcode Left} and {@linkcode Right} extend each other.
* Not quite the same as an equality check since `any` can make it resolve
* to `true`. So should only be used when {@linkcode Left} and
* {@linkcode Right} are known to avoid `any`.
*/
export type MutuallyExtends<Left, Right> = And<[Extends<Left, Right>, Extends<Right, Left>]>;
/**
* @internal
*/
declare const mismatch: unique symbol;
/**
* @internal
*/
type Mismatch = {
[mismatch]: 'mismatch';
};
/**
* A type which should match anything passed as a value but *doesn't*
* match {@linkcode Mismatch}. It helps TypeScript select the right overload
* for {@linkcode PositiveExpectTypeOf.toEqualTypeOf | .toEqualTypeOf()} and
* {@linkcode PositiveExpectTypeOf.toMatchTypeOf | .toMatchTypeOf()}.
*
* @internal
*/
declare const avalue: unique symbol;
/**
* Represents a value that can be of various types.
*/
export type AValue = {
[avalue]?: undefined;
} | string | number | boolean | symbol | bigint | null | undefined | void;
/**
* Represents the type of mismatched arguments between
* the actual result and the expected result.
*
* If {@linkcode ActualResult} and {@linkcode ExpectedResult} are equivalent,
* the type resolves to an empty tuple `[]`, indicating no mismatch.
* If they are not equivalent, it resolves to a tuple containing the element
* {@linkcode Mismatch}, signifying a discrepancy between
* the expected and actual results.
*/
export type MismatchArgs<ActualResult extends boolean, ExpectedResult extends boolean> = Eq<ActualResult, ExpectedResult> extends true ? [] : [Mismatch];
/**
* Represents the options for the {@linkcode ExpectTypeOf} function.
*/
export interface ExpectTypeOfOptions {
positive: boolean;
branded: boolean;
}
/**
* Convert a union to an intersection.
* `A | B | C` -\> `A & B & C`
*/
export type UnionToIntersection<Union> = (Union extends any ? (distributedUnion: Union) => void : never) extends (mergedIntersection: infer Intersection) => void ? Intersection : never;
/**
* Get the last element of a union.
* First, converts to a union of `() => T` functions,
* then uses {@linkcode UnionToIntersection} to get the last one.
*/
export type LastOf<Union> = UnionToIntersection<Union extends any ? () => Union : never> extends () => infer R ? R : never;
/**
* Intermediate type for {@linkcode UnionToTuple} which pushes the
* "last" union member to the end of a tuple, and recursively prepends
* the remainder of the union.
*/
export type TuplifyUnion<Union, LastElement = LastOf<Union>> = IsNever<Union> extends true ? [] : [...TuplifyUnion<Exclude<Union, LastElement>>, LastElement];
/**
* Convert a union like `1 | 2 | 3` to a tuple like `[1, 2, 3]`.
*/
export type UnionToTuple<Union> = TuplifyUnion<Union>;
/** The numbers between 0 and 9 that you learned in school */
export type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
/**
* e.g. `['a', 'b']` -> `{ 0: 'a', 1: 'b' }`
* Looks at the keys to see which look digit-like, so could do the wrong thing for types like
* `['a', 'b'] & {'1foo': string}`
*/
export type TupleToRecord<T extends any[]> = {
[K in keyof T as `${Extract<K, `${Digit}${string}`>}`]: T[K];
};
/** `true` iff `T` is a tuple, as opposed to an indeterminate-length array */
export type IsTuple<T extends readonly any[]> = number extends T['length'] ? false : true;
/** `true` iff `T` is a record accepting any string keys, or accepting any number keys */
export type IsRecord<T> = Or<[Extends<string, keyof T>, Extends<number, keyof T>]>;
export type IsUnion<T> = Not<Extends<UnionToTuple<T>['length'], 1>>;
/**
* A recursive version of `Pick` that selects properties from the left type that are present in the right type.
* The "leaf" types from `Left` are used - only the keys of `Right` are considered.
*
* @example
* ```ts
* const user = {email: 'a@b.com', name: 'John Doe', address: {street: '123 2nd St', city: 'New York', zip: '10001', state: 'NY', country: 'USA'}}
*
* type Result = DeepPickMatchingProps<typeof user, {name: unknown; address: {city: unknown}}> // {name: string, address: {city: string}}
* ```
*/
export type DeepPickMatchingProps<Left, Right> = Left extends Record<string, unknown> ? Pick<{
[K in keyof Left]: K extends keyof Right ? DeepPickMatchingProps<Left[K], Right[K]> : never;
}, Extract<keyof Left, keyof Right>> : Left;
export {};

View File

@@ -0,0 +1,530 @@
/**
* Utils for modular division and fields.
* Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
* There is no division: it is replaced by modular multiplicative inverse.
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { _validateObject, anumber, bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, } from "../utils.js";
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);
// prettier-ignore
const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);
// prettier-ignore
const _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
// Calculates a modulo b
export function mod(a, b) {
const result = a % b;
return result >= _0n ? result : b + result;
}
/**
* Efficiently raise num to power and do modular division.
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
* @example
* pow(2n, 6n, 11n) // 64n % 11n == 9n
*/
export function pow(num, power, modulo) {
return FpPow(Field(modulo), num, power);
}
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
export function pow2(x, power, modulo) {
let res = x;
while (power-- > _0n) {
res *= res;
res %= modulo;
}
return res;
}
/**
* Inverses number over modulo.
* Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
*/
export function invert(number, modulo) {
if (number === _0n)
throw new Error('invert: expected non-zero number');
if (modulo <= _0n)
throw new Error('invert: expected positive modulus, got ' + modulo);
// Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
let a = mod(number, modulo);
let b = modulo;
// prettier-ignore
let x = _0n, y = _1n, u = _1n, v = _0n;
while (a !== _0n) {
// JIT applies optimization if those two lines follow each other
const q = b / a;
const r = b % a;
const m = x - u * q;
const n = y - v * q;
// prettier-ignore
b = a, a = r, x = u, y = v, u = m, v = n;
}
const gcd = b;
if (gcd !== _1n)
throw new Error('invert: does not exist');
return mod(x, modulo);
}
function assertIsSquare(Fp, root, n) {
if (!Fp.eql(Fp.sqr(root), n))
throw new Error('Cannot find square root');
}
// Not all roots are possible! Example which will throw:
// const NUM =
// n = 72057594037927816n;
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
function sqrt3mod4(Fp, n) {
const p1div4 = (Fp.ORDER + _1n) / _4n;
const root = Fp.pow(n, p1div4);
assertIsSquare(Fp, root, n);
return root;
}
function sqrt5mod8(Fp, n) {
const p5div8 = (Fp.ORDER - _5n) / _8n;
const n2 = Fp.mul(n, _2n);
const v = Fp.pow(n2, p5div8);
const nv = Fp.mul(n, v);
const i = Fp.mul(Fp.mul(nv, _2n), v);
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
assertIsSquare(Fp, root, n);
return root;
}
// Based on RFC9380, Kong algorithm
// prettier-ignore
function sqrt9mod16(P) {
const Fp_ = Field(P);
const tn = tonelliShanks(P);
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic
return (Fp, n) => {
let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4
let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1
const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1
const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1
const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x
const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x
tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x
tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x
const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x
const root = Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2
assertIsSquare(Fp, root, n);
return root;
};
}
/**
* Tonelli-Shanks square root search algorithm.
* 1. https://eprint.iacr.org/2012/685.pdf (page 12)
* 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
* @param P field order
* @returns function that takes field Fp (created from P) and number n
*/
export function tonelliShanks(P) {
// Initialization (precomputation).
// Caching initialization could boost perf by 7%.
if (P < _3n)
throw new Error('sqrt is not defined for small field');
// Factor P - 1 = Q * 2^S, where Q is odd
let Q = P - _1n;
let S = 0;
while (Q % _2n === _0n) {
Q /= _2n;
S++;
}
// Find the first quadratic non-residue Z >= 2
let Z = _2n;
const _Fp = Field(P);
while (FpLegendre(_Fp, Z) === 1) {
// Basic primality test for P. After x iterations, chance of
// not finding quadratic non-residue is 2^x, so 2^1000.
if (Z++ > 1000)
throw new Error('Cannot find square root: probably non-prime P');
}
// Fast-path; usually done before Z, but we do "primality test".
if (S === 1)
return sqrt3mod4;
// Slow-path
// TODO: test on Fp2 and others
let cc = _Fp.pow(Z, Q); // c = z^Q
const Q1div2 = (Q + _1n) / _2n;
return function tonelliSlow(Fp, n) {
if (Fp.is0(n))
return n;
// Check if n is a quadratic residue using Legendre symbol
if (FpLegendre(Fp, n) !== 1)
throw new Error('Cannot find square root');
// Initialize variables for the main loop
let M = S;
let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor
let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
// Main loop
// while t != 1
while (!Fp.eql(t, Fp.ONE)) {
if (Fp.is0(t))
return Fp.ZERO; // if t=0 return R=0
let i = 1;
// Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
let t_tmp = Fp.sqr(t); // t^(2^1)
while (!Fp.eql(t_tmp, Fp.ONE)) {
i++;
t_tmp = Fp.sqr(t_tmp); // t^(2^2)...
if (i === M)
throw new Error('Cannot find square root');
}
// Calculate the exponent for b: 2^(M - i - 1)
const exponent = _1n << BigInt(M - i - 1); // bigint is important
const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)
// Update variables
M = i;
c = Fp.sqr(b); // c = b^2
t = Fp.mul(t, c); // t = (t * b^2)
R = Fp.mul(R, b); // R = R*b
}
return R;
};
}
/**
* Square root for a finite field. Will try optimized versions first:
*
* 1. P ≡ 3 (mod 4)
* 2. P ≡ 5 (mod 8)
* 3. P ≡ 9 (mod 16)
* 4. Tonelli-Shanks algorithm
*
* Different algorithms can give different roots, it is up to user to decide which one they want.
* For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
*/
export function FpSqrt(P) {
// P ≡ 3 (mod 4) => √n = n^((P+1)/4)
if (P % _4n === _3n)
return sqrt3mod4;
// P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
if (P % _8n === _5n)
return sqrt5mod8;
// P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
if (P % _16n === _9n)
return sqrt9mod16(P);
// Tonelli-Shanks algorithm
return tonelliShanks(P);
}
// Little-endian check for first LE bit (last BE bit);
export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
// prettier-ignore
const FIELD_FIELDS = [
'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
'eql', 'add', 'sub', 'mul', 'pow', 'div',
'addN', 'subN', 'mulN', 'sqrN'
];
export function validateField(field) {
const initial = {
ORDER: 'bigint',
MASK: 'bigint',
BYTES: 'number',
BITS: 'number',
};
const opts = FIELD_FIELDS.reduce((map, val) => {
map[val] = 'function';
return map;
}, initial);
_validateObject(field, opts);
// const max = 16384;
// if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');
// if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');
return field;
}
// Generic field functions
/**
* Same as `pow` but for Fp: non-constant-time.
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
*/
export function FpPow(Fp, num, power) {
if (power < _0n)
throw new Error('invalid exponent, negatives unsupported');
if (power === _0n)
return Fp.ONE;
if (power === _1n)
return num;
let p = Fp.ONE;
let d = num;
while (power > _0n) {
if (power & _1n)
p = Fp.mul(p, d);
d = Fp.sqr(d);
power >>= _1n;
}
return p;
}
/**
* Efficiently invert an array of Field elements.
* Exception-free. Will return `undefined` for 0 elements.
* @param passZero map 0 to 0 (instead of undefined)
*/
export function FpInvertBatch(Fp, nums, passZero = false) {
const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
// Walk from first to last, multiply them by each other MOD p
const multipliedAcc = nums.reduce((acc, num, i) => {
if (Fp.is0(num))
return acc;
inverted[i] = acc;
return Fp.mul(acc, num);
}, Fp.ONE);
// Invert last element
const invertedAcc = Fp.inv(multipliedAcc);
// Walk from last to first, multiply them by inverted each other MOD p
nums.reduceRight((acc, num, i) => {
if (Fp.is0(num))
return acc;
inverted[i] = Fp.mul(acc, inverted[i]);
return Fp.mul(acc, num);
}, invertedAcc);
return inverted;
}
// TODO: remove
export function FpDiv(Fp, lhs, rhs) {
return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));
}
/**
* Legendre symbol.
* Legendre constant is used to calculate Legendre symbol (a | p)
* which denotes the value of a^((p-1)/2) (mod p).
*
* * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
* * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
* * (a | p) ≡ 0 if a ≡ 0 (mod p)
*/
export function FpLegendre(Fp, n) {
// We can use 3rd argument as optional cache of this value
// but seems unneeded for now. The operation is very fast.
const p1mod2 = (Fp.ORDER - _1n) / _2n;
const powered = Fp.pow(n, p1mod2);
const yes = Fp.eql(powered, Fp.ONE);
const zero = Fp.eql(powered, Fp.ZERO);
const no = Fp.eql(powered, Fp.neg(Fp.ONE));
if (!yes && !zero && !no)
throw new Error('invalid Legendre symbol result');
return yes ? 1 : zero ? 0 : -1;
}
// This function returns True whenever the value x is a square in the field F.
export function FpIsSquare(Fp, n) {
const l = FpLegendre(Fp, n);
return l === 1;
}
// CURVE.n lengths
export function nLength(n, nBitLength) {
// Bit size, byte size of CURVE.n
if (nBitLength !== undefined)
anumber(nBitLength);
const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
const nByteLength = Math.ceil(_nBitLength / 8);
return { nBitLength: _nBitLength, nByteLength };
}
/**
* Creates a finite field. Major performance optimizations:
* * 1. Denormalized operations like mulN instead of mul.
* * 2. Identical object shape: never add or remove keys.
* * 3. `Object.freeze`.
* Fragile: always run a benchmark on a change.
* Security note: operations don't check 'isValid' for all elements for performance reasons,
* it is caller responsibility to check this.
* This is low-level code, please make sure you know what you're doing.
*
* Note about field properties:
* * CHARACTERISTIC p = prime number, number of elements in main subgroup.
* * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
*
* @param ORDER field order, probably prime, or could be composite
* @param bitLen how many bits the field consumes
* @param isLE (default: false) if encoding / decoding should be in little-endian
* @param redef optional faster redefinitions of sqrt and other methods
*/
export function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?
isLE = false, opts = {}) {
if (ORDER <= _0n)
throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
let _nbitLength = undefined;
let _sqrt = undefined;
let modFromBytes = false;
let allowedLengths = undefined;
if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {
if (opts.sqrt || isLE)
throw new Error('cannot specify opts in two arguments');
const _opts = bitLenOrOpts;
if (_opts.BITS)
_nbitLength = _opts.BITS;
if (_opts.sqrt)
_sqrt = _opts.sqrt;
if (typeof _opts.isLE === 'boolean')
isLE = _opts.isLE;
if (typeof _opts.modFromBytes === 'boolean')
modFromBytes = _opts.modFromBytes;
allowedLengths = _opts.allowedLengths;
}
else {
if (typeof bitLenOrOpts === 'number')
_nbitLength = bitLenOrOpts;
if (opts.sqrt)
_sqrt = opts.sqrt;
}
const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
if (BYTES > 2048)
throw new Error('invalid field: expected ORDER of <= 2048 bytes');
let sqrtP; // cached sqrtP
const f = Object.freeze({
ORDER,
isLE,
BITS,
BYTES,
MASK: bitMask(BITS),
ZERO: _0n,
ONE: _1n,
allowedLengths: allowedLengths,
create: (num) => mod(num, ORDER),
isValid: (num) => {
if (typeof num !== 'bigint')
throw new Error('invalid field element: expected bigint, got ' + typeof num);
return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
},
is0: (num) => num === _0n,
// is valid and invertible
isValidNot0: (num) => !f.is0(num) && f.isValid(num),
isOdd: (num) => (num & _1n) === _1n,
neg: (num) => mod(-num, ORDER),
eql: (lhs, rhs) => lhs === rhs,
sqr: (num) => mod(num * num, ORDER),
add: (lhs, rhs) => mod(lhs + rhs, ORDER),
sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
pow: (num, power) => FpPow(f, num, power),
div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
// Same as above, but doesn't normalize
sqrN: (num) => num * num,
addN: (lhs, rhs) => lhs + rhs,
subN: (lhs, rhs) => lhs - rhs,
mulN: (lhs, rhs) => lhs * rhs,
inv: (num) => invert(num, ORDER),
sqrt: _sqrt ||
((n) => {
if (!sqrtP)
sqrtP = FpSqrt(ORDER);
return sqrtP(f, n);
}),
toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
fromBytes: (bytes, skipValidation = true) => {
if (allowedLengths) {
if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
}
const padded = new Uint8Array(BYTES);
// isLE add 0 to right, !isLE to the left.
padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
bytes = padded;
}
if (bytes.length !== BYTES)
throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
if (modFromBytes)
scalar = mod(scalar, ORDER);
if (!skipValidation)
if (!f.isValid(scalar))
throw new Error('invalid field element: outside of range 0..ORDER');
// NOTE: we don't validate scalar here, please use isValid. This done such way because some
// protocol may allow non-reduced scalar that reduced later or changed some other way.
return scalar;
},
// TODO: we don't need it here, move out to separate fn
invertBatch: (lst) => FpInvertBatch(f, lst),
// We can't move this out because Fp6, Fp12 implement it
// and it's unclear what to return in there.
cmov: (a, b, c) => (c ? b : a),
});
return Object.freeze(f);
}
// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?
// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).
// which mean we cannot force this via opts.
// Not sure what to do with randomBytes, we can accept it inside opts if wanted.
// Probably need to export getMinHashLength somewhere?
// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {
// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;
// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?
// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;
// return reduced;
// },
export function FpSqrtOdd(Fp, elm) {
if (!Fp.isOdd)
throw new Error("Field doesn't have isOdd");
const root = Fp.sqrt(elm);
return Fp.isOdd(root) ? root : Fp.neg(root);
}
export function FpSqrtEven(Fp, elm) {
if (!Fp.isOdd)
throw new Error("Field doesn't have isOdd");
const root = Fp.sqrt(elm);
return Fp.isOdd(root) ? Fp.neg(root) : root;
}
/**
* "Constant-time" private key generation utility.
* Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
* Which makes it slightly more biased, less secure.
* @deprecated use `mapKeyToField` instead
*/
export function hashToPrivateScalar(hash, groupOrder, isLE = false) {
hash = ensureBytes('privateHash', hash);
const hashLen = hash.length;
const minLen = nLength(groupOrder).nByteLength + 8;
if (minLen < 24 || hashLen < minLen || hashLen > 1024)
throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);
const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);
return mod(num, groupOrder - _1n) + _1n;
}
/**
* Returns total number of bytes consumed by the field element.
* For example, 32 bytes for usual 256-bit weierstrass curve.
* @param fieldOrder number of field elements, usually CURVE.n
* @returns byte length of field
*/
export function getFieldBytesLength(fieldOrder) {
if (typeof fieldOrder !== 'bigint')
throw new Error('field order must be bigint');
const bitLength = fieldOrder.toString(2).length;
return Math.ceil(bitLength / 8);
}
/**
* Returns minimal amount of bytes that can be safely reduced
* by field order.
* Should be 2^-128 for 128-bit curve such as P256.
* @param fieldOrder number of field elements, usually CURVE.n
* @returns byte length of target hash
*/
export function getMinHashLength(fieldOrder) {
const length = getFieldBytesLength(fieldOrder);
return length + Math.ceil(length / 2);
}
/**
* "Constant-time" private key generation utility.
* Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
* and convert them into private scalar, with the modulo bias being negligible.
* Needs at least 48 bytes of input for 32-byte private key.
* https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
* FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
* RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
* @param hash hash output from SHA3 or a similar function
* @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
* @param isLE interpret hash bytes as LE num
* @returns valid private scalar
*/
export function mapHashToField(key, fieldOrder, isLE = false) {
const len = key.length;
const fieldLen = getFieldBytesLength(fieldOrder);
const minLen = getMinHashLength(fieldOrder);
// No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
if (len < 16 || len < minLen || len > 1024)
throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
// `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
const reduced = mod(num, fieldOrder - _1n) + _1n;
return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
//# sourceMappingURL=modular.js.map

View File

@@ -0,0 +1,330 @@
import { expect, expectTypeOf, test } from "vitest";
import * as z from "zod/v4";
const stringMap = z.map(z.string(), z.string());
type stringMap = z.infer<typeof stringMap>;
const minTwo = stringMap.min(2);
const maxTwo = stringMap.max(2);
const justTwo = stringMap.size(2);
const nonEmpty = stringMap.nonempty();
const nonEmptyMax = stringMap.nonempty().max(2);
test("type inference", () => {
expectTypeOf<stringMap>().toEqualTypeOf<Map<string, string>>();
});
test("valid parse", () => {
const result = stringMap.safeParse(
new Map([
["first", "foo"],
["second", "bar"],
])
);
expect(result.success).toEqual(true);
expect(result.data).toMatchInlineSnapshot(`
Map {
"first" => "foo",
"second" => "bar",
}
`);
});
test("valid parse: size-related methods", () => {
expect(() => {
minTwo.parse(
new Map([
["a", "b"],
["c", "d"],
])
);
minTwo.parse(
new Map([
["a", "b"],
["c", "d"],
["e", "f"],
])
);
maxTwo.parse(
new Map([
["a", "b"],
["c", "d"],
])
);
maxTwo.parse(new Map([["a", "b"]]));
justTwo.parse(
new Map([
["a", "b"],
["c", "d"],
])
);
nonEmpty.parse(new Map([["a", "b"]]));
nonEmptyMax.parse(
new Map([
["a", "b"],
["c", "d"],
])
);
}).not.toThrow();
const sizeZeroResult = stringMap.parse(new Map());
expect(sizeZeroResult.size).toBe(0);
const sizeTwoResult = minTwo.parse(
new Map([
["a", "b"],
["c", "d"],
])
);
expect(sizeTwoResult.size).toBe(2);
});
test("failing when parsing empty map in nonempty ", () => {
const result = nonEmpty.safeParse(new Map());
expect(result.success).toEqual(false);
expect(result.error!.issues.length).toEqual(1);
expect(result.error!.issues[0].code).toEqual("too_small");
});
test("failing when map is bigger than max() ", () => {
const result = maxTwo.safeParse(
new Map([
["a", "b"],
["c", "d"],
["e", "f"],
])
);
expect(result.success).toEqual(false);
expect(result.error!.issues.length).toEqual(1);
expect(result.error!.issues[0].code).toEqual("too_big");
});
test("valid parse async", async () => {
const asyncMap = z.map(
z.string().refine(async () => false, "bad key"),
z.string().refine(async () => false, "bad value")
);
const result = await asyncMap.safeParseAsync(new Map([["first", "foo"]]));
expect(result.success).toEqual(false);
expect(result.error).toMatchInlineSnapshot(`
[ZodError: [
{
"code": "custom",
"path": [
"first"
],
"message": "bad key"
},
{
"code": "custom",
"path": [
"first"
],
"message": "bad value"
}
]]
`);
});
test("throws when a Set is given", () => {
const result = stringMap.safeParse(new Set([]));
expect(result.success).toEqual(false);
if (result.success === false) {
expect(result.error.issues.length).toEqual(1);
expect(result.error.issues[0].code).toEqual("invalid_type");
}
});
test("throws when the given map has invalid key and invalid input", () => {
const result = stringMap.safeParse(new Map([[42, Symbol()]]));
expect(result.success).toEqual(false);
if (result.success === false) {
expect(result.error.issues.length).toEqual(2);
expect(result.error).toMatchInlineSnapshot(`
[ZodError: [
{
"expected": "string",
"code": "invalid_type",
"path": [
42
],
"message": "Invalid input: expected string, received number"
},
{
"expected": "string",
"code": "invalid_type",
"path": [
42
],
"message": "Invalid input: expected string, received symbol"
}
]]
`);
}
});
test("throws when the given map has multiple invalid entries", () => {
// const result = stringMap.safeParse(new Map([[42, Symbol()]]));
const result = stringMap.safeParse(
new Map([
[1, "foo"],
["bar", 2],
] as [any, any][]) as Map<any, any>
);
// const result = stringMap.safeParse(new Map([[42, Symbol()]]));
expect(result.success).toEqual(false);
if (result.success === false) {
expect(result.error.issues.length).toEqual(2);
expect(result.error.issues).toMatchInlineSnapshot(`
[
{
"code": "invalid_type",
"expected": "string",
"message": "Invalid input: expected string, received number",
"path": [
1,
],
},
{
"code": "invalid_type",
"expected": "string",
"message": "Invalid input: expected string, received number",
"path": [
"bar",
],
},
]
`);
}
});
test("dirty", async () => {
const map = z.map(
z.string().refine((val) => val === val.toUpperCase(), {
message: "Keys must be uppercase",
}),
z.string()
);
const result = await map.spa(
new Map([
["first", "foo"],
["second", "bar"],
])
);
expect(result.success).toEqual(false);
if (!result.success) {
expect(result.error.issues.length).toEqual(2);
expect(result.error).toMatchInlineSnapshot(`
[ZodError: [
{
"code": "custom",
"path": [
"first"
],
"message": "Keys must be uppercase"
},
{
"code": "custom",
"path": [
"second"
],
"message": "Keys must be uppercase"
}
]]
`);
}
});
test("map with object keys", () => {
const map = z.map(
z.object({
name: z.string(),
age: z.number(),
}),
z.string()
);
const data = new Map([
[{ name: "John", age: 30 }, "foo"],
[{ name: "Jane", age: 25 }, "bar"],
]);
const result = map.safeParse(data);
expect(result.success).toEqual(true);
expect(result.data!).toEqual(data);
const badData = new Map([["bad", "foo"]]);
const badResult = map.safeParse(badData);
expect(badResult.success).toEqual(false);
expect(badResult.error).toMatchInlineSnapshot(`
[ZodError: [
{
"expected": "object",
"code": "invalid_type",
"path": [
"bad"
],
"message": "Invalid input: expected object, received string"
}
]]
`);
});
test("min/max", async () => {
const schema = stringMap.min(4).max(5);
const r1 = schema.safeParse(
new Map([
["a", "a"],
["b", "b"],
["c", "c"],
["d", "d"],
])
);
expect(r1.success).toEqual(true);
const r2 = schema.safeParse(
new Map([
["a", "a"],
["b", "b"],
["c", "c"],
])
);
expect(r2.success).toEqual(false);
expect(r2.error!.issues).toMatchInlineSnapshot(`
[
{
"code": "too_small",
"inclusive": true,
"message": "Too small: expected map to have >=4 entries",
"minimum": 4,
"origin": "map",
"path": [],
},
]
`);
const r3 = schema.safeParse(
new Map([
["a", "a"],
["b", "b"],
["c", "c"],
["d", "d"],
["e", "e"],
["f", "f"],
])
);
expect(r3.success).toEqual(false);
expect(r3.error!.issues).toMatchInlineSnapshot(`
[
{
"code": "too_big",
"inclusive": true,
"maximum": 5,
"message": "Too big: expected map to have <=5 entries",
"origin": "map",
"path": [],
},
]
`);
});

View File

@@ -0,0 +1,420 @@
declare module "node:repl" {
import { AsyncCompleter, Completer, Interface, InterfaceEventMap } from "node:readline";
import { InspectOptions } from "node:util";
import { Context } from "node:vm";
interface ReplOptions {
/**
* The input prompt to display.
* @default "> "
*/
prompt?: string | undefined;
/**
* The `Readable` stream from which REPL input will be read.
* @default process.stdin
*/
input?: NodeJS.ReadableStream | undefined;
/**
* The `Writable` stream to which REPL output will be written.
* @default process.stdout
*/
output?: NodeJS.WritableStream | undefined;
/**
* If `true`, specifies that the output should be treated as a TTY terminal, and have
* ANSI/VT100 escape codes written to it.
* Default: checking the value of the `isTTY` property on the output stream upon
* instantiation.
*/
terminal?: boolean | undefined;
/**
* The function to be used when evaluating each given line of input.
* **Default:** an async wrapper for the JavaScript `eval()` function. An `eval` function can
* error with `repl.Recoverable` to indicate the input was incomplete and prompt for
* additional lines. See the [custom evaluation functions](https://nodejs.org/dist/latest-v26.x/docs/api/repl.html#custom-evaluation-functions)
* section for more details.
*/
eval?: REPLEval | undefined;
/**
* Defines if the repl prints output previews or not.
* @default `true` Always `false` in case `terminal` is falsy.
*/
preview?: boolean | undefined;
/**
* If `true`, specifies that the default `writer` function should include ANSI color
* styling to REPL output. If a custom `writer` function is provided then this has no
* effect.
* @default the REPL instance's `terminal` value
*/
useColors?: boolean | undefined;
/**
* If `true`, specifies that the default evaluation function will use the JavaScript
* `global` as the context as opposed to creating a new separate context for the REPL
* instance. The node CLI REPL sets this value to `true`.
* @default false
*/
useGlobal?: boolean | undefined;
/**
* If `true`, specifies that the default writer will not output the return value of a
* command if it evaluates to `undefined`.
* @default false
*/
ignoreUndefined?: boolean | undefined;
/**
* The function to invoke to format the output of each command before writing to `output`.
* @default a wrapper for `util.inspect`
*
* @see https://nodejs.org/dist/latest-v26.x/docs/api/repl.html#repl_customizing_repl_output
*/
writer?: REPLWriter | undefined;
/**
* An optional function used for custom Tab auto completion.
*
* @see https://nodejs.org/dist/latest-v26.x/docs/api/readline.html#readline_use_of_the_completer_function
*/
completer?: Completer | AsyncCompleter | undefined;
/**
* A flag that specifies whether the default evaluator executes all JavaScript commands in
* strict mode or default (sloppy) mode.
* Accepted values are:
* - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode.
* - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to
* prefacing every repl statement with `'use strict'`.
*/
replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined;
/**
* Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is
* pressed. This cannot be used together with a custom `eval` function.
* @default false
*/
breakEvalOnSigint?: boolean | undefined;
/**
* This function customizes error handling in the REPL.
* It receives the thrown exception as its first argument and must return one
* of the following values synchronously:
* * `'print'` to print the error to the output stream (default behavior).
* * `'ignore'` to skip all remaining error handling.
* * `'unhandled'` to treat the exception as fully unhandled. In this case,
* the error will be passed to process-wide exception handlers, such as
* the `'uncaughtException'` event.
* The `'unhandled'` value may or may not be desirable in situations
* where the `REPLServer` instance has been closed, depending on the particular
* use case.
* @since v25.9.0
*/
handleError?: ((err: unknown) => "print" | "ignore" | "unhandled") | undefined;
}
type REPLEval = (
this: REPLServer,
evalCmd: string,
context: Context,
file: string,
cb: (err: Error | null, result: any) => void,
) => void;
type REPLWriter = (this: REPLServer, obj: any) => string;
/**
* This is the default "writer" value, if none is passed in the REPL options,
* and it can be overridden by custom print functions.
*/
const writer: REPLWriter & {
options: InspectOptions;
};
type REPLCommandAction = (this: REPLServer, text: string) => void;
interface REPLCommand {
/**
* Help text to be displayed when `.help` is entered.
*/
help?: string | undefined;
/**
* The function to execute, optionally accepting a single string argument.
*/
action: REPLCommandAction;
}
interface REPLServerSetupHistoryOptions {
filePath?: string | undefined;
size?: number | undefined;
removeHistoryDuplicates?: boolean | undefined;
onHistoryFileLoaded?: ((err: Error | null, repl: REPLServer) => void) | undefined;
}
interface REPLServerEventMap extends InterfaceEventMap {
"exit": [];
"reset": [context: Context];
}
/**
* Instances of `repl.REPLServer` are created using the {@link start} method
* or directly using the JavaScript `new` keyword.
*
* ```js
* import repl from 'node:repl';
*
* const options = { useColors: true };
*
* const firstInstance = repl.start(options);
* const secondInstance = new repl.REPLServer(options);
* ```
* @since v0.1.91
*/
class REPLServer extends Interface {
/**
* NOTE: According to the documentation:
*
* > Instances of `repl.REPLServer` are created using the `repl.start()` method and
* > _should not_ be created directly using the JavaScript `new` keyword.
*
* `REPLServer` cannot be subclassed due to implementation specifics in NodeJS.
*
* @see https://nodejs.org/dist/latest-v26.x/docs/api/repl.html#repl_class_replserver
*/
private constructor();
/**
* The `vm.Context` provided to the `eval` function to be used for JavaScript
* evaluation.
*/
readonly context: Context;
/**
* @deprecated since v14.3.0 - Use `input` instead.
*/
readonly inputStream: NodeJS.ReadableStream;
/**
* @deprecated since v14.3.0 - Use `output` instead.
*/
readonly outputStream: NodeJS.WritableStream;
/**
* The `Readable` stream from which REPL input will be read.
*/
readonly input: NodeJS.ReadableStream;
/**
* The `Writable` stream to which REPL output will be written.
*/
readonly output: NodeJS.WritableStream;
/**
* The commands registered via `replServer.defineCommand()`.
*/
readonly commands: NodeJS.ReadOnlyDict<REPLCommand>;
/**
* A value indicating whether the REPL is currently in "editor mode".
*
* @see https://nodejs.org/dist/latest-v26.x/docs/api/repl.html#repl_commands_and_special_keys
*/
readonly editorMode: boolean;
/**
* A value indicating whether the `_` variable has been assigned.
*
* @see https://nodejs.org/dist/latest-v26.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable
*/
readonly underscoreAssigned: boolean;
/**
* The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL).
*
* @see https://nodejs.org/dist/latest-v26.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable
*/
readonly last: any;
/**
* A value indicating whether the `_error` variable has been assigned.
*
* @since v9.8.0
* @see https://nodejs.org/dist/latest-v26.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable
*/
readonly underscoreErrAssigned: boolean;
/**
* The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL).
*
* @since v9.8.0
* @see https://nodejs.org/dist/latest-v26.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable
*/
readonly lastError: any;
/**
* Specified in the REPL options, this is the function to be used when evaluating each
* given line of input. If not specified in the REPL options, this is an async wrapper
* for the JavaScript `eval()` function.
*/
readonly eval: REPLEval;
/**
* Specified in the REPL options, this is a value indicating whether the default
* `writer` function should include ANSI color styling to REPL output.
*/
readonly useColors: boolean;
/**
* Specified in the REPL options, this is a value indicating whether the default `eval`
* function will use the JavaScript `global` as the context as opposed to creating a new
* separate context for the REPL instance.
*/
readonly useGlobal: boolean;
/**
* Specified in the REPL options, this is a value indicating whether the default `writer`
* function should output the result of a command if it evaluates to `undefined`.
*/
readonly ignoreUndefined: boolean;
/**
* Specified in the REPL options, this is the function to invoke to format the output of
* each command before writing to `outputStream`. If not specified in the REPL options,
* this will be a wrapper for `util.inspect`.
*/
readonly writer: REPLWriter;
/**
* Specified in the REPL options, this is the function to use for custom Tab auto-completion.
*/
readonly completer: Completer | AsyncCompleter;
/**
* Specified in the REPL options, this is a flag that specifies whether the default `eval`
* function should execute all JavaScript commands in strict mode or default (sloppy) mode.
* Possible values are:
* - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode.
* - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to
* prefacing every repl statement with `'use strict'`.
*/
readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT;
/**
* The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands
* to the REPL instance. Such commands are invoked by typing a `.` followed by the `keyword`. The `cmd` is either a `Function` or an `Object` with the following
* properties:
*
* The following example shows two new commands added to the REPL instance:
*
* ```js
* import repl from 'node:repl';
*
* const replServer = repl.start({ prompt: '> ' });
* replServer.defineCommand('sayhello', {
* help: 'Say hello',
* action(name) {
* this.clearBufferedCommand();
* console.log(`Hello, ${name}!`);
* this.displayPrompt();
* },
* });
* replServer.defineCommand('saybye', function saybye() {
* console.log('Goodbye!');
* this.close();
* });
* ```
*
* The new commands can then be used from within the REPL instance:
*
* ```console
* > .sayhello Node.js User
* Hello, Node.js User!
* > .saybye
* Goodbye!
* ```
* @since v0.3.0
* @param keyword The command keyword (_without_ a leading `.` character).
* @param cmd The function to invoke when the command is processed.
*/
defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void;
/**
* The `replServer.displayPrompt()` method readies the REPL instance for input
* from the user, printing the configured `prompt` to a new line in the `output` and resuming the `input` to accept new input.
*
* When multi-line input is being entered, a pipe `'|'` is printed rather than the
* 'prompt'.
*
* When `preserveCursor` is `true`, the cursor placement will not be reset to `0`.
*
* The `replServer.displayPrompt` method is primarily intended to be called from
* within the action function for commands registered using the `replServer.defineCommand()` method.
* @since v0.1.91
*/
displayPrompt(preserveCursor?: boolean): void;
/**
* The `replServer.clearBufferedCommand()` method clears any command that has been
* buffered but not yet executed. This method is primarily intended to be
* called from within the action function for commands registered using the `replServer.defineCommand()` method.
* @since v9.0.0
*/
clearBufferedCommand(): void;
/**
* Initializes a history log file for the REPL instance. When executing the
* Node.js binary and using the command-line REPL, a history file is initialized
* by default. However, this is not the case when creating a REPL
* programmatically. Use this method to initialize a history log file when working
* with REPL instances programmatically.
* @since v11.10.0
* @param historyPath the path to the history file
* @param callback called when history writes are ready or upon error
*/
setupHistory(historyPath: string, callback: (err: Error | null, repl: this) => void): void;
setupHistory(
historyConfig?: REPLServerSetupHistoryOptions,
callback?: (err: Error | null, repl: this) => void,
): void;
// #region InternalEventEmitter
addListener<E extends keyof REPLServerEventMap>(
eventName: E,
listener: (...args: REPLServerEventMap[E]) => void,
): this;
addListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
emit<E extends keyof REPLServerEventMap>(eventName: E, ...args: REPLServerEventMap[E]): boolean;
emit(eventName: string | symbol, ...args: any[]): boolean;
listenerCount<E extends keyof REPLServerEventMap>(
eventName: E,
listener?: (...args: REPLServerEventMap[E]) => void,
): number;
listenerCount(eventName: string | symbol, listener?: (...args: any[]) => void): number;
listeners<E extends keyof REPLServerEventMap>(eventName: E): ((...args: REPLServerEventMap[E]) => void)[];
listeners(eventName: string | symbol): ((...args: any[]) => void)[];
off<E extends keyof REPLServerEventMap>(eventName: E, listener: (...args: REPLServerEventMap[E]) => void): this;
off(eventName: string | symbol, listener: (...args: any[]) => void): this;
on<E extends keyof REPLServerEventMap>(eventName: E, listener: (...args: REPLServerEventMap[E]) => void): this;
on(eventName: string | symbol, listener: (...args: any[]) => void): this;
once<E extends keyof REPLServerEventMap>(
eventName: E,
listener: (...args: REPLServerEventMap[E]) => void,
): this;
once(eventName: string | symbol, listener: (...args: any[]) => void): this;
prependListener<E extends keyof REPLServerEventMap>(
eventName: E,
listener: (...args: REPLServerEventMap[E]) => void,
): this;
prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener<E extends keyof REPLServerEventMap>(
eventName: E,
listener: (...args: REPLServerEventMap[E]) => void,
): this;
prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
rawListeners<E extends keyof REPLServerEventMap>(eventName: E): ((...args: REPLServerEventMap[E]) => void)[];
rawListeners(eventName: string | symbol): ((...args: any[]) => void)[];
// eslint-disable-next-line @definitelytyped/no-unnecessary-generics
removeAllListeners<E extends keyof REPLServerEventMap>(eventName?: E): this;
removeAllListeners(eventName?: string | symbol): this;
removeListener<E extends keyof REPLServerEventMap>(
eventName: E,
listener: (...args: REPLServerEventMap[E]) => void,
): this;
removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
// #endregion
}
/**
* A flag passed in the REPL options. Evaluates expressions in sloppy mode.
*/
const REPL_MODE_SLOPPY: unique symbol;
/**
* A flag passed in the REPL options. Evaluates expressions in strict mode.
* This is equivalent to prefacing every repl statement with `'use strict'`.
*/
const REPL_MODE_STRICT: unique symbol;
/**
* The `repl.start()` method creates and starts a {@link REPLServer} instance.
*
* If `options` is a string, then it specifies the input prompt:
*
* ```js
* import repl from 'node:repl';
*
* // a Unix style prompt
* repl.start('$ ');
* ```
* @since v0.1.91
*/
function start(options?: string | ReplOptions): REPLServer;
/**
* Indicates a recoverable error that a `REPLServer` can use to support multi-line input.
*
* @see https://nodejs.org/dist/latest-v26.x/docs/api/repl.html#repl_recoverable_errors
*/
class Recoverable extends SyntaxError {
err: Error;
constructor(err: Error);
}
}
declare module "repl" {
export * from "node:repl";
}

View File

@@ -0,0 +1,7 @@
'use strict'
const SemVer = require('../classes/semver')
const compare = (a, b, loose) =>
new SemVer(a, loose).compare(new SemVer(b, loose))
module.exports = compare

View File

@@ -0,0 +1,125 @@
import * as util from "../core/util.js";
const error = () => {
const Sizable = {
string: { unit: "caractères", verb: "avoir" },
file: { unit: "octets", verb: "avoir" },
array: { unit: "éléments", verb: "avoir" },
set: { unit: "éléments", verb: "avoir" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "entrée",
email: "adresse e-mail",
url: "URL",
emoji: "emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "date et heure ISO",
date: "date ISO",
time: "heure ISO",
duration: "durée ISO",
ipv4: "adresse IPv4",
ipv6: "adresse IPv6",
cidrv4: "plage IPv4",
cidrv6: "plage IPv6",
base64: "chaîne encodée en base64",
base64url: "chaîne encodée en base64url",
json_string: "chaîne JSON",
e164: "numéro E.164",
jwt: "JWT",
template_literal: "entrée",
};
const TypeDictionary = {
string: "chaîne",
number: "nombre",
int: "entier",
boolean: "booléen",
bigint: "grand entier",
symbol: "symbole",
undefined: "indéfini",
null: "null",
never: "jamais",
void: "vide",
date: "date",
array: "tableau",
object: "objet",
tuple: "tuple",
record: "enregistrement",
map: "carte",
set: "ensemble",
file: "fichier",
nonoptional: "non-optionnel",
nan: "NaN",
function: "fonction",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
if (/^[A-Z]/.test(issue.expected)) {
return `Entrée invalide : instanceof ${issue.expected} attendu, ${received} reçu`;
}
return `Entrée invalide : ${expected} attendu, ${received} reçu`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Entrée invalide : ${util.stringifyPrimitive(issue.values[0])} attendu`;
return `Option invalide : une valeur parmi ${util.joinValues(issue.values, "|")} attendue`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Trop grand : ${TypeDictionary[issue.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "élément(s)"}`;
return `Trop grand : ${TypeDictionary[issue.origin] ?? "valeur"} doit être ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing)
return `Trop petit : ${TypeDictionary[issue.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;
return `Trop petit : ${TypeDictionary[issue.origin] ?? "valeur"} doit être ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with")
return `Chaîne invalide : doit commencer par "${_issue.prefix}"`;
if (_issue.format === "ends_with")
return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`;
if (_issue.format === "includes")
return `Chaîne invalide : doit inclure "${_issue.includes}"`;
if (_issue.format === "regex")
return `Chaîne invalide : doit correspondre au modèle ${_issue.pattern}`;
return `${FormatDictionary[_issue.format] ?? issue.format} invalide`;
}
case "not_multiple_of":
return `Nombre invalide : doit être un multiple de ${issue.divisor}`;
case "unrecognized_keys":
return `Clé${issue.keys.length > 1 ? "s" : ""} non reconnue${issue.keys.length > 1 ? "s" : ""} : ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Clé invalide dans ${issue.origin}`;
case "invalid_union":
return "Entrée invalide";
case "invalid_element":
return `Valeur invalide dans ${issue.origin}`;
default:
return `Entrée invalide`;
}
};
};
export default function () {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"moduleDetectionKind.enum.js","sourceRoot":"","sources":["../../src/enums/moduleDetectionKind.enum.ts"],"names":[],"mappings":"AAAA,sGAAsG;AAEtG,MAAM,CAAN,IAAY,mBAKX;AALD,WAAY,mBAAmB;IAC3B,6DAAQ,CAAA;IACR,6DAAQ,CAAA;IACR,iEAAU,CAAA;IACV,+DAAS,CAAA;AACb,CAAC,EALW,mBAAmB,KAAnB,mBAAmB,QAK9B"}

View File

@@ -0,0 +1,2 @@
import type { LibDefinition } from '../variable';
export declare const esnext_collection: LibDefinition;

View File

@@ -0,0 +1,2 @@
declare function validate(uuid: unknown): boolean;
export default validate;

View File

@@ -0,0 +1,35 @@
import { OuterExpressionKinds } from "#enums/outerExpressionKinds";
import type { AsExpression, BindingPattern, BlockOrExpression, BooleanLiteral, ConciseBody, ExclamationToken, Expression, ExpressionWithTypeArguments, ForInitializer, Identifier, JSDocTypeExpression, JSDocTypeLiteral, JsxTagNameExpression, LeftHandSideExpression, LiteralExpression, MinusToken, ModuleDeclaration, Node, NonNullExpression, NullLiteral, ParenthesizedExpression, PartiallyEmittedExpression, PlusToken, PrefixUnaryExpression, QuestionToken, ReadonlyKeyword, SatisfiesExpression, Statement, TemplateMiddle, TemplateTail, ThisTypeNode, TypeAssertion, TypeNode, UnaryExpressionBase } from "./ast.ts";
export * from "./is.generated.ts";
type JSDocNamespaceDeclaration = ModuleDeclaration;
type WrappedExpression<T extends Expression> = ParenthesizedExpression | TypeAssertion | AsExpression | SatisfiesExpression | ExpressionWithTypeArguments | NonNullExpression | PartiallyEmittedExpression;
type OuterExpression = WrappedExpression<Expression>;
export declare function isTypeNode(node: Node): node is TypeNode;
export declare function isStatement(node: Node): node is Statement;
export declare function isExpression(node: Node): node is Expression;
export declare function isBlockOrExpression(node: Node): node is BlockOrExpression;
export declare function isLeftHandSideExpression(node: Node): node is LeftHandSideExpression;
export declare function skipPartiallyEmittedExpressions(node: Expression): Expression;
export declare function skipPartiallyEmittedExpressions(node: Node): Node;
export declare function isUnaryExpression(node: Node): node is UnaryExpressionBase;
/** @internal */
export declare function isOuterExpression(node: Node, kinds?: OuterExpressionKinds): node is OuterExpression;
/** @internal */
export declare function skipOuterExpressions<T extends Expression>(node: WrappedExpression<T>): T;
/** @internal */
export declare function skipOuterExpressions(node: Expression, kinds?: OuterExpressionKinds): Expression;
/** @internal */
export declare function skipOuterExpressions(node: Node, kinds?: OuterExpressionKinds): Node;
export declare function isBindingPattern(node: Node): node is BindingPattern;
export declare function isConciseBody(node: Node): node is ConciseBody;
export declare function isForInitializer(node: Node): node is ForInitializer;
export declare function isQuestionOrExclamationToken(node: Node): node is QuestionToken | ExclamationToken;
export declare function isIdentifierOrThisTypeNode(node: Node): node is Identifier | ThisTypeNode;
export declare function isReadonlyKeywordOrPlusOrMinusToken(node: Node): node is ReadonlyKeyword | PlusToken | MinusToken;
export declare function isQuestionOrPlusOrMinusToken(node: Node): node is QuestionToken | PlusToken | MinusToken;
export declare function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail;
export declare function isLiteralTypeLiteral(node: Node): node is NullLiteral | BooleanLiteral | LiteralExpression | PrefixUnaryExpression;
export declare function isIdentifierOrJSDocNamespaceDeclaration(node: Node): node is Identifier | JSDocNamespaceDeclaration;
export declare function isJSDocTypeExpressionOrJSDocTypeLiteral(node: Node): node is JSDocTypeExpression | JSDocTypeLiteral;
export declare function isJsxTagNameExpression(node: Node): node is JsxTagNameExpression;
//# sourceMappingURL=is.d.ts.map

View File

@@ -0,0 +1,12 @@
# The BSD 2-Clause License
Copyright (c) 2014, Domenic Denicola
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,35 @@
import validate from './validate.js';
function parse(uuid) {
if (!validate(uuid)) {
throw TypeError('Invalid UUID');
}
let v;
const arr = new Uint8Array(16); // Parse ########-....-....-....-............
arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
arr[1] = v >>> 16 & 0xff;
arr[2] = v >>> 8 & 0xff;
arr[3] = v & 0xff; // Parse ........-####-....-....-............
arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
arr[5] = v & 0xff; // Parse ........-....-####-....-............
arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
arr[7] = v & 0xff; // Parse ........-....-....-####-............
arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
arr[9] = v & 0xff; // Parse ........-....-....-....-############
// (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
arr[11] = v / 0x100000000 & 0xff;
arr[12] = v >>> 24 & 0xff;
arr[13] = v >>> 16 & 0xff;
arr[14] = v >>> 8 & 0xff;
arr[15] = v & 0xff;
return arr;
}
export default parse;

View File

@@ -0,0 +1 @@
{"version":3,"file":"visitor.d.ts","sourceRoot":"","sources":["../../src/ast/visitor.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAER,2BAA2B,EAG3B,IAAI,EACJ,SAAS,EACZ,MAAM,UAAU,CAAC;AAUlB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAMtD,YAAY,EAAE,OAAO,EAAE,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAoBhG,iBAAS,yCAAyC,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,KAAK,EAAE,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,SAAS,GAAG,CAAC,GAAG,SAAS,CAM/J;AAED,OAAO,EAAE,yCAAyC,IAAI,+BAA+B,EAAE,yCAAyC,IAAI,8BAA8B,EAAE,CAAC;AAIrK,iBAAS,2CAA2C,CAAC,IAAI,EAAE,2BAA2B,EAAE,OAAO,EAAE,OAAO,GAAG,2BAA2B,CAQrI;AAED,OAAO,EAAE,2CAA2C,IAAI,iCAAiC,EAAE,2CAA2C,IAAI,gCAAgC,EAAE,CAAC"}

View File

@@ -0,0 +1,16 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.esnext_iterator = void 0;
const base_config_1 = require("./base-config");
const es2015_iterable_1 = require("./es2015.iterable");
exports.esnext_iterator = {
libs: [es2015_iterable_1.es2015_iterable],
variables: [
['Iterator', base_config_1.TYPE_VALUE],
['IteratorObjectConstructor', base_config_1.TYPE],
],
};

View File

@@ -0,0 +1,34 @@
/**
* @fileoverview The instance of Ajv validator.
* @author Evgeny Poberezkin
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const Ajv = require("ajv"),
metaSchema = require("ajv/lib/refs/json-schema-draft-04.json");
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = (additionalOptions = {}) => {
const ajv = new Ajv({
meta: false,
useDefaults: true,
validateSchema: false,
missingRefs: "ignore",
verbose: true,
schemaId: "auto",
...additionalOptions,
});
ajv.addMetaSchema(metaSchema);
// eslint-disable-next-line no-underscore-dangle -- Ajv's API
ajv._opts.defaultMeta = metaSchema.id;
return ajv;
};

View File

@@ -0,0 +1,88 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hkdf = void 0;
exports.extract = extract;
exports.expand = expand;
/**
* HKDF (RFC 5869): extract + expand in one step.
* See https://soatok.blog/2021/11/17/understanding-hkdf/.
* @module
*/
const hmac_ts_1 = require("./hmac.js");
const utils_ts_1 = require("./utils.js");
/**
* HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`
* Arguments position differs from spec (IKM is first one, since it is not optional)
* @param hash - hash function that would be used (e.g. sha256)
* @param ikm - input keying material, the initial key
* @param salt - optional salt value (a non-secret random value)
*/
function extract(hash, ikm, salt) {
(0, utils_ts_1.ahash)(hash);
// NOTE: some libraries treat zero-length array as 'not provided';
// we don't, since we have undefined as 'not provided'
// https://github.com/RustCrypto/KDFs/issues/15
if (salt === undefined)
salt = new Uint8Array(hash.outputLen);
return (0, hmac_ts_1.hmac)(hash, (0, utils_ts_1.toBytes)(salt), (0, utils_ts_1.toBytes)(ikm));
}
const HKDF_COUNTER = /* @__PURE__ */ Uint8Array.from([0]);
const EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
/**
* HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`
* @param hash - hash function that would be used (e.g. sha256)
* @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)
* @param info - optional context and application specific information (can be a zero-length string)
* @param length - length of output keying material in bytes
*/
function expand(hash, prk, info, length = 32) {
(0, utils_ts_1.ahash)(hash);
(0, utils_ts_1.anumber)(length);
const olen = hash.outputLen;
if (length > 255 * olen)
throw new Error('Length should be <= 255*HashLen');
const blocks = Math.ceil(length / olen);
if (info === undefined)
info = EMPTY_BUFFER;
// first L(ength) octets of T
const okm = new Uint8Array(blocks * olen);
// Re-use HMAC instance between blocks
const HMAC = hmac_ts_1.hmac.create(hash, prk);
const HMACTmp = HMAC._cloneInto();
const T = new Uint8Array(HMAC.outputLen);
for (let counter = 0; counter < blocks; counter++) {
HKDF_COUNTER[0] = counter + 1;
// T(0) = empty string (zero length)
// T(N) = HMAC-Hash(PRK, T(N-1) | info | N)
HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)
.update(info)
.update(HKDF_COUNTER)
.digestInto(T);
okm.set(T, olen * counter);
HMAC._cloneInto(HMACTmp);
}
HMAC.destroy();
HMACTmp.destroy();
(0, utils_ts_1.clean)(T, HKDF_COUNTER);
return okm.slice(0, length);
}
/**
* HKDF (RFC 5869): derive keys from an initial input.
* Combines hkdf_extract + hkdf_expand in one step
* @param hash - hash function that would be used (e.g. sha256)
* @param ikm - input keying material, the initial key
* @param salt - optional salt value (a non-secret random value)
* @param info - optional context and application specific information (can be a zero-length string)
* @param length - length of output keying material in bytes
* @example
* import { hkdf } from '@noble/hashes/hkdf';
* import { sha256 } from '@noble/hashes/sha2';
* import { randomBytes } from '@noble/hashes/utils';
* const inputKey = randomBytes(32);
* const salt = randomBytes(32);
* const info = 'application-key';
* const hk1 = hkdf(sha256, inputKey, salt, info, 32);
*/
const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);
exports.hkdf = hkdf;
//# sourceMappingURL=hkdf.js.map

View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFixOrSuggest = getFixOrSuggest;
function getFixOrSuggest({ fixOrSuggest, suggestion, }) {
switch (fixOrSuggest) {
case 'fix':
return { fix: suggestion.fix };
case 'none':
return undefined;
case 'suggest':
return { suggest: [suggestion] };
}
}

View File

@@ -0,0 +1 @@
export { _ as default } from "../esm/_class_apply_descriptor_get.js";

View File

@@ -0,0 +1,292 @@
'use strict';
const { kForOnEventAttribute, kListener } = require('./constants');
const kCode = Symbol('kCode');
const kData = Symbol('kData');
const kError = Symbol('kError');
const kMessage = Symbol('kMessage');
const kReason = Symbol('kReason');
const kTarget = Symbol('kTarget');
const kType = Symbol('kType');
const kWasClean = Symbol('kWasClean');
/**
* Class representing an event.
*/
class Event {
/**
* Create a new `Event`.
*
* @param {String} type The name of the event
* @throws {TypeError} If the `type` argument is not specified
*/
constructor(type) {
this[kTarget] = null;
this[kType] = type;
}
/**
* @type {*}
*/
get target() {
return this[kTarget];
}
/**
* @type {String}
*/
get type() {
return this[kType];
}
}
Object.defineProperty(Event.prototype, 'target', { enumerable: true });
Object.defineProperty(Event.prototype, 'type', { enumerable: true });
/**
* Class representing a close event.
*
* @extends Event
*/
class CloseEvent extends Event {
/**
* Create a new `CloseEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {Number} [options.code=0] The status code explaining why the
* connection was closed
* @param {String} [options.reason=''] A human-readable string explaining why
* the connection was closed
* @param {Boolean} [options.wasClean=false] Indicates whether or not the
* connection was cleanly closed
*/
constructor(type, options = {}) {
super(type);
this[kCode] = options.code === undefined ? 0 : options.code;
this[kReason] = options.reason === undefined ? '' : options.reason;
this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
}
/**
* @type {Number}
*/
get code() {
return this[kCode];
}
/**
* @type {String}
*/
get reason() {
return this[kReason];
}
/**
* @type {Boolean}
*/
get wasClean() {
return this[kWasClean];
}
}
Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });
Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });
Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });
/**
* Class representing an error event.
*
* @extends Event
*/
class ErrorEvent extends Event {
/**
* Create a new `ErrorEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {*} [options.error=null] The error that generated this event
* @param {String} [options.message=''] The error message
*/
constructor(type, options = {}) {
super(type);
this[kError] = options.error === undefined ? null : options.error;
this[kMessage] = options.message === undefined ? '' : options.message;
}
/**
* @type {*}
*/
get error() {
return this[kError];
}
/**
* @type {String}
*/
get message() {
return this[kMessage];
}
}
Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });
Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });
/**
* Class representing a message event.
*
* @extends Event
*/
class MessageEvent extends Event {
/**
* Create a new `MessageEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {*} [options.data=null] The message content
*/
constructor(type, options = {}) {
super(type);
this[kData] = options.data === undefined ? null : options.data;
}
/**
* @type {*}
*/
get data() {
return this[kData];
}
}
Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });
/**
* This provides methods for emulating the `EventTarget` interface. It's not
* meant to be used directly.
*
* @mixin
*/
const EventTarget = {
/**
* Register an event listener.
*
* @param {String} type A string representing the event type to listen for
* @param {(Function|Object)} handler The listener to add
* @param {Object} [options] An options object specifies characteristics about
* the event listener
* @param {Boolean} [options.once=false] A `Boolean` indicating that the
* listener should be invoked at most once after being added. If `true`,
* the listener would be automatically removed when invoked.
* @public
*/
addEventListener(type, handler, options = {}) {
for (const listener of this.listeners(type)) {
if (
!options[kForOnEventAttribute] &&
listener[kListener] === handler &&
!listener[kForOnEventAttribute]
) {
return;
}
}
let wrapper;
if (type === 'message') {
wrapper = function onMessage(data, isBinary) {
const event = new MessageEvent('message', {
data: isBinary ? data : data.toString()
});
event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === 'close') {
wrapper = function onClose(code, message) {
const event = new CloseEvent('close', {
code,
reason: message.toString(),
wasClean: this._closeFrameReceived && this._closeFrameSent
});
event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === 'error') {
wrapper = function onError(error) {
const event = new ErrorEvent('error', {
error,
message: error.message
});
event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === 'open') {
wrapper = function onOpen() {
const event = new Event('open');
event[kTarget] = this;
callListener(handler, this, event);
};
} else {
return;
}
wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
wrapper[kListener] = handler;
if (options.once) {
this.once(type, wrapper);
} else {
this.on(type, wrapper);
}
},
/**
* Remove an event listener.
*
* @param {String} type A string representing the event type to remove
* @param {(Function|Object)} handler The listener to remove
* @public
*/
removeEventListener(type, handler) {
for (const listener of this.listeners(type)) {
if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
this.removeListener(type, listener);
break;
}
}
}
};
module.exports = {
CloseEvent,
ErrorEvent,
Event,
EventTarget,
MessageEvent
};
/**
* Call an event listener
*
* @param {(Function|Object)} listener The listener to call
* @param {*} thisArg The value to use as `this`` when calling the listener
* @param {Event} event The event to pass to the listener
* @private
*/
function callListener(listener, thisArg, event) {
if (typeof listener === 'object' && listener.handleEvent) {
listener.handleEvent.call(listener, event);
} else {
listener.call(thisArg, event);
}
}

View File

@@ -0,0 +1,83 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
exports.default = (0, util_1.createRule)({
name: 'no-var-requires',
meta: {
type: 'problem',
deprecated: {
deprecatedSince: '8.0.0',
replacedBy: [
{
rule: {
name: '@typescript-eslint/no-require-imports',
url: 'https://typescript-eslint.io/rules/no-require-imports',
},
},
],
url: 'https://github.com/typescript-eslint/typescript-eslint/pull/8334',
},
docs: {
description: 'Disallow `require` statements except in import statements',
},
messages: {
noVarReqs: 'Require statement not part of import statement.',
},
replacedBy: ['@typescript-eslint/no-require-imports'],
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
allow: {
type: 'array',
description: 'Patterns of import paths to allow requiring from.',
items: { type: 'string' },
},
},
},
],
},
defaultOptions: [{ allow: [] }],
create(context, options) {
const allowPatterns = options[0].allow.map(pattern => new RegExp(pattern, 'u'));
function isImportPathAllowed(importPath) {
return allowPatterns.some(pattern => importPath.match(pattern));
}
function isStringOrTemplateLiteral(node) {
return ((node.type === utils_1.AST_NODE_TYPES.Literal &&
typeof node.value === 'string') ||
node.type === utils_1.AST_NODE_TYPES.TemplateLiteral);
}
return {
'CallExpression[callee.name="require"]'(node) {
if (node.arguments[0] && isStringOrTemplateLiteral(node.arguments[0])) {
const argValue = (0, util_1.getStaticStringValue)(node.arguments[0]);
if (typeof argValue === 'string' && isImportPathAllowed(argValue)) {
return;
}
}
const parent = node.parent.type === utils_1.AST_NODE_TYPES.ChainExpression
? node.parent.parent
: node.parent;
if ([
utils_1.AST_NODE_TYPES.CallExpression,
utils_1.AST_NODE_TYPES.MemberExpression,
utils_1.AST_NODE_TYPES.NewExpression,
utils_1.AST_NODE_TYPES.TSAsExpression,
utils_1.AST_NODE_TYPES.TSTypeAssertion,
utils_1.AST_NODE_TYPES.VariableDeclarator,
].includes(parent.type)) {
const variable = utils_1.ASTUtils.findVariable(context.sourceCode.getScope(node), 'require');
if (!variable?.identifiers.length) {
context.report({
node,
messageId: 'noVarReqs',
});
}
}
},
};
},
});

View File

@@ -0,0 +1,27 @@
{
"name": "tinybench",
"version": "2.9.0",
"type": "module",
"packageManager": "pnpm@8.4.0",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.cts",
"exports": {
"require": "./dist/index.cjs",
"import": "./dist/index.js",
"default": "./dist/index.js"
},
"files": [
"dist/**"
],
"repository": "tinylibs/tinybench",
"license": "MIT",
"keywords": [
"benchmark",
"tinylibs",
"tiny"
],
"scripts": {
"publish": "npm run build && clean-publish"
}
}

View File

@@ -0,0 +1,29 @@
function _iterable_to_array_limit(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
export { _iterable_to_array_limit as _ };

View File

@@ -0,0 +1,121 @@
import type { $ZodStringFormats } from "../core/checks.js";
import type * as errors from "../core/errors.js";
import * as util from "../core/util.js";
const error: () => errors.$ZodErrorMap = () => {
const Sizable: Record<string, { unit: string; verb: string }> = {
string: { unit: "χαρακτήρες", verb: "να έχει" },
file: { unit: "bytes", verb: "να έχει" },
array: { unit: "στοιχεία", verb: "να έχει" },
set: { unit: "στοιχεία", verb: "να έχει" },
map: { unit: "καταχωρήσεις", verb: "να έχει" },
};
function getSizing(origin: string): { unit: string; verb: string } | null {
return Sizable[origin] ?? null;
}
const FormatDictionary: {
[k in $ZodStringFormats | (string & {})]?: string;
} = {
regex: "είσοδος",
email: "διεύθυνση email",
url: "URL",
emoji: "emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "ISO ημερομηνία και ώρα",
date: "ISO ημερομηνία",
time: "ISO ώρα",
duration: "ISO διάρκεια",
ipv4: "διεύθυνση IPv4",
ipv6: "διεύθυνση IPv6",
mac: "διεύθυνση MAC",
cidrv4: "εύρος IPv4",
cidrv6: "εύρος IPv6",
base64: "συμβολοσειρά κωδικοποιημένη σε base64",
base64url: "συμβολοσειρά κωδικοποιημένη σε base64url",
json_string: "συμβολοσειρά JSON",
e164: "αριθμός E.164",
jwt: "JWT",
template_literal: "είσοδος",
};
const TypeDictionary: {
[k in errors.$ZodInvalidTypeExpected | (string & {})]?: string;
} = {
nan: "NaN",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
if (typeof issue.expected === "string" && /^[A-Z]/.test(issue.expected)) {
return `Μη έγκυρη είσοδος: αναμενόταν instanceof ${issue.expected}, λήφθηκε ${received}`;
}
return `Μη έγκυρη είσοδος: αναμενόταν ${expected}, λήφθηκε ${received}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Μη έγκυρη είσοδος: αναμενόταν ${util.stringifyPrimitive(issue.values[0])}`;
return `Μη έγκυρη επιλογή: αναμενόταν ένα από ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Πολύ μεγάλο: αναμενόταν ${issue.origin ?? "τιμή"} να έχει ${adj}${issue.maximum.toString()} ${sizing.unit ?? "στοιχεία"}`;
return `Πολύ μεγάλο: αναμενόταν ${issue.origin ?? "τιμή"} να είναι ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Πολύ μικρό: αναμενόταν ${issue.origin} να έχει ${adj}${issue.minimum.toString()} ${sizing.unit}`;
}
return `Πολύ μικρό: αναμενόταν ${issue.origin} να είναι ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue as errors.$ZodStringFormatIssues;
if (_issue.format === "starts_with") {
return `Μη έγκυρη συμβολοσειρά: πρέπει να ξεκινά με "${_issue.prefix}"`;
}
if (_issue.format === "ends_with") return `Μη έγκυρη συμβολοσειρά: πρέπει να τελειώνει με "${_issue.suffix}"`;
if (_issue.format === "includes") return `Μη έγκυρη συμβολοσειρά: πρέπει να περιέχει "${_issue.includes}"`;
if (_issue.format === "regex")
return `Μη έγκυρη συμβολοσειρά: πρέπει να ταιριάζει με το μοτίβο ${_issue.pattern}`;
return `Μη έγκυρο: ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Μη έγκυρος αριθμός: πρέπει να είναι πολλαπλάσιο του ${issue.divisor}`;
case "unrecognized_keys":
return `Άγνωστ${issue.keys.length > 1 ? "α" : "ο"} κλειδ${issue.keys.length > 1 ? "ιά" : "ί"}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Μη έγκυρο κλειδί στο ${issue.origin}`;
case "invalid_union":
return "Μη έγκυρη είσοδος";
case "invalid_element":
return `Μη έγκυρη τιμή στο ${issue.origin}`;
default:
return `Μη έγκυρη είσοδος`;
}
};
};
export default function (): { localeError: errors.$ZodErrorMap } {
return {
localeError: error(),
};
}