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,257 @@
import { __exportAll, __reExport, __toCommonJS, __toESM } from './experimental-runtime-base.mjs';
// @ts-check
class Module {
/**
* @type {{ exports: any }}
*/
exportsHolder = { exports: null };
/**
* @type {string}
*/
id;
/**
* @param {string} id
*/
constructor(id) {
this.id = id;
}
get exports() {
return this.exportsHolder.exports;
}
}
/**
* Compiler-emitted module-graph delta — pure topology (static + dynamic edges).
* `ids[0, localCount)` are the modules this payload carries; `ids[localCount, …)` are foreign edge targets.
* `edges[i]` / `dynamicEdges[i]` are the static / dynamic-`import()` out-edges of `ids[i]`.
* @typedef {{ ids: string[], localCount: number, edges: number[][], dynamicEdges?: number[][] }} ModuleGraphDelta
* @typedef {{ createModuleHotContext(moduleId: string): any, onModuleCacheRemoval(moduleId: string): void }} DevRuntimeHooks
*/
export class MissingFactoryError extends Error {
/**
* @param {string} id
*/
constructor(id) {
super(`No factory registered for module ${id}`);
this.id = id;
}
}
export class DevRuntime {
/**
* Client ID generated at runtime initialization, used for lazy compilation requests.
* @type {string}
*/
clientId;
/**
* @param {string} clientId
*/
constructor(clientId) {
this.clientId = clientId;
}
/**
* Static import edges from `registerGraph` — entries persist across `removeModuleCache`
* and change only by replacement from a newer payload (last write wins).
* @type {Map<string, { edges: string[] }>}
*/
staticImports = new Map();
/**
* Reverse index over the static imports.
* @type {Map<string, Set<string>>}
*/
importers = new Map();
/**
* Dynamic `import()` edges from `registerGraph`, keyed by importer — mirror of
* `staticImports` for the dynamic reverse index.
* @type {Map<string, { edges: string[] }>}
*/
dynamicImports = new Map();
/**
* Reverse index over the dynamic imports.
* @type {Map<string, Set<string>>}
*/
dynamicImporters = new Map();
/**
* The module cache. Membership means "this module's side effects ran in this tab" —
* registration is emitted ahead of every module body, and nothing un-registers on
* unwind, so a factory that throws mid-body stays registered. A `Map` rather than a
* plain object: HMR eviction deletes entries, and a `delete` on an object drops V8
* into dictionary mode, taxing every later lookup on the hottest read path.
* @type {Map<string, Module>}
*/
moduleCache = new Map();
/**
* Re-runnable factories from HMR patches and lazy chunks. The initial bundle stays
* scope-hoisted and contributes none.
* @type {Map<string, { kind: 'esm' | 'cjs', fn: (id: string) => void }>}
*/
factories = new Map();
/**
* Installed by the dev client at boot. The runtime is a store + executor and makes
* no HMR decisions; accepting, disposing, and reloading live behind these hooks.
* @type {DevRuntimeHooks | null}
*/
hooks = null;
/**
* @param {ModuleGraphDelta} delta
*/
registerGraph(delta) {
for (let i = 0; i < delta.localCount; i++) {
const id = delta.ids[i];
const edges = delta.edges[i].map((j) => delta.ids[j]);
for (const target of this.staticImports.get(id)?.edges ?? []) {
this.importers.get(target)?.delete(id);
}
for (const target of edges) {
let importerSet = this.importers.get(target);
if (!importerSet) {
importerSet = new Set();
this.importers.set(target, importerSet);
}
importerSet.add(id);
}
this.staticImports.set(id, { edges });
// Dynamic `import()` edges are maintained in a parallel reverse index with the same
// last-write-wins bookkeeping; `getImporters` unions the two.
const dynamicEdges = (delta.dynamicEdges?.[i] ?? []).map((j) => delta.ids[j]);
for (const target of this.dynamicImports.get(id)?.edges ?? []) {
this.dynamicImporters.get(target)?.delete(id);
}
for (const target of dynamicEdges) {
let importerSet = this.dynamicImporters.get(target);
if (!importerSet) {
importerSet = new Set();
this.dynamicImporters.set(target, importerSet);
}
importerSet.add(id);
}
this.dynamicImports.set(id, { edges: dynamicEdges });
}
}
/**
* @param {string} id
* @param {'esm' | 'cjs'} kind
* @param {(id: string) => void} fn
*/
registerFactory(id, kind, fn) {
this.factories.set(id, { kind, fn });
}
/**
* @param {string} id
* @param {{ exports: any }} exportsHolder
*/
registerModule(id, exportsHolder) {
const module = new Module(id);
module.exportsHolder = exportsHolder;
this.moduleCache.set(id, module);
}
/**
* @param {string} id
* @returns {string[]}
*/
getImporters(id) {
// Static dynamic importers — the boundary walk treats both kinds the same (parity
// with Vite `node.importers` / webpack `module.parents`). Deduped so a module that
// imports `id` both statically and via `import()` appears once.
const dynamic = this.dynamicImporters.get(id);
if (!dynamic || dynamic.size === 0) {
return [...(this.importers.get(id) ?? [])];
}
return [...new Set([...(this.importers.get(id) ?? []), ...dynamic])];
}
/**
* @param {string} id
*/
isExecuted(id) {
return this.moduleCache.has(id);
}
/**
* @param {string} id
*/
hasFactory(id) {
return this.factories.has(id);
}
/**
* Module-cache delete only — static imports and factories persist. Removal is what
* re-arms a cache-gated factory for `initModule`.
* @param {string} id
*/
removeModuleCache(id) {
this.moduleCache.delete(id);
this.hooks?.onModuleCacheRemoval(id);
}
/**
* The one re-execution gate: registered → return the live exports; otherwise run the
* mapped factory (which registers itself first, then runs the body).
* @param {string} id
*/
initModule(id) {
if (this.moduleCache.has(id)) {
return this.loadExports(id);
}
const factory = this.factories.get(id);
if (!factory) {
throw new MissingFactoryError(id);
}
factory.fn(id);
return this.loadExports(id);
}
/**
* @param {string} id
*/
loadExports(id) {
const module = this.moduleCache.get(id);
if (module) {
return module.exportsHolder.exports;
} else {
console.warn(`Module ${id} not found`);
return {};
}
}
/**
* @param {string} moduleId
*/
createModuleHotContext(moduleId) {
if (this.hooks) {
return this.hooks.createModuleHotContext(moduleId);
}
throw new Error('createModuleHotContext requires installed hooks or an override');
}
/** @internal */
// @ts-expect-error The variable will be injected at build time.
__toESM = __toESM;
/** @internal */
// @ts-expect-error The variable will be injected at build time.
__toCommonJS = __toCommonJS;
/** @internal */
// @ts-expect-error The variable will be injected at build time.
__exportAll = __exportAll;
/**
* @param {boolean} [isNodeMode]
* @returns {(mod: any) => any}
* @internal
*/
// @ts-expect-error The variable will be injected at build time.
__toDynamicImportESM = (isNodeMode) => (mod) => __toESM(mod.default, isNodeMode);
/** @internal */
// @ts-expect-error The variable will be injected at build time.
__reExport = __reExport;
}

View File

@@ -0,0 +1,33 @@
'use strict'
const build = require('pino-abstract-transport')
const { pipeline, Transform } = require('node:stream')
module.exports = () => {
return build(function (source) {
const myTransportStream = new Transform({
autoDestroy: true,
objectMode: true,
transform (chunk, enc, cb) {
const {
time,
level,
[source.messageKey]: body,
[source.errorKey]: error,
...attributes
} = chunk
this.push(JSON.stringify({
severityText: source.levels.labels[level],
body,
attributes,
...(error && { error })
}))
cb()
}
})
pipeline(source, myTransportStream, () => {})
return myTransportStream
}, {
enablePipelining: true,
expectPinoConfig: true
})
}

View File

@@ -0,0 +1,924 @@
/*! *****************************************************************************
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,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Array<T> {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast 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.
*/
findLast<S extends T>(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S | undefined;
findLast(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex 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.
*/
findLastIndex(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): number;
/**
* Returns a copy of an array with its elements reversed.
*/
toReversed(): T[];
/**
* Returns a copy of an array with its elements sorted.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
* ```ts
* [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22]
* ```
*/
toSorted(compareFn?: (a: T, b: T) => number): T[];
/**
* Copies an array and removes elements and, if necessary, inserts new elements in their place. Returns the copied array.
* @param start The zero-based location in the array from which to start removing elements.
* @param deleteCount The number of elements to remove.
* @param items Elements to insert into the copied array in place of the deleted elements.
* @returns The copied array.
*/
toSpliced(start: number, deleteCount: number, ...items: T[]): T[];
/**
* Copies an array and removes elements while returning the remaining elements.
* @param start The zero-based location in the array from which to start removing elements.
* @param deleteCount The number of elements to remove.
* @returns A copy of the original array with the remaining elements.
*/
toSpliced(start: number, deleteCount?: number): T[];
/**
* Copies an array, then overwrites the value at the provided index with the
* given value. If the index is negative, then it replaces from the end
* of the array.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to write into the copied array.
* @returns The copied array with the updated value.
*/
with(index: number, value: T): T[];
}
interface ReadonlyArray<T> {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast 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.
*/
findLast<S extends T>(
predicate: (value: T, index: number, array: readonly T[]) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (value: T, index: number, array: readonly T[]) => unknown,
thisArg?: any,
): T | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex 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.
*/
findLastIndex(
predicate: (value: T, index: number, array: readonly T[]) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copied array with all of its elements reversed.
*/
toReversed(): T[];
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
* ```ts
* [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22]
* ```
*/
toSorted(compareFn?: (a: T, b: T) => number): T[];
/**
* Copies an array and removes elements while, if necessary, inserting new elements in their place, returning the remaining elements.
* @param start The zero-based location in the array from which to start removing elements.
* @param deleteCount The number of elements to remove.
* @param items Elements to insert into the copied array in place of the deleted elements.
* @returns A copy of the original array with the remaining elements.
*/
toSpliced(start: number, deleteCount: number, ...items: T[]): T[];
/**
* Copies an array and removes elements while returning the remaining elements.
* @param start The zero-based location in the array from which to start removing elements.
* @param deleteCount The number of elements to remove.
* @returns A copy of the original array with the remaining elements.
*/
toSpliced(start: number, deleteCount?: number): T[];
/**
* Copies an array, then overwrites the value at the provided index with the
* given value. If the index is negative, then it replaces from the end
* of the array
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: T): T[];
}
interface Int8Array {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast 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.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: Int8Array,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (value: number, index: number, array: Int8Array) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex 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.
*/
findLastIndex(
predicate: (value: number, index: number, array: Int8Array) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Int8Array;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Int8Array.from([11, 2, 22, 1]);
* myNums.toSorted((a, b) => a - b) // Int8Array(4) [1, 2, 11, 22]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Int8Array;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Int8Array;
}
interface Uint8Array {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast 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.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: Uint8Array,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (value: number, index: number, array: Uint8Array) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex 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.
*/
findLastIndex(
predicate: (value: number, index: number, array: Uint8Array) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Uint8Array;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Uint8Array.from([11, 2, 22, 1]);
* myNums.toSorted((a, b) => a - b) // Uint8Array(4) [1, 2, 11, 22]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Uint8Array;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Uint8Array;
}
interface Uint8ClampedArray {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast 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.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: Uint8ClampedArray,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (
value: number,
index: number,
array: Uint8ClampedArray,
) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex 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.
*/
findLastIndex(
predicate: (
value: number,
index: number,
array: Uint8ClampedArray,
) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Uint8ClampedArray;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Uint8ClampedArray.from([11, 2, 22, 1]);
* myNums.toSorted((a, b) => a - b) // Uint8ClampedArray(4) [1, 2, 11, 22]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Uint8ClampedArray;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Uint8ClampedArray;
}
interface Int16Array {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast 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.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: Int16Array,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (value: number, index: number, array: Int16Array) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex 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.
*/
findLastIndex(
predicate: (value: number, index: number, array: Int16Array) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Int16Array;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Int16Array.from([11, 2, -22, 1]);
* myNums.toSorted((a, b) => a - b) // Int16Array(4) [-22, 1, 2, 11]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Int16Array;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Int16Array;
}
interface Uint16Array {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast 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.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: Uint16Array,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (
value: number,
index: number,
array: Uint16Array,
) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex 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.
*/
findLastIndex(
predicate: (
value: number,
index: number,
array: Uint16Array,
) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Uint16Array;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Uint16Array.from([11, 2, 22, 1]);
* myNums.toSorted((a, b) => a - b) // Uint16Array(4) [1, 2, 11, 22]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Uint16Array;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Uint16Array;
}
interface Int32Array {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast 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.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: Int32Array,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (value: number, index: number, array: Int32Array) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex 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.
*/
findLastIndex(
predicate: (value: number, index: number, array: Int32Array) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Int32Array;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Int32Array.from([11, 2, -22, 1]);
* myNums.toSorted((a, b) => a - b) // Int32Array(4) [-22, 1, 2, 11]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Int32Array;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Int32Array;
}
interface Uint32Array {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast 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.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: Uint32Array,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (
value: number,
index: number,
array: Uint32Array,
) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex 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.
*/
findLastIndex(
predicate: (
value: number,
index: number,
array: Uint32Array,
) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Uint32Array;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Uint32Array.from([11, 2, 22, 1]);
* myNums.toSorted((a, b) => a - b) // Uint32Array(4) [1, 2, 11, 22]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Uint32Array;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Uint32Array;
}
interface Float32Array {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast 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.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: Float32Array,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (
value: number,
index: number,
array: Float32Array,
) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex 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.
*/
findLastIndex(
predicate: (
value: number,
index: number,
array: Float32Array,
) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Float32Array;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Float32Array.from([11.25, 2, -22.5, 1]);
* myNums.toSorted((a, b) => a - b) // Float32Array(4) [-22.5, 1, 2, 11.5]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Float32Array;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Float32Array;
}
interface Float64Array {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast 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.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: Float64Array,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (
value: number,
index: number,
array: Float64Array,
) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex 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.
*/
findLastIndex(
predicate: (
value: number,
index: number,
array: Float64Array,
) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Float64Array;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Float64Array.from([11.25, 2, -22.5, 1]);
* myNums.toSorted((a, b) => a - b) // Float64Array(4) [-22.5, 1, 2, 11.5]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Float64Array;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Float64Array;
}
interface BigInt64Array {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast 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.
*/
findLast<S extends bigint>(
predicate: (
value: bigint,
index: number,
array: BigInt64Array,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (
value: bigint,
index: number,
array: BigInt64Array,
) => unknown,
thisArg?: any,
): bigint | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex 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.
*/
findLastIndex(
predicate: (
value: bigint,
index: number,
array: BigInt64Array,
) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): BigInt64Array;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = BigInt64Array.from([11n, 2n, -22n, 1n]);
* myNums.toSorted((a, b) => Number(a - b)) // BigInt64Array(4) [-22n, 1n, 2n, 11n]
* ```
*/
toSorted(compareFn?: (a: bigint, b: bigint) => number): BigInt64Array;
/**
* Copies the array and inserts the given bigint at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: bigint): BigInt64Array;
}
interface BigUint64Array {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast 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.
*/
findLast<S extends bigint>(
predicate: (
value: bigint,
index: number,
array: BigUint64Array,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (
value: bigint,
index: number,
array: BigUint64Array,
) => unknown,
thisArg?: any,
): bigint | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex 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.
*/
findLastIndex(
predicate: (
value: bigint,
index: number,
array: BigUint64Array,
) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): BigUint64Array;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = BigUint64Array.from([11n, 2n, 22n, 1n]);
* myNums.toSorted((a, b) => Number(a - b)) // BigUint64Array(4) [1n, 2n, 11n, 22n]
* ```
*/
toSorted(compareFn?: (a: bigint, b: bigint) => number): BigUint64Array;
/**
* Copies the array and inserts the given bigint at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: bigint): BigUint64Array;
}

View File

@@ -0,0 +1,63 @@
'use strict'
const { test } = require('tap')
const fs = require('fs')
const proxyquire = require('proxyquire')
const { file } = require('./helper')
test('fsync with sync', (t) => {
t.plan(5)
const fakeFs = Object.create(fs)
fakeFs.fsyncSync = function (fd) {
t.pass('fake fs.fsyncSync called')
return fs.fsyncSync(fd)
}
const SonicBoom = proxyquire('../', {
fs: fakeFs
})
const dest = file()
const fd = fs.openSync(dest, 'w')
const stream = new SonicBoom({ fd, sync: true, fsync: true })
t.ok(stream.write('hello world\n'))
t.ok(stream.write('something else\n'))
stream.end()
const data = fs.readFileSync(dest, 'utf8')
t.equal(data, 'hello world\nsomething else\n')
})
test('fsync with async', (t) => {
t.plan(7)
const fakeFs = Object.create(fs)
fakeFs.fsyncSync = function (fd) {
t.pass('fake fs.fsyncSync called')
return fs.fsyncSync(fd)
}
const SonicBoom = proxyquire('../', {
fs: fakeFs
})
const dest = file()
const fd = fs.openSync(dest, 'w')
const stream = new SonicBoom({ fd, fsync: true })
t.ok(stream.write('hello world\n'))
t.ok(stream.write('something else\n'))
stream.end()
stream.on('finish', () => {
fs.readFile(dest, 'utf8', (err, data) => {
t.error(err)
t.equal(data, 'hello world\nsomething else\n')
})
})
stream.on('close', () => {
t.pass('close emitted')
})
})

View File

@@ -0,0 +1,120 @@
/**
* @fileoverview Define 2 token factories; forward and backward.
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const BackwardTokenCommentCursor = require("./backward-token-comment-cursor");
const BackwardTokenCursor = require("./backward-token-cursor");
const FilterCursor = require("./filter-cursor");
const ForwardTokenCommentCursor = require("./forward-token-comment-cursor");
const ForwardTokenCursor = require("./forward-token-cursor");
const LimitCursor = require("./limit-cursor");
const SkipCursor = require("./skip-cursor");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* The cursor factory.
* @private
*/
class CursorFactory {
/**
* Initializes this cursor.
* @param {Function} TokenCursor The class of the cursor which iterates tokens only.
* @param {Function} TokenCommentCursor The class of the cursor which iterates the mix of tokens and comments.
*/
constructor(TokenCursor, TokenCommentCursor) {
this.TokenCursor = TokenCursor;
this.TokenCommentCursor = TokenCommentCursor;
}
/**
* Creates a base cursor instance that can be decorated by createCursor.
* @param {Token[]} tokens The array of tokens.
* @param {Comment[]} comments The array of comments.
* @param {Object} indexMap The map from locations to indices in `tokens`.
* @param {number} startLoc The start location of the iteration range.
* @param {number} endLoc The end location of the iteration range.
* @param {boolean} includeComments The flag to iterate comments as well.
* @returns {Cursor} The created base cursor.
*/
createBaseCursor(
tokens,
comments,
indexMap,
startLoc,
endLoc,
includeComments,
) {
const Cursor = includeComments
? this.TokenCommentCursor
: this.TokenCursor;
return new Cursor(tokens, comments, indexMap, startLoc, endLoc);
}
/**
* Creates a cursor that iterates tokens with normalized options.
* @param {Token[]} tokens The array of tokens.
* @param {Comment[]} comments The array of comments.
* @param {Object} indexMap The map from locations to indices in `tokens`.
* @param {number} startLoc The start location of the iteration range.
* @param {number} endLoc The end location of the iteration range.
* @param {boolean} includeComments The flag to iterate comments as well.
* @param {Function|null} filter The predicate function to choose tokens.
* @param {number} skip The count of tokens the cursor skips.
* @param {number} count The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility.
* @returns {Cursor} The created cursor.
*/
createCursor(
tokens,
comments,
indexMap,
startLoc,
endLoc,
includeComments,
filter,
skip,
count,
) {
let cursor = this.createBaseCursor(
tokens,
comments,
indexMap,
startLoc,
endLoc,
includeComments,
);
if (filter) {
cursor = new FilterCursor(cursor, filter);
}
if (skip >= 1) {
cursor = new SkipCursor(cursor, skip);
}
if (count >= 0) {
cursor = new LimitCursor(cursor, count);
}
return cursor;
}
}
//------------------------------------------------------------------------------
// Exports
//------------------------------------------------------------------------------
module.exports = {
forward: new CursorFactory(ForwardTokenCursor, ForwardTokenCommentCursor),
backward: new CursorFactory(
BackwardTokenCursor,
BackwardTokenCommentCursor,
),
};

View File

@@ -0,0 +1,24 @@
"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.es2018 = void 0;
const es2017_1 = require("./es2017");
const es2018_asyncgenerator_1 = require("./es2018.asyncgenerator");
const es2018_asynciterable_1 = require("./es2018.asynciterable");
const es2018_intl_1 = require("./es2018.intl");
const es2018_promise_1 = require("./es2018.promise");
const es2018_regexp_1 = require("./es2018.regexp");
exports.es2018 = {
libs: [
es2017_1.es2017,
es2018_asynciterable_1.es2018_asynciterable,
es2018_asyncgenerator_1.es2018_asyncgenerator,
es2018_promise_1.es2018_promise,
es2018_regexp_1.es2018_regexp,
es2018_intl_1.es2018_intl,
],
variables: [],
};

View File

@@ -0,0 +1,39 @@
export {};
import { webcrypto } from "crypto";
type _Crypto = typeof globalThis extends { onmessage: any } ? {} : webcrypto.Crypto;
type _CryptoKey = typeof globalThis extends { onmessage: any } ? {} : webcrypto.CryptoKey;
type _SubtleCrypto = typeof globalThis extends { onmessage: any } ? {} : webcrypto.SubtleCrypto;
declare global {
interface Crypto extends _Crypto {}
var Crypto: typeof globalThis extends { onmessage: any; Crypto: infer T } ? T : {
prototype: webcrypto.Crypto;
new(): webcrypto.Crypto;
};
interface CryptoKey extends _CryptoKey {}
var CryptoKey: typeof globalThis extends { onmessage: any; CryptoKey: infer T } ? T : {
prototype: webcrypto.CryptoKey;
new(): webcrypto.CryptoKey;
};
interface SubtleCrypto extends _SubtleCrypto {}
var SubtleCrypto: typeof globalThis extends { onmessage: any; SubtleCrypto: infer T } ? T : {
prototype: webcrypto.SubtleCrypto;
new(): webcrypto.SubtleCrypto;
supports(
operation: string,
algorithm: webcrypto.AlgorithmIdentifier,
length?: number,
): boolean;
supports(
operation: string,
algorithm: webcrypto.AlgorithmIdentifier,
additionalAlgorithm: webcrypto.AlgorithmIdentifier,
): boolean;
};
var crypto: typeof globalThis extends { onmessage: any; crypto: infer T } ? T : webcrypto.Crypto;
}

View File

@@ -0,0 +1,322 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const tsutils = __importStar(require("ts-api-utils"));
const ts = __importStar(require("typescript"));
const util_1 = require("../util");
var Usefulness;
(function (Usefulness) {
Usefulness["Always"] = "always";
Usefulness["Never"] = "will";
Usefulness["Sometimes"] = "may";
})(Usefulness || (Usefulness = {}));
const canHaveTypeParameters = (declaration) => {
return (ts.isTypeAliasDeclaration(declaration) ||
ts.isInterfaceDeclaration(declaration) ||
ts.isClassDeclaration(declaration));
};
exports.default = (0, util_1.createRule)({
name: 'no-base-to-string',
meta: {
type: 'suggestion',
docs: {
description: 'Require `.toString()` and `.toLocaleString()` to only be called on objects which provide useful information when stringified',
recommended: 'recommended',
requiresTypeChecking: true,
},
messages: {
baseArrayJoin: "Using `join()` for {{name}} {{certainty}} use Object's default stringification format ('[object Object]') when stringified.",
baseToString: "'{{name}}' {{certainty}} use Object's default stringification format ('[object Object]') when stringified.",
},
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
checkUnknown: {
type: 'boolean',
description: 'Whether to also check values of type `unknown`',
},
ignoredTypeNames: {
type: 'array',
description: 'Stringified type names to ignore.',
items: {
type: 'string',
},
},
},
},
],
},
defaultOptions: [
{
checkUnknown: false,
ignoredTypeNames: ['Error', 'RegExp', 'URL', 'URLSearchParams'],
},
],
create(context, [option]) {
const services = (0, util_1.getParserServices)(context);
const { program } = services;
const checker = program.getTypeChecker();
const ignoredTypeNames = option.ignoredTypeNames ?? [];
function checkExpression(node, type) {
if (node.type === utils_1.AST_NODE_TYPES.Literal) {
return;
}
const certainty = collectToStringCertainty(type ?? services.getTypeAtLocation(node), new Set());
if (certainty === Usefulness.Always) {
return;
}
context.report({
node,
messageId: 'baseToString',
data: {
name: context.sourceCode.getText(node),
certainty,
},
});
}
function checkExpressionForArrayJoin(node, type) {
const certainty = collectJoinCertainty(type, new Set());
if (certainty === Usefulness.Always) {
return;
}
context.report({
node,
messageId: 'baseArrayJoin',
data: {
name: context.sourceCode.getText(node),
certainty,
},
});
}
function collectUnionTypeCertainty(type, collectSubTypeCertainty) {
const certainties = type.types.map(t => collectSubTypeCertainty(t));
if (certainties.every(certainty => certainty === Usefulness.Never)) {
return Usefulness.Never;
}
if (certainties.every(certainty => certainty === Usefulness.Always)) {
return Usefulness.Always;
}
return Usefulness.Sometimes;
}
function collectIntersectionTypeCertainty(type, collectSubTypeCertainty) {
for (const subType of type.types) {
const subtypeUsefulness = collectSubTypeCertainty(subType);
if (subtypeUsefulness === Usefulness.Always) {
return Usefulness.Always;
}
}
return Usefulness.Never;
}
function collectTupleCertainty(type, visited) {
const typeArgs = checker.getTypeArguments(type);
const certainties = typeArgs.map(t => collectToStringCertainty(t, visited));
if (certainties.some(certainty => certainty === Usefulness.Never)) {
return Usefulness.Never;
}
if (certainties.some(certainty => certainty === Usefulness.Sometimes)) {
return Usefulness.Sometimes;
}
return Usefulness.Always;
}
function collectArrayCertainty(type, visited) {
const elemType = (0, util_1.nullThrows)(type.getNumberIndexType(), 'array should have number index type');
return collectToStringCertainty(elemType, visited);
}
function collectJoinCertainty(type, visited) {
if (tsutils.isUnionType(type)) {
return collectUnionTypeCertainty(type, t => collectJoinCertainty(t, visited));
}
if (tsutils.isIntersectionType(type)) {
return collectIntersectionTypeCertainty(type, t => collectJoinCertainty(t, visited));
}
if (checker.isTupleType(type)) {
return collectTupleCertainty(type, visited);
}
if (checker.isArrayType(type)) {
return collectArrayCertainty(type, visited);
}
return Usefulness.Always;
}
function collectToStringCertainty(type, visited) {
if (visited.has(type)) {
// don't report if this is a self referencing array or tuple type
return Usefulness.Always;
}
if (tsutils.isTypeParameter(type)) {
const constraint = type.getConstraint();
if (constraint) {
return collectToStringCertainty(constraint, visited);
}
// unconstrained generic means `unknown`
return option.checkUnknown ? Usefulness.Sometimes : Usefulness.Always;
}
// the Boolean type definition missing toString()
if (tsutils.isTypeFlagSet(type, ts.TypeFlags.Boolean) ||
tsutils.isTypeFlagSet(type, ts.TypeFlags.BooleanLiteral)) {
return Usefulness.Always;
}
const symbol = type.aliasSymbol ?? type.getSymbol();
const decl = symbol?.getDeclarations()?.[0];
if (decl &&
canHaveTypeParameters(decl) &&
decl.typeParameters &&
ignoredTypeNames.includes(symbol.name)) {
return Usefulness.Always;
}
if ((0, util_1.matchesTypeOrBaseType)(services, type => ignoredTypeNames.includes((0, util_1.getTypeName)(checker, type)), type)) {
return Usefulness.Always;
}
if (type.isIntersection()) {
return collectIntersectionTypeCertainty(type, t => collectToStringCertainty(t, visited));
}
if (type.isUnion()) {
return collectUnionTypeCertainty(type, t => collectToStringCertainty(t, visited));
}
if (checker.isTupleType(type)) {
return collectTupleCertainty(type, new Set([...visited, type]));
}
if (checker.isArrayType(type)) {
return collectArrayCertainty(type, new Set([...visited, type]));
}
switch (isToStringLikeFromObject(type)) {
case undefined:
// unknown
if (option.checkUnknown && type.flags === ts.TypeFlags.Unknown) {
return Usefulness.Sometimes;
}
// e.g. any
return Usefulness.Always;
case true:
return Usefulness.Never;
case false:
return Usefulness.Always;
}
}
function isBuiltInStringCall(node) {
if (node.callee.type === utils_1.AST_NODE_TYPES.Identifier &&
// eslint-disable-next-line @typescript-eslint/internal/prefer-ast-types-enum
node.callee.name === 'String' &&
node.arguments[0]) {
const scope = context.sourceCode.getScope(node);
// eslint-disable-next-line @typescript-eslint/internal/prefer-ast-types-enum
const variable = utils_1.ASTUtils.findVariable(scope, 'String');
return !variable?.defs.length;
}
return false;
}
function isSymbolToPrimitiveMethod(node) {
return (ts.isMethodSignature(node) &&
ts.isComputedPropertyName(node.name) &&
ts.isPropertyAccessExpression(node.name.expression) &&
ts.isIdentifier(node.name.expression.expression) &&
node.name.expression.expression.text === 'Symbol' &&
ts.isIdentifier(node.name.expression.name) &&
node.name.expression.name.text === 'toPrimitive' &&
(0, util_1.isSymbolFromDefaultLibrary)(program, checker.getSymbolAtLocation(node.name.expression.expression)));
}
function isToStringLikeFromObject(type) {
// An explicit [Symbol.toPrimitive] declaration is always user-defined
if (type
.getProperties()
.some(property => property.valueDeclaration &&
isSymbolToPrimitiveMethod(property.valueDeclaration))) {
return false;
}
// Otherwise, we check for known methods used in type coercion.
// We'll try to find one that's not declared on Object itself.
// Failing that, we'll fall back to one that is.
let foundFallbackOnObject = false;
for (const propertyName of ['toLocaleString', 'toString', 'valueOf']) {
const candidate = checker.getPropertyOfType(type, propertyName);
if (!candidate) {
continue;
}
const declarations = candidate.getDeclarations();
if (!declarations?.length) {
continue;
}
// If any declaration is not from the Object interface, this is
// user-defined (e.g. overloaded toString on a class or module).
// see https://github.com/typescript-eslint/typescript-eslint/issues/8585
// see https://github.com/typescript-eslint/typescript-eslint/issues/11945
if (declarations.some(declaration => !(ts.isInterfaceDeclaration(declaration.parent) &&
declaration.parent.name.text === 'Object'))) {
return false;
}
foundFallbackOnObject = true;
}
return foundFallbackOnObject ? true : undefined;
}
return {
'AssignmentExpression[operator = "+="], BinaryExpression[operator = "+"]'(node) {
const leftType = services.getTypeAtLocation(node.left);
const rightType = services.getTypeAtLocation(node.right);
if ((0, util_1.getTypeName)(checker, leftType) === 'string') {
checkExpression(node.right, rightType);
}
else if (node.left.type !== utils_1.AST_NODE_TYPES.PrivateIdentifier &&
(0, util_1.getTypeName)(checker, rightType) === 'string') {
checkExpression(node.left, leftType);
}
},
CallExpression(node) {
if (isBuiltInStringCall(node) &&
node.arguments[0].type !== utils_1.AST_NODE_TYPES.SpreadElement) {
checkExpression(node.arguments[0]);
}
},
'CallExpression > MemberExpression.callee > Identifier[name = "join"].property'(node) {
const memberExpr = node.parent;
const type = (0, util_1.getConstrainedTypeAtLocation)(services, memberExpr.object);
checkExpressionForArrayJoin(memberExpr.object, type);
},
'CallExpression > MemberExpression.callee > Identifier[name = /^(toLocaleString|toString)$/].property'(node) {
const memberExpr = node.parent;
checkExpression(memberExpr.object);
},
TemplateLiteral(node) {
if (node.parent.type === utils_1.AST_NODE_TYPES.TaggedTemplateExpression) {
return;
}
for (const expression of node.expressions) {
checkExpression(expression);
}
},
};
},
});

View File

@@ -0,0 +1,17 @@
range-set ::= range ( logical-or range ) *
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
range ::= hyphen | simple ( ' ' simple ) * | ''
hyphen ::= partial ' - ' partial
simple ::= primitive | partial | tilde | caret
primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
xr ::= 'x' | 'X' | '*' | nr
nr ::= '0' | [1-9] ( [0-9] ) *
tilde ::= '~' partial
caret ::= '^' partial
qualifier ::= ( '-' pre )? ( '+' build )?
pre ::= prepart ( '.' prepart ) *
prepart ::= nr | alphanumid
build ::= buildid ( '.' buildid ) *
alphanumid ::= ( [0-9] ) * [A-Za-z-] [-0-9A-Za-z] *
buildid ::= [-0-9A-Za-z]+

View File

@@ -0,0 +1,72 @@
'use strict';
const net = require('net');
const utils = require('../utils');
/**
* Constructor for a Jayson TCP server
* @class ServerTcp
* @extends require('net').Server
* @param {Server} server Server instance
* @param {Object} [options] Options for this instance
* @return {ServerTcp}
*/
const ServerTcp = function(server, options) {
if(!(this instanceof ServerTcp)) {
return new ServerTcp(server, options);
}
this.options = utils.merge(server.options, options || {});
net.Server.call(this, getTcpListener(this, server));
};
require('util').inherits(ServerTcp, net.Server);
module.exports = ServerTcp;
/**
* Returns a TCP connection listener bound to the server in the argument.
* @param {Server} server Instance of JaysonServer
* @param {net.Server} self Instance of net.Server
* @return {Function}
* @private
* @ignore
*/
function getTcpListener(self, server) {
return function(conn) {
const options = self.options || {};
utils.parseStream(conn, options, function(err, request) {
if(err) {
return respondError(err);
}
server.call(request, function(error, success) {
const response = error || success;
if(response) {
utils.JSON.stringify(response, options, function(err, body) {
if(err) {
return respondError(err);
}
conn.write(body);
});
} else {
// no response received at all, must be a notification
}
});
});
// ends the request with an error code
function respondError(err) {
const error = server.error(-32700, null, String(err));
const response = utils.response(error, undefined, undefined, self.options.version);
utils.JSON.stringify(response, options, function(err, body) {
if(err) {
body = ''; // we tried our best.
}
conn.end(body);
});
}
};
}

View File

@@ -0,0 +1,204 @@
/**
* @fileoverview Rule to warn when a function expression does not have a name.
* @author Kyle T. Nunery
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Types
//------------------------------------------------------------------------------
/** @typedef {import("eslint-scope").Variable} Variable */
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Checks whether or not a given variable is a function name.
* @param {Variable} variable A variable to check.
* @returns {boolean} `true` if the variable is a function name.
*/
function isFunctionName(variable) {
return variable && variable.defs[0].type === "FunctionName";
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
defaultOptions: ["always", {}],
docs: {
description: "Require or disallow named `function` expressions",
recommended: false,
url: "https://eslint.org/docs/latest/rules/func-names",
},
schema: {
definitions: {
value: {
enum: ["always", "as-needed", "never"],
},
},
type: "array",
items: [
{
$ref: "#/definitions/value",
},
{
type: "object",
properties: {
generators: {
$ref: "#/definitions/value",
},
},
additionalProperties: false,
},
],
additionalItems: false,
},
messages: {
unnamed: "Unexpected unnamed {{name}}.",
named: "Unexpected named {{name}}.",
},
},
create(context) {
const sourceCode = context.sourceCode;
/**
* Returns the config option for the given node.
* @param {ASTNode} node A node to get the config for.
* @returns {string} The config option.
*/
function getConfigForNode(node) {
if (node.generator && context.options[1].generators) {
return context.options[1].generators;
}
return context.options[0];
}
/**
* Determines whether the current FunctionExpression node is a get, set, or
* shorthand method in an object literal or a class.
* @param {ASTNode} node A node to check.
* @returns {boolean} True if the node is a get, set, or shorthand method.
*/
function isObjectOrClassMethod(node) {
const parent = node.parent;
return (
parent.type === "MethodDefinition" ||
(parent.type === "Property" &&
(parent.method ||
parent.kind === "get" ||
parent.kind === "set"))
);
}
/**
* Determines whether the current FunctionExpression node has a name that would be
* inferred from context in a conforming ES6 environment.
* @param {ASTNode} node A node to check.
* @returns {boolean} True if the node would have a name assigned automatically.
*/
function hasInferredName(node) {
const parent = node.parent;
return (
isObjectOrClassMethod(node) ||
(parent.type === "VariableDeclarator" &&
parent.id.type === "Identifier" &&
parent.init === node) ||
(parent.type === "Property" && parent.value === node) ||
(parent.type === "PropertyDefinition" &&
parent.value === node) ||
(parent.type === "AssignmentExpression" &&
parent.left.type === "Identifier" &&
parent.right === node) ||
(parent.type === "AssignmentPattern" &&
parent.left.type === "Identifier" &&
parent.right === node)
);
}
/**
* Reports that an unnamed function should be named
* @param {ASTNode} node The node to report in the event of an error.
* @returns {void}
*/
function reportUnexpectedUnnamedFunction(node) {
context.report({
node,
messageId: "unnamed",
loc: astUtils.getFunctionHeadLoc(node, sourceCode),
data: { name: astUtils.getFunctionNameWithKind(node) },
});
}
/**
* Reports that a named function should be unnamed
* @param {ASTNode} node The node to report in the event of an error.
* @returns {void}
*/
function reportUnexpectedNamedFunction(node) {
context.report({
node,
messageId: "named",
loc: astUtils.getFunctionHeadLoc(node, sourceCode),
data: { name: astUtils.getFunctionNameWithKind(node) },
});
}
/**
* The listener for function nodes.
* @param {ASTNode} node function node
* @returns {void}
*/
function handleFunction(node) {
// Skip recursive functions.
const nameVar = sourceCode.getDeclaredVariables(node)[0];
if (isFunctionName(nameVar) && nameVar.references.length > 0) {
return;
}
const hasName = Boolean(node.id && node.id.name);
const config = getConfigForNode(node);
if (config === "never") {
if (hasName && node.type !== "FunctionDeclaration") {
reportUnexpectedNamedFunction(node);
}
} else if (config === "as-needed") {
if (!hasName && !hasInferredName(node)) {
reportUnexpectedUnnamedFunction(node);
}
} else {
if (!hasName && !isObjectOrClassMethod(node)) {
reportUnexpectedUnnamedFunction(node);
}
}
}
return {
"FunctionExpression:exit": handleFunction,
"ExportDefaultDeclaration > FunctionDeclaration": handleFunction,
};
},
};

View File

@@ -0,0 +1,27 @@
import * as core from "../core/index.js";
import * as schemas from "./schemas.js";
export interface ZodCoercedString<T = unknown> extends schemas._ZodString<core.$ZodStringInternals<T>> {}
export function string<T = unknown>(params?: string | core.$ZodStringParams): ZodCoercedString<T> {
return core._coercedString(schemas.ZodString, params) as any;
}
export interface ZodCoercedNumber<T = unknown> extends schemas._ZodNumber<core.$ZodNumberInternals<T>> {}
export function number<T = unknown>(params?: string | core.$ZodNumberParams): ZodCoercedNumber<T> {
return core._coercedNumber(schemas.ZodNumber, params) as ZodCoercedNumber<T>;
}
export interface ZodCoercedBoolean<T = unknown> extends schemas._ZodBoolean<core.$ZodBooleanInternals<T>> {}
export function boolean<T = unknown>(params?: string | core.$ZodBooleanParams): ZodCoercedBoolean<T> {
return core._coercedBoolean(schemas.ZodBoolean, params) as ZodCoercedBoolean<T>;
}
export interface ZodCoercedBigInt<T = unknown> extends schemas._ZodBigInt<core.$ZodBigIntInternals<T>> {}
export function bigint<T = unknown>(params?: string | core.$ZodBigIntParams): ZodCoercedBigInt<T> {
return core._coercedBigint(schemas.ZodBigInt, params) as ZodCoercedBigInt<T>;
}
export interface ZodCoercedDate<T = unknown> extends schemas._ZodDate<core.$ZodDateInternals<T>> {}
export function date<T = unknown>(params?: string | core.$ZodDateParams): ZodCoercedDate<T> {
return core._coercedDate(schemas.ZodDate, params) as ZodCoercedDate<T>;
}

View File

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

View File

@@ -0,0 +1,10 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('node:os').hostname = function () { return 'abcdefghijklmnopqr' }
const pino = require(require.resolve('./../../'))
const dest = pino.destination({ dest: 1, minLength: 4096, sync: false })
const logger = pino({}, dest)
logger.info('hello')
logger.info('world')
dest.flushSync()
process.exit(0)

View File

@@ -0,0 +1,249 @@
/**
* @fileoverview Require spaces around infix operators
* @author Michael Ficarra
* @deprecated in ESLint v8.53.0
*/
"use strict";
const { isEqToken } = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
deprecated: {
message: "Formatting rules are being moved out of ESLint core.",
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
deprecatedSince: "8.53.0",
availableUntil: "11.0.0",
replacedBy: [
{
message:
"ESLint Stylistic now maintains deprecated stylistic core rules.",
url: "https://eslint.style/guide/migration",
plugin: {
name: "@stylistic/eslint-plugin",
url: "https://eslint.style",
},
rule: {
name: "space-infix-ops",
url: "https://eslint.style/rules/space-infix-ops",
},
},
],
},
type: "layout",
docs: {
description: "Require spacing around infix operators",
recommended: false,
url: "https://eslint.org/docs/latest/rules/space-infix-ops",
},
fixable: "whitespace",
schema: [
{
type: "object",
properties: {
int32Hint: {
type: "boolean",
default: false,
},
},
additionalProperties: false,
},
],
messages: {
missingSpace: "Operator '{{operator}}' must be spaced.",
},
},
create(context) {
const int32Hint = context.options[0]
? context.options[0].int32Hint === true
: false;
const sourceCode = context.sourceCode;
/**
* Returns the first token which violates the rule
* @param {ASTNode} left The left node of the main node
* @param {ASTNode} right The right node of the main node
* @param {string} op The operator of the main node
* @returns {Object} The violator token or null
* @private
*/
function getFirstNonSpacedToken(left, right, op) {
const operator = sourceCode.getFirstTokenBetween(
left,
right,
token => token.value === op,
);
const prev = sourceCode.getTokenBefore(operator);
const next = sourceCode.getTokenAfter(operator);
if (
!sourceCode.isSpaceBetween(prev, operator) ||
!sourceCode.isSpaceBetween(operator, next)
) {
return operator;
}
return null;
}
/**
* Reports an AST node as a rule violation
* @param {ASTNode} mainNode The node to report
* @param {Object} culpritToken The token which has a problem
* @returns {void}
* @private
*/
function report(mainNode, culpritToken) {
context.report({
node: mainNode,
loc: culpritToken.loc,
messageId: "missingSpace",
data: {
operator: culpritToken.value,
},
fix(fixer) {
const previousToken =
sourceCode.getTokenBefore(culpritToken);
const afterToken = sourceCode.getTokenAfter(culpritToken);
let fixString = "";
if (culpritToken.range[0] - previousToken.range[1] === 0) {
fixString = " ";
}
fixString += culpritToken.value;
if (afterToken.range[0] - culpritToken.range[1] === 0) {
fixString += " ";
}
return fixer.replaceText(culpritToken, fixString);
},
});
}
/**
* Check if the node is binary then report
* @param {ASTNode} node node to evaluate
* @returns {void}
* @private
*/
function checkBinary(node) {
const leftNode = node.left.typeAnnotation
? node.left.typeAnnotation
: node.left;
const rightNode = node.right;
// search for = in AssignmentPattern nodes
const operator = node.operator || "=";
const nonSpacedNode = getFirstNonSpacedToken(
leftNode,
rightNode,
operator,
);
if (nonSpacedNode) {
if (!(int32Hint && sourceCode.getText(node).endsWith("|0"))) {
report(node, nonSpacedNode);
}
}
}
/**
* Check if the node is conditional
* @param {ASTNode} node node to evaluate
* @returns {void}
* @private
*/
function checkConditional(node) {
const nonSpacedConsequentNode = getFirstNonSpacedToken(
node.test,
node.consequent,
"?",
);
const nonSpacedAlternateNode = getFirstNonSpacedToken(
node.consequent,
node.alternate,
":",
);
if (nonSpacedConsequentNode) {
report(node, nonSpacedConsequentNode);
}
if (nonSpacedAlternateNode) {
report(node, nonSpacedAlternateNode);
}
}
/**
* Check if the node is a variable
* @param {ASTNode} node node to evaluate
* @returns {void}
* @private
*/
function checkVar(node) {
const leftNode = node.id.typeAnnotation
? node.id.typeAnnotation
: node.id;
const rightNode = node.init;
if (rightNode) {
const nonSpacedNode = getFirstNonSpacedToken(
leftNode,
rightNode,
"=",
);
if (nonSpacedNode) {
report(node, nonSpacedNode);
}
}
}
return {
AssignmentExpression: checkBinary,
AssignmentPattern: checkBinary,
BinaryExpression: checkBinary,
LogicalExpression: checkBinary,
ConditionalExpression: checkConditional,
VariableDeclarator: checkVar,
PropertyDefinition(node) {
if (!node.value) {
return;
}
/*
* Because of computed properties and type annotations, some
* tokens may exist between `node.key` and `=`.
* Therefore, find the `=` from the right.
*/
const operatorToken = sourceCode.getTokenBefore(
node.value,
isEqToken,
);
const leftToken = sourceCode.getTokenBefore(operatorToken);
const rightToken = sourceCode.getTokenAfter(operatorToken);
if (
!sourceCode.isSpaceBetween(leftToken, operatorToken) ||
!sourceCode.isSpaceBetween(operatorToken, rightToken)
) {
report(node, operatorToken);
}
},
};
},
};

View File

@@ -0,0 +1,4 @@
import index from './index.js';
const { transform, transformStyleAttribute, bundle, bundleAsync, browserslistToTargets, composeVisitors, Features } = index;
export { transform, transformStyleAttribute, bundle, bundleAsync, browserslistToTargets, composeVisitors, Features };

View File

@@ -0,0 +1,50 @@
# TypeScript
[![GitHub Actions CI](https://github.com/microsoft/TypeScript/workflows/CI/badge.svg)](https://github.com/microsoft/TypeScript/actions?query=workflow%3ACI)
[![npm version](https://badge.fury.io/js/typescript.svg)](https://www.npmjs.com/package/typescript)
[![Downloads](https://img.shields.io/npm/dm/typescript.svg)](https://www.npmjs.com/package/typescript)
[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/microsoft/TypeScript/badge)](https://securityscorecards.dev/viewer/?uri=github.com/microsoft/TypeScript)
[TypeScript](https://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](https://www.typescriptlang.org/play/), and stay up to date via [our blog](https://blogs.msdn.microsoft.com/typescript) and [Twitter account](https://twitter.com/typescript).
Find others who are using TypeScript at [our community page](https://www.typescriptlang.org/community/).
## Installing
For the latest stable version:
```bash
npm install -D typescript
```
For our nightly builds:
```bash
npm install -D typescript@next
```
## Contribute
There are many ways to [contribute](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md) to TypeScript.
* [Submit bugs](https://github.com/microsoft/TypeScript/issues) and help us verify fixes as they are checked in.
* Review the [source code changes](https://github.com/microsoft/TypeScript/pulls).
* Engage with other TypeScript users and developers on [StackOverflow](https://stackoverflow.com/questions/tagged/typescript).
* Help each other in the [TypeScript Community Discord](https://discord.gg/typescript).
* Join the [#typescript](https://twitter.com/search?q=%23TypeScript) discussion on Twitter.
* [Contribute bug fixes](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md).
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see
the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com)
with any additional questions or comments.
## Documentation
* [TypeScript in 5 minutes](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html)
* [Programming handbook](https://www.typescriptlang.org/docs/handbook/intro.html)
* [Homepage](https://www.typescriptlang.org/)
## Roadmap
For details on our planned features and future direction, please refer to our [roadmap](https://github.com/microsoft/TypeScript/wiki/Roadmap).

View File

@@ -0,0 +1,519 @@
/**
* Experimental implementation of NTT / FFT (Fast Fourier Transform) over finite fields.
* API may change at any time. The code has not been audited. Feature requests are welcome.
* @module
*/
import type { IField } from './modular.ts';
export interface MutableArrayLike<T> {
[index: number]: T;
length: number;
slice(start?: number, end?: number): this;
[Symbol.iterator](): Iterator<T>;
}
function checkU32(n: number) {
// 0xff_ff_ff_ff
if (!Number.isSafeInteger(n) || n < 0 || n > 0xffffffff)
throw new Error('wrong u32 integer:' + n);
return n;
}
/** Checks if integer is in form of `1 << X` */
export function isPowerOfTwo(x: number): boolean {
checkU32(x);
return (x & (x - 1)) === 0 && x !== 0;
}
export function nextPowerOfTwo(n: number): number {
checkU32(n);
if (n <= 1) return 1;
return (1 << (log2(n - 1) + 1)) >>> 0;
}
export function reverseBits(n: number, bits: number): number {
checkU32(n);
let reversed = 0;
for (let i = 0; i < bits; i++, n >>>= 1) reversed = (reversed << 1) | (n & 1);
return reversed;
}
/** Similar to `bitLen(x)-1` but much faster for small integers, like indices */
export function log2(n: number): number {
checkU32(n);
return 31 - Math.clz32(n);
}
/**
* Moves lowest bit to highest position, which at first step splits
* array on even and odd indices, then it applied again to each part,
* which is core of fft
*/
export function bitReversalInplace<T extends MutableArrayLike<any>>(values: T): T {
const n = values.length;
if (n < 2 || !isPowerOfTwo(n))
throw new Error('n must be a power of 2 and greater than 1. Got ' + n);
const bits = log2(n);
for (let i = 0; i < n; i++) {
const j = reverseBits(i, bits);
if (i < j) {
const tmp = values[i];
values[i] = values[j];
values[j] = tmp;
}
}
return values;
}
export function bitReversalPermutation<T>(values: T[]): T[] {
return bitReversalInplace(values.slice()) as T[];
}
const _1n = /** @__PURE__ */ BigInt(1);
function findGenerator(field: IField<bigint>) {
let G = BigInt(2);
for (; field.eql(field.pow(G, field.ORDER >> _1n), field.ONE); G++);
return G;
}
export type RootsOfUnity = {
roots: (bits: number) => bigint[];
brp(bits: number): bigint[];
inverse(bits: number): bigint[];
omega: (bits: number) => bigint;
clear: () => void;
};
/** We limit roots up to 2**31, which is a lot: 2-billion polynomimal should be rare. */
export function rootsOfUnity(field: IField<bigint>, generator?: bigint): RootsOfUnity {
// Factor field.ORDER-1 as oddFactor * 2^powerOfTwo
let oddFactor = field.ORDER - _1n;
let powerOfTwo = 0;
for (; (oddFactor & _1n) !== _1n; powerOfTwo++, oddFactor >>= _1n);
// Find non quadratic residue
let G = generator !== undefined ? BigInt(generator) : findGenerator(field);
// Powers of generator
const omegas: bigint[] = new Array(powerOfTwo + 1);
omegas[powerOfTwo] = field.pow(G, oddFactor);
for (let i = powerOfTwo; i > 0; i--) omegas[i - 1] = field.sqr(omegas[i]);
// Compute all roots of unity for powers up to maxPower
const rootsCache: bigint[][] = [];
const checkBits = (bits: number) => {
checkU32(bits);
if (bits > 31 || bits > powerOfTwo)
throw new Error('rootsOfUnity: wrong bits ' + bits + ' powerOfTwo=' + powerOfTwo);
return bits;
};
const precomputeRoots = (maxPower: number) => {
checkBits(maxPower);
for (let power = maxPower; power >= 0; power--) {
if (rootsCache[power]) continue; // Skip if we've already computed roots for this power
const rootsAtPower: bigint[] = [];
for (let j = 0, cur = field.ONE; j < 2 ** power; j++, cur = field.mul(cur, omegas[power]))
rootsAtPower.push(cur);
rootsCache[power] = rootsAtPower;
}
return rootsCache[maxPower];
};
const brpCache = new Map<number, bigint[]>();
const inverseCache = new Map<number, bigint[]>();
// NOTE: we use bits instead of power, because power = 2**bits,
// but power is not neccesary isPowerOfTwo(power)!
return {
roots: (bits: number): bigint[] => {
const b = checkBits(bits);
return precomputeRoots(b);
},
brp(bits: number): bigint[] {
const b = checkBits(bits);
if (brpCache.has(b)) return brpCache.get(b)!;
else {
const res = bitReversalPermutation(this.roots(b));
brpCache.set(b, res);
return res;
}
},
inverse(bits: number): bigint[] {
const b = checkBits(bits);
if (inverseCache.has(b)) return inverseCache.get(b)!;
else {
const res = field.invertBatch(this.roots(b));
inverseCache.set(b, res);
return res;
}
},
omega: (bits: number): bigint => omegas[checkBits(bits)],
clear: (): void => {
rootsCache.splice(0, rootsCache.length);
brpCache.clear();
},
};
}
export type Polynomial<T> = MutableArrayLike<T>;
/**
* Maps great to Field<bigint>, but not to Group (EC points):
* - inv from scalar field
* - we need multiplyUnsafe here, instead of multiply for speed
* - multiplyUnsafe is safe in the context: we do mul(rootsOfUnity), which are public and sparse
*/
export type FFTOpts<T, R> = {
add: (a: T, b: T) => T;
sub: (a: T, b: T) => T;
mul: (a: T, scalar: R) => T;
inv: (a: R) => R;
};
export type FFTCoreOpts<R> = {
N: number;
roots: Polynomial<R>;
dit: boolean;
invertButterflies?: boolean;
skipStages?: number;
brp?: boolean;
};
export type FFTCoreLoop<T> = <P extends Polynomial<T>>(values: P) => P;
/**
* Constructs different flavors of FFT. radix2 implementation of low level mutating API. Flavors:
*
* - DIT (Decimation-in-Time): Bottom-Up (leaves -> root), Cool-Turkey
* - DIF (Decimation-in-Frequency): Top-Down (root -> leaves), GentlemanSande
*
* DIT takes brp input, returns natural output.
* DIF takes natural input, returns brp output.
*
* The output is actually identical. Time / frequence distinction is not meaningful
* for Polynomial multiplication in fields.
* Which means if protocol supports/needs brp output/inputs, then we can skip this step.
*
* Cyclic NTT: Rq = Zq[x]/(x^n-1). butterfly_DIT+loop_DIT OR butterfly_DIF+loop_DIT, roots are omega
* Negacyclic NTT: Rq = Zq[x]/(x^n+1). butterfly_DIT+loop_DIF, at least for mlkem / mldsa
*/
export const FFTCore = <T, R>(F: FFTOpts<T, R>, coreOpts: FFTCoreOpts<R>): FFTCoreLoop<T> => {
const { N, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;
const bits = log2(N);
if (!isPowerOfTwo(N)) throw new Error('FFT: Polynomial size should be power of two');
const isDit = dit !== invertButterflies;
isDit;
return <P extends Polynomial<T>>(values: P): P => {
if (values.length !== N) throw new Error('FFT: wrong Polynomial length');
if (dit && brp) bitReversalInplace(values);
for (let i = 0, g = 1; i < bits - skipStages; i++) {
// For each stage s (sub-FFT length m = 2^s)
const s = dit ? i + 1 + skipStages : bits - i;
const m = 1 << s;
const m2 = m >> 1;
const stride = N >> s;
// Loop over each subarray of length m
for (let k = 0; k < N; k += m) {
// Loop over each butterfly within the subarray
for (let j = 0, grp = g++; j < m2; j++) {
const rootPos = invertButterflies ? (dit ? N - grp : grp) : j * stride;
const i0 = k + j;
const i1 = k + j + m2;
const omega = roots[rootPos];
const b = values[i1];
const a = values[i0];
// Inlining gives us 10% perf in kyber vs functions
if (isDit) {
const t = F.mul(b, omega); // Standard DIT butterfly
values[i0] = F.add(a, t);
values[i1] = F.sub(a, t);
} else if (invertButterflies) {
values[i0] = F.add(b, a); // DIT loop + inverted butterflies (Kyber decode)
values[i1] = F.mul(F.sub(b, a), omega);
} else {
values[i0] = F.add(a, b); // Standard DIF butterfly
values[i1] = F.mul(F.sub(a, b), omega);
}
}
}
}
if (!dit && brp) bitReversalInplace(values);
return values;
};
};
export type FFTMethods<T> = {
direct<P extends Polynomial<T>>(values: P, brpInput?: boolean, brpOutput?: boolean): P;
inverse<P extends Polynomial<T>>(values: P, brpInput?: boolean, brpOutput?: boolean): P;
};
/**
* NTT aka FFT over finite field (NOT over complex numbers).
* Naming mirrors other libraries.
*/
export function FFT<T>(roots: RootsOfUnity, opts: FFTOpts<T, bigint>): FFTMethods<T> {
const getLoop = (
N: number,
roots: Polynomial<bigint>,
brpInput = false,
brpOutput = false
): (<P extends Polynomial<T>>(values: P) => P) => {
if (brpInput && brpOutput) {
// we cannot optimize this case, but lets support it anyway
return (values) =>
FFTCore(opts, { N, roots, dit: false, brp: false })(bitReversalInplace(values));
}
if (brpInput) return FFTCore(opts, { N, roots, dit: true, brp: false });
if (brpOutput) return FFTCore(opts, { N, roots, dit: false, brp: false });
return FFTCore(opts, { N, roots, dit: true, brp: true }); // all natural
};
return {
direct<P extends Polynomial<T>>(values: P, brpInput = false, brpOutput = false): P {
const N = values.length;
if (!isPowerOfTwo(N)) throw new Error('FFT: Polynomial size should be power of two');
const bits = log2(N);
return getLoop(N, roots.roots(bits), brpInput, brpOutput)<P>(values.slice());
},
inverse<P extends Polynomial<T>>(values: P, brpInput = false, brpOutput = false): P {
const N = values.length;
const bits = log2(N);
const res = getLoop(N, roots.inverse(bits), brpInput, brpOutput)(values.slice());
const ivm = opts.inv(BigInt(values.length)); // scale
// we can get brp output if we use dif instead of dit!
for (let i = 0; i < res.length; i++) res[i] = opts.mul(res[i], ivm);
// Allows to re-use non-inverted roots, but is VERY fragile
// return [res[0]].concat(res.slice(1).reverse());
// inverse calculated as pow(-1), which transforms into ω^{-kn} (-> reverses indices)
return res;
},
};
}
export type CreatePolyFn<P extends Polynomial<T>, T> = (len: number, elm?: T) => P;
export type PolyFn<P extends Polynomial<T>, T> = {
roots: RootsOfUnity;
create: CreatePolyFn<P, T>;
length?: number; // optional enforced size
degree: (a: P) => number;
extend: (a: P, len: number) => P;
add: (a: P, b: P) => P; // fc(x) = fa(x) + fb(x)
sub: (a: P, b: P) => P; // fc(x) = fa(x) - fb(x)
mul: (a: P, b: P | T) => P; // fc(x) = fa(x) * fb(x) OR fc(x) = fa(x) * scalar (same as field)
dot: (a: P, b: P) => P; // point-wise coeff multiplication
convolve: (a: P, b: P) => P;
shift: (p: P, factor: bigint) => P; // point-wise coeffcient shift
clone: (a: P) => P;
// Eval
eval: (a: P, basis: P) => T; // y = fc(x)
monomial: {
basis: (x: T, n: number) => P;
eval: (a: P, x: T) => T;
};
lagrange: {
basis: (x: T, n: number, brp?: boolean) => P;
eval: (a: P, x: T, brp?: boolean) => T;
};
// Complex
vanishing: (roots: P) => P; // f(x) = 0 for every x in roots
};
/**
* Poly wants a cracker.
*
* Polynomials are functions like `y=f(x)`, which means when we multiply two polynomials, result is
* function `f3(x) = f1(x) * f2(x)`, we don't multiply values. Key takeaways:
*
* - **Polynomial** is an array of coefficients: `f(x) = sum(coeff[i] * basis[i](x))`
* - **Basis** is array of functions
* - **Monominal** is Polynomial where `basis[i](x) == x**i` (powers)
* - **Array size** is domain size
* - **Lattice** is matrix (Polynomial of Polynomials)
*/
export function poly<T>(
field: IField<T>,
roots: RootsOfUnity,
create?: undefined,
fft?: FFTMethods<T>,
length?: number
): PolyFn<T[], T>;
export function poly<T, P extends Polynomial<T>>(
field: IField<T>,
roots: RootsOfUnity,
create: CreatePolyFn<P, T>,
fft?: FFTMethods<T>,
length?: number
): PolyFn<P, T>;
export function poly<T, P extends Polynomial<T>>(
field: IField<T>,
roots: RootsOfUnity,
create?: CreatePolyFn<P, T>,
fft?: FFTMethods<T>,
length?: number
): PolyFn<any, T> {
const F = field;
const _create =
create ||
(((len: number, elm?: T): Polynomial<T> => new Array(len).fill(elm ?? F.ZERO)) as CreatePolyFn<
P,
T
>);
const isPoly = (x: any): x is P => Array.isArray(x) || ArrayBuffer.isView(x);
const checkLength = (...lst: P[]): number => {
if (!lst.length) return 0;
for (const i of lst) if (!isPoly(i)) throw new Error('poly: not polynomial: ' + i);
const L = lst[0].length;
for (let i = 1; i < lst.length; i++)
if (lst[i].length !== L) throw new Error(`poly: mismatched lengths ${L} vs ${lst[i].length}`);
if (length !== undefined && L !== length)
throw new Error(`poly: expected fixed length ${length}, got ${L}`);
return L;
};
function findOmegaIndex(x: T, n: number, brp = false): number {
const bits = log2(n);
const omega = brp ? roots.brp(bits) : roots.roots(bits);
for (let i = 0; i < n; i++) if (F.eql(x, omega[i] as T)) return i;
return -1;
}
// TODO: mutating versions for mlkem/mldsa
return {
roots,
create: _create,
length,
extend: (a: P, len: number): P => {
checkLength(a);
const out = _create(len, F.ZERO);
for (let i = 0; i < a.length; i++) out[i] = a[i];
return out;
},
degree: (a: P): number => {
checkLength(a);
for (let i = a.length - 1; i >= 0; i--) if (!F.is0(a[i])) return i;
return -1;
},
add: (a: P, b: P): P => {
const len = checkLength(a, b);
const out = _create(len);
for (let i = 0; i < len; i++) out[i] = F.add(a[i], b[i]);
return out;
},
sub: (a: P, b: P): P => {
const len = checkLength(a, b);
const out = _create(len);
for (let i = 0; i < len; i++) out[i] = F.sub(a[i], b[i]);
return out;
},
dot: (a: P, b: P): P => {
const len = checkLength(a, b);
const out = _create(len);
for (let i = 0; i < len; i++) out[i] = F.mul(a[i], b[i]);
return out;
},
mul: (a: P, b: P | T): P => {
if (isPoly(b)) {
const len = checkLength(a, b);
if (fft) {
const A = fft.direct(a, false, true);
const B = fft.direct(b, false, true);
for (let i = 0; i < A.length; i++) A[i] = F.mul(A[i], B[i]);
return fft.inverse(A, true, false) as P;
} else {
// NOTE: this is quadratic and mostly for compat tests with FFT
const res = _create(len);
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
const k = (i + j) % len; // wrap mod length
res[k] = F.add(res[k], F.mul(a[i], b[j]));
}
}
return res;
}
} else {
const out = _create(checkLength(a));
for (let i = 0; i < out.length; i++) out[i] = F.mul(a[i], b);
return out;
}
},
convolve(a: P, b: P): P {
const len = nextPowerOfTwo(a.length + b.length - 1);
return this.mul(this.extend(a, len), this.extend(b, len));
},
shift(p: P, factor: bigint): P {
const out = _create(checkLength(p));
out[0] = p[0];
for (let i = 1, power = F.ONE; i < p.length; i++) {
power = F.mul(power, factor);
out[i] = F.mul(p[i], power);
}
return out;
},
clone: (a: P): P => {
checkLength(a);
const out = _create(a.length);
for (let i = 0; i < a.length; i++) out[i] = a[i];
return out;
},
eval: (a: P, basis: P): T => {
checkLength(a);
let acc = F.ZERO;
for (let i = 0; i < a.length; i++) acc = F.add(acc, F.mul(a[i], basis[i]));
return acc;
},
monomial: {
basis: (x: T, n: number): P => {
const out = _create(n);
let pow = F.ONE;
for (let i = 0; i < n; i++) {
out[i] = pow;
pow = F.mul(pow, x);
}
return out;
},
eval: (a: P, x: T): T => {
checkLength(a);
// Same as eval(a, monomialBasis(x, a.length)), but it is faster this way
let acc = F.ZERO;
for (let i = a.length - 1; i >= 0; i--) acc = F.add(F.mul(acc, x), a[i]);
return acc;
},
},
lagrange: {
basis: (x: T, n: number, brp = false, weights?: P): P => {
const bits = log2(n);
const cache = weights || brp ? roots.brp(bits) : roots.roots(bits); // [ω⁰, ω¹, ..., ωⁿ⁻¹]
const out = _create(n);
// Fast Kronecker-δ shortcut
const idx = findOmegaIndex(x, n, brp);
if (idx !== -1) {
out[idx] = F.ONE;
return out;
}
const tm = F.pow(x, BigInt(n));
const c = F.mul(F.sub(tm, F.ONE), F.inv(BigInt(n) as T)); // c = (xⁿ - 1)/n
const denom = _create(n);
for (let i = 0; i < n; i++) denom[i] = F.sub(x, cache[i] as T);
const inv = F.invertBatch(denom as any as T[]);
for (let i = 0; i < n; i++) out[i] = F.mul(c, F.mul(cache[i] as T, inv[i]));
return out;
},
eval(a: P, x: T, brp = false): T {
checkLength(a);
const idx = findOmegaIndex(x, a.length, brp);
if (idx !== -1) return a[idx]; // fast path
const L = this.basis(x, a.length, brp); // Lᵢ(x)
let acc = F.ZERO;
for (let i = 0; i < a.length; i++) if (!F.is0(a[i])) acc = F.add(acc, F.mul(a[i], L[i]));
return acc;
},
},
vanishing(roots: P): P {
checkLength(roots);
const out = _create(roots.length + 1, F.ZERO);
out[0] = F.ONE;
for (const r of roots) {
const neg = F.neg(r);
for (let j = out.length - 1; j > 0; j--) out[j] = F.add(F.mul(out[j], neg), out[j - 1]);
out[0] = F.mul(out[0], neg);
}
return out;
},
};
}

View File

@@ -0,0 +1,82 @@
/**
* HKDF (RFC 5869): extract + expand in one step.
* See https://soatok.blog/2021/11/17/understanding-hkdf/.
* @module
*/
import { hmac } from "./hmac.js";
import { ahash, anumber, clean, toBytes } from "./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)
*/
export function extract(hash, ikm, salt) {
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 hmac(hash, toBytes(salt), 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
*/
export function expand(hash, prk, info, length = 32) {
ahash(hash);
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.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();
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);
*/
export const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);
//# sourceMappingURL=hkdf.js.map

View File

@@ -0,0 +1,96 @@
import { VariableSizeCodec, VariableSizeDecoder, VariableSizeEncoder } from '@solana/codecs-core';
/**
* Returns an encoder for `shortU16` values.
*
* This encoder serializes `shortU16` values using **1 to 3 bytes**.
* Smaller values use fewer bytes, while larger values take up more space.
*
* For more details, see {@link getShortU16Codec}.
*
* @returns A `VariableSizeEncoder<number | bigint>` for encoding `shortU16` values.
*
* @example
* Encoding a `shortU16` value.
* ```ts
* const encoder = getShortU16Encoder();
* encoder.encode(42); // 0x2a
* encoder.encode(128); // 0x8001
* encoder.encode(16384); // 0x808001
* ```
*
* @see {@link getShortU16Codec}
*/
export declare const getShortU16Encoder: () => VariableSizeEncoder<bigint | number>;
/**
* Returns a decoder for `shortU16` values.
*
* This decoder deserializes `shortU16` values from **1 to 3 bytes**.
* The number of bytes used depends on the encoded value.
*
* For more details, see {@link getShortU16Codec}.
*
* @returns A `VariableSizeDecoder<number>` for decoding `shortU16` values.
*
* @example
* Decoding a `shortU16` value.
* ```ts
* const decoder = getShortU16Decoder();
* decoder.decode(new Uint8Array([0x2a])); // 42
* decoder.decode(new Uint8Array([0x80, 0x01])); // 128
* decoder.decode(new Uint8Array([0x80, 0x80, 0x01])); // 16384
* ```
*
* @see {@link getShortU16Codec}
*/
export declare const getShortU16Decoder: () => VariableSizeDecoder<number>;
/**
* Returns a codec for encoding and decoding `shortU16` values.
*
* It serializes unsigned integers using **1 to 3 bytes** based on the encoded value.
* The larger the value, the more bytes it uses.
*
* - If the value is `<= 0x7f` (127), it is stored in a **single byte**
* and the first bit is set to `0` to indicate the end of the value.
* - Otherwise, the first bit is set to `1` to indicate that the value continues in the next byte, which follows the same pattern.
* - This process repeats until the value is fully encoded in up to 3 bytes. The third and last byte, if needed, uses all 8 bits to store the remaining value.
*
* In other words, the encoding scheme follows this structure:
*
* ```txt
* 0XXXXXXX <- Values 0 to 127 (1 byte)
* 1XXXXXXX 0XXXXXXX <- Values 128 to 16,383 (2 bytes)
* 1XXXXXXX 1XXXXXXX XXXXXXXX <- Values 16,384 to 4,194,303 (3 bytes)
* ```
*
* @returns A `VariableSizeCodec<number | bigint, number>` for encoding and decoding `shortU16` values.
*
* @example
* Encoding and decoding `shortU16` values.
* ```ts
* const codec = getShortU16Codec();
* const bytes1 = codec.encode(42); // 0x2a
* const bytes2 = codec.encode(128); // 0x8001
* const bytes3 = codec.encode(16384); // 0x808001
*
* codec.decode(bytes1); // 42
* codec.decode(bytes2); // 128
* codec.decode(bytes3); // 16384
* ```
*
* @remarks
* This codec efficiently stores small numbers, making it useful for transactions and compact representations.
*
* If you need a fixed-size `u16` codec, consider using {@link getU16Codec}.
*
* Separate {@link getShortU16Encoder} and {@link getShortU16Decoder} functions are available.
*
* ```ts
* const bytes = getShortU16Encoder().encode(42);
* const value = getShortU16Decoder().decode(bytes);
* ```
*
* @see {@link getShortU16Encoder}
* @see {@link getShortU16Decoder}
*/
export declare const getShortU16Codec: () => VariableSizeCodec<bigint | number, number>;
//# sourceMappingURL=short-u16.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"pbkdf2.js","sourceRoot":"","sources":["../src/pbkdf2.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,kBAAkB;AAClB,OAAO,EACL,KAAK,EAAE,OAAO,EACd,SAAS,EAAE,SAAS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AC,QAAQ,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;QAC5B,6CAA6C;QAC7C,0CAA0C;QAC1C,CAAC,IAAI,GAAG,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC5D,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;QACjC,MAAM,SAAS,CAAC,CAAC,GAAG,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE;YACrC,2BAA2B;YAC3B,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YAC7C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,EAAE;gBAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACpD,CAAC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACjD,CAAC"}

View File

@@ -0,0 +1 @@
{"version":3,"file":"regularExpressionFlags.enum.d.ts","sourceRoot":"","sources":["../../src/enums/regularExpressionFlags.enum.ts"],"names":[],"mappings":"AAAA,oBAAY,sBAAsB;IAC9B,IAAI,IAAI;IACR,UAAU,IAAS;IACnB,MAAM,IAAS;IACf,UAAU,IAAS;IACnB,SAAS,IAAS;IAClB,MAAM,KAAS;IACf,OAAO,KAAS;IAChB,WAAW,KAAS;IACpB,MAAM,MAAS;IACf,cAAc,KAAwB;CACzC"}

View File

@@ -0,0 +1,497 @@
/**
* @fileoverview Rule to check for max length on a line.
* @author Matt DuVall <http://www.mattduvall.com>
* @deprecated in ESLint v8.53.0
*/
"use strict";
//------------------------------------------------------------------------------
// Constants
//------------------------------------------------------------------------------
const OPTIONS_SCHEMA = {
type: "object",
properties: {
code: {
type: "integer",
minimum: 0,
},
comments: {
type: "integer",
minimum: 0,
},
tabWidth: {
type: "integer",
minimum: 0,
},
ignorePattern: {
type: "string",
},
ignoreComments: {
type: "boolean",
},
ignoreStrings: {
type: "boolean",
},
ignoreUrls: {
type: "boolean",
},
ignoreTemplateLiterals: {
type: "boolean",
},
ignoreRegExpLiterals: {
type: "boolean",
},
ignoreTrailingComments: {
type: "boolean",
},
},
additionalProperties: false,
};
const OPTIONS_OR_INTEGER_SCHEMA = {
anyOf: [
OPTIONS_SCHEMA,
{
type: "integer",
minimum: 0,
},
],
};
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
deprecated: {
message: "Formatting rules are being moved out of ESLint core.",
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
deprecatedSince: "8.53.0",
availableUntil: "11.0.0",
replacedBy: [
{
message:
"ESLint Stylistic now maintains deprecated stylistic core rules.",
url: "https://eslint.style/guide/migration",
plugin: {
name: "@stylistic/eslint-plugin",
url: "https://eslint.style",
},
rule: {
name: "max-len",
url: "https://eslint.style/rules/max-len",
},
},
],
},
type: "layout",
docs: {
description: "Enforce a maximum line length",
recommended: false,
url: "https://eslint.org/docs/latest/rules/max-len",
},
schema: [
OPTIONS_OR_INTEGER_SCHEMA,
OPTIONS_OR_INTEGER_SCHEMA,
OPTIONS_SCHEMA,
],
messages: {
max: "This line has a length of {{lineLength}}. Maximum allowed is {{maxLength}}.",
maxComment:
"This line has a comment length of {{lineLength}}. Maximum allowed is {{maxCommentLength}}.",
},
},
create(context) {
/*
* Inspired by https://datatracker.ietf.org/doc/html/rfc3986#appendix-B, however:
* - They're matching an entire string that we know is a URI
* - We're matching part of a string where we think there *might* be a URL
* - We're only concerned about URLs, as picking out any URI would cause
* too many false positives
* - We don't care about matching the entire URL, any small segment is fine
*/
const URL_REGEXP = /[^:/?#]:\/\/[^?#]/u;
const sourceCode = context.sourceCode;
/**
* Computes the length of a line that may contain tabs. The width of each
* tab will be the number of spaces to the next tab stop.
* @param {string} line The line.
* @param {number} tabWidth The width of each tab stop in spaces.
* @returns {number} The computed line length.
* @private
*/
function computeLineLength(line, tabWidth) {
let extraCharacterCount = 0;
line.replace(/\t/gu, (match, offset) => {
const totalOffset = offset + extraCharacterCount,
previousTabStopOffset = tabWidth
? totalOffset % tabWidth
: 0,
spaceCount = tabWidth - previousTabStopOffset;
extraCharacterCount += spaceCount - 1; // -1 for the replaced tab
});
return Array.from(line).length + extraCharacterCount;
}
// The options object must be the last option specified…
const options = Object.assign({}, context.options.at(-1));
// …but max code length…
if (typeof context.options[0] === "number") {
options.code = context.options[0];
}
// …and tabWidth can be optionally specified directly as integers.
if (typeof context.options[1] === "number") {
options.tabWidth = context.options[1];
}
const maxLength = typeof options.code === "number" ? options.code : 80,
tabWidth =
typeof options.tabWidth === "number" ? options.tabWidth : 4,
ignoreComments = !!options.ignoreComments,
ignoreStrings = !!options.ignoreStrings,
ignoreTemplateLiterals = !!options.ignoreTemplateLiterals,
ignoreRegExpLiterals = !!options.ignoreRegExpLiterals,
ignoreTrailingComments =
!!options.ignoreTrailingComments || !!options.ignoreComments,
ignoreUrls = !!options.ignoreUrls,
maxCommentLength = options.comments;
let ignorePattern = options.ignorePattern || null;
if (ignorePattern) {
ignorePattern = new RegExp(ignorePattern, "u");
}
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------
/**
* Tells if a given comment is trailing: it starts on the current line and
* extends to or past the end of the current line.
* @param {string} line The source line we want to check for a trailing comment on
* @param {number} lineNumber The one-indexed line number for line
* @param {ASTNode} comment The comment to inspect
* @returns {boolean} If the comment is trailing on the given line
*/
function isTrailingComment(line, lineNumber, comment) {
return (
comment &&
comment.loc.start.line === lineNumber &&
lineNumber <= comment.loc.end.line &&
(comment.loc.end.line > lineNumber ||
comment.loc.end.column === line.length)
);
}
/**
* Tells if a comment encompasses the entire line.
* @param {string} line The source line with a trailing comment
* @param {number} lineNumber The one-indexed line number this is on
* @param {ASTNode} comment The comment to remove
* @returns {boolean} If the comment covers the entire line
*/
function isFullLineComment(line, lineNumber, comment) {
const start = comment.loc.start,
end = comment.loc.end,
isFirstTokenOnLine = !line
.slice(0, comment.loc.start.column)
.trim();
return (
comment &&
(start.line < lineNumber ||
(start.line === lineNumber && isFirstTokenOnLine)) &&
(end.line > lineNumber ||
(end.line === lineNumber && end.column === line.length))
);
}
/**
* Check if a node is a JSXEmptyExpression contained in a single line JSXExpressionContainer.
* @param {ASTNode} node A node to check.
* @returns {boolean} True if the node is a JSXEmptyExpression contained in a single line JSXExpressionContainer.
*/
function isJSXEmptyExpressionInSingleLineContainer(node) {
if (
!node ||
!node.parent ||
node.type !== "JSXEmptyExpression" ||
node.parent.type !== "JSXExpressionContainer"
) {
return false;
}
const parent = node.parent;
return parent.loc.start.line === parent.loc.end.line;
}
/**
* Gets the line after the comment and any remaining trailing whitespace is
* stripped.
* @param {string} line The source line with a trailing comment
* @param {ASTNode} comment The comment to remove
* @returns {string} Line without comment and trailing whitespace
*/
function stripTrailingComment(line, comment) {
// loc.column is zero-indexed
return line.slice(0, comment.loc.start.column).replace(/\s+$/u, "");
}
/**
* Ensure that an array exists at [key] on `object`, and add `value` to it.
* @param {Object} object the object to mutate
* @param {string} key the object's key
* @param {any} value the value to add
* @returns {void}
* @private
*/
function ensureArrayAndPush(object, key, value) {
if (!Array.isArray(object[key])) {
object[key] = [];
}
object[key].push(value);
}
/**
* Retrieves an array containing all strings (" or ') in the source code.
* @returns {ASTNode[]} An array of string nodes.
*/
function getAllStrings() {
return sourceCode.ast.tokens.filter(
token =>
token.type === "String" ||
(token.type === "JSXText" &&
sourceCode.getNodeByRangeIndex(token.range[0] - 1)
.type === "JSXAttribute"),
);
}
/**
* Retrieves an array containing all template literals in the source code.
* @returns {ASTNode[]} An array of template literal nodes.
*/
function getAllTemplateLiterals() {
return sourceCode.ast.tokens.filter(
token => token.type === "Template",
);
}
/**
* Retrieves an array containing all RegExp literals in the source code.
* @returns {ASTNode[]} An array of RegExp literal nodes.
*/
function getAllRegExpLiterals() {
return sourceCode.ast.tokens.filter(
token => token.type === "RegularExpression",
);
}
/**
*
* reduce an array of AST nodes by line number, both start and end.
* @param {ASTNode[]} arr array of AST nodes
* @returns {Object} accululated AST nodes
*/
function groupArrayByLineNumber(arr) {
const obj = {};
for (let i = 0; i < arr.length; i++) {
const node = arr[i];
for (let j = node.loc.start.line; j <= node.loc.end.line; ++j) {
ensureArrayAndPush(obj, j, node);
}
}
return obj;
}
/**
* Returns an array of all comments in the source code.
* If the element in the array is a JSXEmptyExpression contained with a single line JSXExpressionContainer,
* the element is changed with JSXExpressionContainer node.
* @returns {ASTNode[]} An array of comment nodes
*/
function getAllComments() {
const comments = [];
sourceCode.getAllComments().forEach(commentNode => {
const containingNode = sourceCode.getNodeByRangeIndex(
commentNode.range[0],
);
if (isJSXEmptyExpressionInSingleLineContainer(containingNode)) {
// push a unique node only
if (comments.at(-1) !== containingNode.parent) {
comments.push(containingNode.parent);
}
} else {
comments.push(commentNode);
}
});
return comments;
}
/**
* Check the program for max length
* @param {ASTNode} node Node to examine
* @returns {void}
* @private
*/
function checkProgramForMaxLength(node) {
// split (honors line-ending)
const lines = sourceCode.lines,
// list of comments to ignore
comments =
ignoreComments || maxCommentLength || ignoreTrailingComments
? getAllComments()
: [];
// we iterate over comments in parallel with the lines
let commentsIndex = 0;
const strings = getAllStrings();
const stringsByLine = groupArrayByLineNumber(strings);
const templateLiterals = getAllTemplateLiterals();
const templateLiteralsByLine =
groupArrayByLineNumber(templateLiterals);
const regExpLiterals = getAllRegExpLiterals();
const regExpLiteralsByLine = groupArrayByLineNumber(regExpLiterals);
lines.forEach((line, i) => {
// i is zero-indexed, line numbers are one-indexed
const lineNumber = i + 1;
/*
* if we're checking comment length; we need to know whether this
* line is a comment
*/
let lineIsComment = false;
let textToMeasure;
/*
* We can short-circuit the comment checks if we're already out of
* comments to check.
*/
if (commentsIndex < comments.length) {
let comment;
// iterate over comments until we find one past the current line
do {
comment = comments[++commentsIndex];
} while (comment && comment.loc.start.line <= lineNumber);
// and step back by one
comment = comments[--commentsIndex];
if (isFullLineComment(line, lineNumber, comment)) {
lineIsComment = true;
textToMeasure = line;
} else if (
ignoreTrailingComments &&
isTrailingComment(line, lineNumber, comment)
) {
textToMeasure = stripTrailingComment(line, comment);
// ignore multiple trailing comments in the same line
let lastIndex = commentsIndex;
while (
isTrailingComment(
textToMeasure,
lineNumber,
comments[--lastIndex],
)
) {
textToMeasure = stripTrailingComment(
textToMeasure,
comments[lastIndex],
);
}
} else {
textToMeasure = line;
}
} else {
textToMeasure = line;
}
if (
(ignorePattern && ignorePattern.test(textToMeasure)) ||
(ignoreUrls && URL_REGEXP.test(textToMeasure)) ||
(ignoreStrings && stringsByLine[lineNumber]) ||
(ignoreTemplateLiterals &&
templateLiteralsByLine[lineNumber]) ||
(ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber])
) {
// ignore this line
return;
}
const lineLength = computeLineLength(textToMeasure, tabWidth);
const commentLengthApplies = lineIsComment && maxCommentLength;
if (lineIsComment && ignoreComments) {
return;
}
const loc = {
start: {
line: lineNumber,
column: 0,
},
end: {
line: lineNumber,
column: textToMeasure.length,
},
};
if (commentLengthApplies) {
if (lineLength > maxCommentLength) {
context.report({
node,
loc,
messageId: "maxComment",
data: {
lineLength,
maxCommentLength,
},
});
}
} else if (lineLength > maxLength) {
context.report({
node,
loc,
messageId: "max",
data: {
lineLength,
maxLength,
},
});
}
});
}
//--------------------------------------------------------------------------
// Public API
//--------------------------------------------------------------------------
return {
Program: checkProgramForMaxLength,
};
},
};

View File

@@ -0,0 +1,8 @@
"use strict";
function _class_extract_field_descriptor(receiver, privateMap, action) {
if (!privateMap.has(receiver)) throw new TypeError("attempted to " + action + " private field on non-instance");
return privateMap.get(receiver);
}
exports._ = _class_extract_field_descriptor;

View File

@@ -0,0 +1,135 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
const util = __importStar(require("../core/util.cjs"));
const error = () => {
const Sizable = {
string: { unit: "caratteri", verb: "avere" },
file: { unit: "byte", verb: "avere" },
array: { unit: "elementi", verb: "avere" },
set: { unit: "elementi", verb: "avere" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "input",
email: "indirizzo 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: "data e ora ISO",
date: "data ISO",
time: "ora ISO",
duration: "durata ISO",
ipv4: "indirizzo IPv4",
ipv6: "indirizzo IPv6",
cidrv4: "intervallo IPv4",
cidrv6: "intervallo IPv6",
base64: "stringa codificata in base64",
base64url: "URL codificata in base64",
json_string: "stringa JSON",
e164: "numero E.164",
jwt: "JWT",
template_literal: "input",
};
const TypeDictionary = {
nan: "NaN",
number: "numero",
array: "vettore",
};
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 `Input non valido: atteso instanceof ${issue.expected}, ricevuto ${received}`;
}
return `Input non valido: atteso ${expected}, ricevuto ${received}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Input non valido: atteso ${util.stringifyPrimitive(issue.values[0])}`;
return `Opzione non valida: atteso uno tra ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Troppo grande: ${issue.origin ?? "valore"} deve avere ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementi"}`;
return `Troppo grande: ${issue.origin ?? "valore"} deve essere ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Troppo piccolo: ${issue.origin} deve avere ${adj}${issue.minimum.toString()} ${sizing.unit}`;
}
return `Troppo piccolo: ${issue.origin} deve essere ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with")
return `Stringa non valida: deve iniziare con "${_issue.prefix}"`;
if (_issue.format === "ends_with")
return `Stringa non valida: deve terminare con "${_issue.suffix}"`;
if (_issue.format === "includes")
return `Stringa non valida: deve includere "${_issue.includes}"`;
if (_issue.format === "regex")
return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;
return `Input non valido: ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Numero non valido: deve essere un multiplo di ${issue.divisor}`;
case "unrecognized_keys":
return `Chiav${issue.keys.length > 1 ? "i" : "e"} non riconosciut${issue.keys.length > 1 ? "e" : "a"}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Chiave non valida in ${issue.origin}`;
case "invalid_union":
return "Input non valido";
case "invalid_element":
return `Valore non valido in ${issue.origin}`;
default:
return `Input non valido`;
}
};
};
function default_1() {
return {
localeError: error(),
};
}
module.exports = exports.default;

View File

@@ -0,0 +1,27 @@
{
"name": "@types/estree",
"version": "1.0.9",
"description": "TypeScript definitions for estree",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree",
"license": "MIT",
"contributors": [
{
"name": "RReverser",
"githubUsername": "RReverser",
"url": "https://github.com/RReverser"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/estree"
},
"scripts": {},
"dependencies": {},
"peerDependencies": {},
"typesPublisherContentHash": "db16da859cb0bee641414117047a4becba2e9f39d3e14a6745f887c47ef68482",
"typeScriptVersion": "5.3",
"nonNpm": true
}

View File

@@ -0,0 +1,91 @@
import type { Lib, TSESTree } from '@typescript-eslint/types';
import type { Scope } from '../scope';
import type { ScopeManager } from '../ScopeManager';
import type { ReferenceImplicitGlobal } from './Reference';
import type { VisitorOptions } from './Visitor';
import { Visitor } from './Visitor';
export interface ReferencerOptions extends VisitorOptions {
jsxFragmentName: string | null;
jsxPragma: string | null;
lib: Lib[];
}
export declare class Referencer extends Visitor {
#private;
readonly scopeManager: ScopeManager;
constructor(options: ReferencerOptions, scopeManager: ScopeManager);
private populateGlobalsFromLib;
/**
* Resolves lib names into a deduplicated set of LibDefinitions,
* including all transitive dependencies.
*/
private resolveLibDefinitions;
close(node: TSESTree.Node): void;
currentScope(): Scope;
currentScope(throwOnNull: true): Scope | null;
referencingDefaultValue(pattern: TSESTree.Identifier, assignments: (TSESTree.AssignmentExpression | TSESTree.AssignmentPattern)[], maybeImplicitGlobal: ReferenceImplicitGlobal | null, init: boolean): void;
/**
* Searches for a variable named "name" in the upper scopes and adds a pseudo-reference from itself to itself
*/
private referenceInSomeUpperScope;
private referenceJsxFragment;
private referenceJsxPragma;
protected visitClass(node: TSESTree.ClassDeclaration | TSESTree.ClassExpression): void;
protected visitForIn(node: TSESTree.ForInStatement | TSESTree.ForOfStatement): void;
protected visitFunction(node: TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclaration | TSESTree.FunctionExpression | TSESTree.TSDeclareFunction | TSESTree.TSEmptyBodyFunctionExpression): void;
protected visitFunctionParameterTypeAnnotation(node: TSESTree.Parameter): void;
protected visitJSXElement(node: TSESTree.JSXClosingElement | TSESTree.JSXOpeningElement): void;
protected visitProperty(node: TSESTree.Property): void;
protected visitType(node: TSESTree.Node | null | undefined): void;
protected visitTypeAssertion(node: TSESTree.TSAsExpression | TSESTree.TSSatisfiesExpression | TSESTree.TSTypeAssertion): void;
protected ArrowFunctionExpression(node: TSESTree.ArrowFunctionExpression): void;
protected AssignmentExpression(node: TSESTree.AssignmentExpression): void;
protected BlockStatement(node: TSESTree.BlockStatement): void;
protected BreakStatement(): void;
protected CallExpression(node: TSESTree.CallExpression): void;
protected CatchClause(node: TSESTree.CatchClause): void;
protected ClassDeclaration(node: TSESTree.ClassDeclaration): void;
protected ClassExpression(node: TSESTree.ClassExpression): void;
protected ContinueStatement(): void;
protected ExportAllDeclaration(): void;
protected ExportDefaultDeclaration(node: TSESTree.ExportDefaultDeclaration): void;
protected ExportNamedDeclaration(node: TSESTree.ExportNamedDeclaration): void;
protected ForInStatement(node: TSESTree.ForInStatement): void;
protected ForOfStatement(node: TSESTree.ForOfStatement): void;
protected ForStatement(node: TSESTree.ForStatement): void;
protected FunctionDeclaration(node: TSESTree.FunctionDeclaration): void;
protected FunctionExpression(node: TSESTree.FunctionExpression): void;
protected Identifier(node: TSESTree.Identifier): void;
protected ImportAttribute(): void;
protected ImportDeclaration(node: TSESTree.ImportDeclaration): void;
protected JSXAttribute(node: TSESTree.JSXAttribute): void;
protected JSXClosingElement(node: TSESTree.JSXClosingElement): void;
protected JSXFragment(node: TSESTree.JSXFragment): void;
protected JSXIdentifier(node: TSESTree.JSXIdentifier): void;
protected JSXMemberExpression(node: TSESTree.JSXMemberExpression): void;
protected JSXOpeningElement(node: TSESTree.JSXOpeningElement): void;
protected LabeledStatement(node: TSESTree.LabeledStatement): void;
protected MemberExpression(node: TSESTree.MemberExpression): void;
protected MetaProperty(): void;
protected NewExpression(node: TSESTree.NewExpression): void;
protected PrivateIdentifier(): void;
protected Program(node: TSESTree.Program): void;
protected Property(node: TSESTree.Property): void;
protected SwitchStatement(node: TSESTree.SwitchStatement): void;
protected TaggedTemplateExpression(node: TSESTree.TaggedTemplateExpression): void;
protected TSAsExpression(node: TSESTree.TSAsExpression): void;
protected TSDeclareFunction(node: TSESTree.TSDeclareFunction): void;
protected TSEmptyBodyFunctionExpression(node: TSESTree.TSEmptyBodyFunctionExpression): void;
protected TSEnumDeclaration(node: TSESTree.TSEnumDeclaration): void;
protected TSExportAssignment(node: TSESTree.TSExportAssignment): void;
protected TSImportEqualsDeclaration(node: TSESTree.TSImportEqualsDeclaration): void;
protected TSInstantiationExpression(node: TSESTree.TSInstantiationExpression): void;
protected TSInterfaceDeclaration(node: TSESTree.TSInterfaceDeclaration): void;
protected TSModuleDeclaration(node: TSESTree.TSModuleDeclaration): void;
protected TSSatisfiesExpression(node: TSESTree.TSSatisfiesExpression): void;
protected TSTypeAliasDeclaration(node: TSESTree.TSTypeAliasDeclaration): void;
protected TSTypeAssertion(node: TSESTree.TSTypeAssertion): void;
protected UpdateExpression(node: TSESTree.UpdateExpression): void;
protected VariableDeclaration(node: TSESTree.VariableDeclaration): void;
protected WithStatement(node: TSESTree.WithStatement): void;
private visitExpressionTarget;
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"crypto.js","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAOA,MAAM,CAAC,MAAM,MAAM,GACjB,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC"}

View File

@@ -0,0 +1 @@
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