WIP: bootstrap and partial real Solana watcher implementation
This commit is contained in:
@@ -0,0 +1 @@
|
||||
ghghghhg
|
||||
@@ -0,0 +1,8 @@
|
||||
import arrayWithHoles from "./arrayWithHoles.js";
|
||||
import iterableToArray from "./iterableToArray.js";
|
||||
import unsupportedIterableToArray from "./unsupportedIterableToArray.js";
|
||||
import nonIterableRest from "./nonIterableRest.js";
|
||||
function _toArray(r) {
|
||||
return arrayWithHoles(r) || iterableToArray(r) || unsupportedIterableToArray(r) || nonIterableRest();
|
||||
}
|
||||
export { _toArray as default };
|
||||
@@ -0,0 +1,17 @@
|
||||
import { SCHEMES } from "./uri";
|
||||
import http from "./schemes/http";
|
||||
SCHEMES[http.scheme] = http;
|
||||
import https from "./schemes/https";
|
||||
SCHEMES[https.scheme] = https;
|
||||
import ws from "./schemes/ws";
|
||||
SCHEMES[ws.scheme] = ws;
|
||||
import wss from "./schemes/wss";
|
||||
SCHEMES[wss.scheme] = wss;
|
||||
import mailto from "./schemes/mailto";
|
||||
SCHEMES[mailto.scheme] = mailto;
|
||||
import urn from "./schemes/urn";
|
||||
SCHEMES[urn.scheme] = urn;
|
||||
import uuid from "./schemes/urn-uuid";
|
||||
SCHEMES[uuid.scheme] = uuid;
|
||||
export * from "./uri";
|
||||
//# sourceMappingURL=index.js.map
|
||||
@@ -0,0 +1,22 @@
|
||||
/*! *****************************************************************************
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
||||
this file except in compliance with the License. You may obtain a copy of the
|
||||
License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
||||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
||||
MERCHANTABILITY OR NON-INFRINGEMENT.
|
||||
|
||||
See the Apache Version 2.0 License for specific language governing permissions
|
||||
and limitations under the License.
|
||||
***************************************************************************** */
|
||||
|
||||
|
||||
/// <reference lib="es2022" />
|
||||
/// <reference lib="dom" />
|
||||
/// <reference lib="webworker.importscripts" />
|
||||
/// <reference lib="scripthost" />
|
||||
/// <reference lib="dom.iterable" />
|
||||
/// <reference lib="dom.asynciterable" />
|
||||
@@ -0,0 +1,4 @@
|
||||
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"errorMessageClass" | "errorMessageInterface", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
|
||||
name: string;
|
||||
};
|
||||
export default _default;
|
||||
@@ -0,0 +1,450 @@
|
||||
// @ts-check
|
||||
/** @typedef {import('./index').Visitor} Visitor */
|
||||
/** @typedef {import('./index').VisitorFunction} VisitorFunction */
|
||||
|
||||
/**
|
||||
* Composes multiple visitor objects into a single one.
|
||||
* @param {(Visitor | VisitorFunction)[]} visitors
|
||||
* @return {Visitor | VisitorFunction}
|
||||
*/
|
||||
function composeVisitors(visitors) {
|
||||
if (visitors.length === 1) {
|
||||
return visitors[0];
|
||||
}
|
||||
|
||||
if (visitors.some(v => typeof v === 'function')) {
|
||||
return (opts) => {
|
||||
let v = visitors.map(v => typeof v === 'function' ? v(opts) : v);
|
||||
return composeVisitors(v);
|
||||
};
|
||||
}
|
||||
|
||||
/** @type Visitor */
|
||||
let res = {};
|
||||
composeSimpleVisitors(res, visitors, 'StyleSheet');
|
||||
composeSimpleVisitors(res, visitors, 'StyleSheetExit');
|
||||
composeObjectVisitors(res, visitors, 'Rule', ruleVisitor, wrapCustomAndUnknownAtRule);
|
||||
composeObjectVisitors(res, visitors, 'RuleExit', ruleVisitor, wrapCustomAndUnknownAtRule);
|
||||
composeObjectVisitors(res, visitors, 'Declaration', declarationVisitor, wrapCustomProperty);
|
||||
composeObjectVisitors(res, visitors, 'DeclarationExit', declarationVisitor, wrapCustomProperty);
|
||||
composeSimpleVisitors(res, visitors, 'Url');
|
||||
composeSimpleVisitors(res, visitors, 'Color');
|
||||
composeSimpleVisitors(res, visitors, 'Image');
|
||||
composeSimpleVisitors(res, visitors, 'ImageExit');
|
||||
composeSimpleVisitors(res, visitors, 'Length');
|
||||
composeSimpleVisitors(res, visitors, 'Angle');
|
||||
composeSimpleVisitors(res, visitors, 'Ratio');
|
||||
composeSimpleVisitors(res, visitors, 'Resolution');
|
||||
composeSimpleVisitors(res, visitors, 'Time');
|
||||
composeSimpleVisitors(res, visitors, 'CustomIdent');
|
||||
composeSimpleVisitors(res, visitors, 'DashedIdent');
|
||||
composeArrayFunctions(res, visitors, 'MediaQuery');
|
||||
composeArrayFunctions(res, visitors, 'MediaQueryExit');
|
||||
composeSimpleVisitors(res, visitors, 'SupportsCondition');
|
||||
composeSimpleVisitors(res, visitors, 'SupportsConditionExit');
|
||||
composeArrayFunctions(res, visitors, 'Selector');
|
||||
composeTokenVisitors(res, visitors, 'Token', 'token', false);
|
||||
composeTokenVisitors(res, visitors, 'Function', 'function', false);
|
||||
composeTokenVisitors(res, visitors, 'FunctionExit', 'function', true);
|
||||
composeTokenVisitors(res, visitors, 'Variable', 'var', false);
|
||||
composeTokenVisitors(res, visitors, 'VariableExit', 'var', true);
|
||||
composeTokenVisitors(res, visitors, 'EnvironmentVariable', 'env', false);
|
||||
composeTokenVisitors(res, visitors, 'EnvironmentVariableExit', 'env', true);
|
||||
return res;
|
||||
}
|
||||
|
||||
module.exports = composeVisitors;
|
||||
|
||||
function wrapCustomAndUnknownAtRule(k, f) {
|
||||
if (k === 'unknown') {
|
||||
return (value => f({ type: 'unknown', value }));
|
||||
}
|
||||
if (k === 'custom') {
|
||||
return (value => f({ type: 'custom', value }));
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
function wrapCustomProperty(k, f) {
|
||||
return k === 'custom' ? (value => f({ property: 'custom', value })) : f;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('./index').Visitor['Rule']} f
|
||||
* @param {import('./ast').Rule} item
|
||||
*/
|
||||
function ruleVisitor(f, item) {
|
||||
if (typeof f === 'object') {
|
||||
if (item.type === 'unknown') {
|
||||
let v = f.unknown;
|
||||
if (typeof v === 'object') {
|
||||
v = v[item.value.name];
|
||||
}
|
||||
return v?.(item.value);
|
||||
}
|
||||
if (item.type === 'custom') {
|
||||
let v = f.custom;
|
||||
if (typeof v === 'object') {
|
||||
v = v[item.value.name];
|
||||
}
|
||||
return v?.(item.value);
|
||||
}
|
||||
return f[item.type]?.(item);
|
||||
}
|
||||
return f?.(item);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('./index').Visitor['Declaration']} f
|
||||
* @param {import('./ast').Declaration} item
|
||||
*/
|
||||
function declarationVisitor(f, item) {
|
||||
if (typeof f === 'object') {
|
||||
/** @type {string} */
|
||||
let name = item.property;
|
||||
if (item.property === 'unparsed') {
|
||||
name = item.value.propertyId.property;
|
||||
} else if (item.property === 'custom') {
|
||||
let v = f.custom;
|
||||
if (typeof v === 'object') {
|
||||
v = v[item.value.name];
|
||||
}
|
||||
return v?.(item.value);
|
||||
}
|
||||
return f[name]?.(item);
|
||||
}
|
||||
return f?.(item);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Visitor[]} visitors
|
||||
* @param {string} key
|
||||
* @returns {[any[], boolean, Set<string>]}
|
||||
*/
|
||||
function extractObjectsOrFunctions(visitors, key) {
|
||||
let values = [];
|
||||
let hasFunction = false;
|
||||
let allKeys = new Set();
|
||||
for (let visitor of visitors) {
|
||||
let v = visitor[key];
|
||||
if (v) {
|
||||
if (typeof v === 'function') {
|
||||
hasFunction = true;
|
||||
} else {
|
||||
for (let key in v) {
|
||||
allKeys.add(key);
|
||||
}
|
||||
}
|
||||
values.push(v);
|
||||
}
|
||||
}
|
||||
return [values, hasFunction, allKeys];
|
||||
}
|
||||
|
||||
/**
|
||||
* @template {keyof Visitor} K
|
||||
* @param {Visitor} res
|
||||
* @param {Visitor[]} visitors
|
||||
* @param {K} key
|
||||
* @param {(visitor: Visitor[K], item: any) => any | any[] | void} apply
|
||||
* @param {(k: string, f: any) => any} wrapKey
|
||||
*/
|
||||
function composeObjectVisitors(res, visitors, key, apply, wrapKey) {
|
||||
let [values, hasFunction, allKeys] = extractObjectsOrFunctions(visitors, key);
|
||||
if (values.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (values.length === 1) {
|
||||
res[key] = values[0];
|
||||
return;
|
||||
}
|
||||
|
||||
let f = createArrayVisitor(visitors, (visitor, item) => apply(visitor[key], item));
|
||||
if (hasFunction) {
|
||||
res[key] = f;
|
||||
} else {
|
||||
/** @type {any} */
|
||||
let v = {};
|
||||
for (let k of allKeys) {
|
||||
v[k] = wrapKey(k, f);
|
||||
}
|
||||
res[key] = v;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Visitor} res
|
||||
* @param {Visitor[]} visitors
|
||||
* @param {string} key
|
||||
* @param {import('./ast').TokenOrValue['type']} type
|
||||
* @param {boolean} isExit
|
||||
*/
|
||||
function composeTokenVisitors(res, visitors, key, type, isExit) {
|
||||
let [values, hasFunction, allKeys] = extractObjectsOrFunctions(visitors, key);
|
||||
if (values.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (values.length === 1) {
|
||||
res[key] = values[0];
|
||||
return;
|
||||
}
|
||||
|
||||
let f = createTokenVisitor(visitors, type, isExit);
|
||||
if (hasFunction) {
|
||||
res[key] = f;
|
||||
} else {
|
||||
let v = {};
|
||||
for (let key of allKeys) {
|
||||
v[key] = f;
|
||||
}
|
||||
res[key] = v;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Visitor[]} visitors
|
||||
* @param {import('./ast').TokenOrValue['type']} type
|
||||
*/
|
||||
function createTokenVisitor(visitors, type, isExit) {
|
||||
let v = createArrayVisitor(visitors, (visitor, /** @type {import('./ast').TokenOrValue} */ item) => {
|
||||
let f;
|
||||
switch (item.type) {
|
||||
case 'token':
|
||||
f = visitor.Token;
|
||||
if (typeof f === 'object') {
|
||||
f = f[item.value.type];
|
||||
}
|
||||
break;
|
||||
case 'function':
|
||||
f = isExit ? visitor.FunctionExit : visitor.Function;
|
||||
if (typeof f === 'object') {
|
||||
f = f[item.value.name];
|
||||
}
|
||||
break;
|
||||
case 'var':
|
||||
f = isExit ? visitor.VariableExit : visitor.Variable;
|
||||
break;
|
||||
case 'env':
|
||||
f = isExit ? visitor.EnvironmentVariableExit : visitor.EnvironmentVariable;
|
||||
if (typeof f === 'object') {
|
||||
let name;
|
||||
switch (item.value.name.type) {
|
||||
case 'ua':
|
||||
case 'unknown':
|
||||
name = item.value.name.value;
|
||||
break;
|
||||
case 'custom':
|
||||
name = item.value.name.ident;
|
||||
break;
|
||||
}
|
||||
f = f[name];
|
||||
}
|
||||
break;
|
||||
case 'color':
|
||||
f = visitor.Color;
|
||||
break;
|
||||
case 'url':
|
||||
f = visitor.Url;
|
||||
break;
|
||||
case 'length':
|
||||
f = visitor.Length;
|
||||
break;
|
||||
case 'angle':
|
||||
f = visitor.Angle;
|
||||
break;
|
||||
case 'time':
|
||||
f = visitor.Time;
|
||||
break;
|
||||
case 'resolution':
|
||||
f = visitor.Resolution;
|
||||
break;
|
||||
case 'dashed-ident':
|
||||
f = visitor.DashedIdent;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!f) {
|
||||
return;
|
||||
}
|
||||
|
||||
let res = f(item.value);
|
||||
switch (item.type) {
|
||||
case 'color':
|
||||
case 'url':
|
||||
case 'length':
|
||||
case 'angle':
|
||||
case 'time':
|
||||
case 'resolution':
|
||||
case 'dashed-ident':
|
||||
if (Array.isArray(res)) {
|
||||
res = res.map(value => ({ type: item.type, value }))
|
||||
} else if (res) {
|
||||
res = { type: item.type, value: res };
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return res;
|
||||
});
|
||||
|
||||
return value => v({ type, value });
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Visitor[]} visitors
|
||||
* @param {string} key
|
||||
*/
|
||||
function extractFunctions(visitors, key) {
|
||||
let functions = [];
|
||||
for (let visitor of visitors) {
|
||||
let f = visitor[key];
|
||||
if (f) {
|
||||
functions.push(f);
|
||||
}
|
||||
}
|
||||
return functions;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Visitor} res
|
||||
* @param {Visitor[]} visitors
|
||||
* @param {string} key
|
||||
*/
|
||||
function composeSimpleVisitors(res, visitors, key) {
|
||||
let functions = extractFunctions(visitors, key);
|
||||
if (functions.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (functions.length === 1) {
|
||||
res[key] = functions[0];
|
||||
return;
|
||||
}
|
||||
|
||||
res[key] = arg => {
|
||||
let mutated = false;
|
||||
for (let f of functions) {
|
||||
let res = f(arg);
|
||||
if (res) {
|
||||
arg = res;
|
||||
mutated = true;
|
||||
}
|
||||
}
|
||||
|
||||
return mutated ? arg : undefined;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Visitor} res
|
||||
* @param {Visitor[]} visitors
|
||||
* @param {string} key
|
||||
*/
|
||||
function composeArrayFunctions(res, visitors, key) {
|
||||
let functions = extractFunctions(visitors, key);
|
||||
if (functions.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (functions.length === 1) {
|
||||
res[key] = functions[0];
|
||||
return;
|
||||
}
|
||||
|
||||
res[key] = createArrayVisitor(functions, (f, item) => f(item));
|
||||
}
|
||||
|
||||
/**
|
||||
* @template T
|
||||
* @template V
|
||||
* @param {T[]} visitors
|
||||
* @param {(visitor: T, item: V) => V | V[] | void} apply
|
||||
* @returns {(item: V) => V | V[] | void}
|
||||
*/
|
||||
function createArrayVisitor(visitors, apply) {
|
||||
let seen = new Bitset(visitors.length);
|
||||
return arg => {
|
||||
let arr = [arg];
|
||||
let mutated = false;
|
||||
seen.clear();
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
// For each value, call all visitors. If a visitor returns a new value,
|
||||
// we start over, but skip the visitor that generated the value or saw
|
||||
// it before (to avoid cycles). This way, visitors can be composed in any order.
|
||||
for (let v = 0; v < visitors.length && i < arr.length;) {
|
||||
if (seen.get(v)) {
|
||||
v++;
|
||||
continue;
|
||||
}
|
||||
|
||||
let item = arr[i];
|
||||
let visitor = visitors[v];
|
||||
let res = apply(visitor, item);
|
||||
if (Array.isArray(res)) {
|
||||
if (res.length === 0) {
|
||||
arr.splice(i, 1);
|
||||
} else if (res.length === 1) {
|
||||
arr[i] = res[0];
|
||||
} else {
|
||||
arr.splice(i, 1, ...res);
|
||||
}
|
||||
mutated = true;
|
||||
seen.set(v);
|
||||
v = 0;
|
||||
} else if (res) {
|
||||
arr[i] = res;
|
||||
mutated = true;
|
||||
seen.set(v);
|
||||
v = 0;
|
||||
} else {
|
||||
v++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!mutated) {
|
||||
return;
|
||||
}
|
||||
|
||||
return arr.length === 1 ? arr[0] : arr;
|
||||
};
|
||||
}
|
||||
|
||||
class Bitset {
|
||||
constructor(maxBits = 32) {
|
||||
this.bits = 0;
|
||||
this.more = maxBits > 32 ? new Uint32Array(Math.ceil((maxBits - 32) / 32)) : null;
|
||||
}
|
||||
|
||||
/** @param {number} bit */
|
||||
get(bit) {
|
||||
if (bit >= 32 && this.more) {
|
||||
let i = Math.floor((bit - 32) / 32);
|
||||
let b = bit % 32;
|
||||
return Boolean(this.more[i] & (1 << b));
|
||||
} else {
|
||||
return Boolean(this.bits & (1 << bit));
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {number} bit */
|
||||
set(bit) {
|
||||
if (bit >= 32 && this.more) {
|
||||
let i = Math.floor((bit - 32) / 32);
|
||||
let b = bit % 32;
|
||||
this.more[i] |= 1 << b;
|
||||
} else {
|
||||
this.bits |= 1 << bit;
|
||||
}
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.bits = 0;
|
||||
if (this.more) {
|
||||
this.more.fill(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"ripemd160.d.ts","sourceRoot":"","sources":["src/ripemd160.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,SAAS,IAAI,UAAU,EAAE,SAAS,IAAI,UAAU,EAAE,MAAM,aAAa,CAAC;AAC/E,+DAA+D;AAC/D,eAAO,MAAM,SAAS,EAAE,OAAO,UAAuB,CAAC;AACvD,+DAA+D;AAC/D,eAAO,MAAM,SAAS,EAAE,OAAO,UAAuB,CAAC"}
|
||||
@@ -0,0 +1,74 @@
|
||||
'use strict'
|
||||
|
||||
const setLevelSym = Symbol('pino.setLevel')
|
||||
const getLevelSym = Symbol('pino.getLevel')
|
||||
const levelValSym = Symbol('pino.levelVal')
|
||||
const levelCompSym = Symbol('pino.levelComp')
|
||||
const useLevelLabelsSym = Symbol('pino.useLevelLabels')
|
||||
const useOnlyCustomLevelsSym = Symbol('pino.useOnlyCustomLevels')
|
||||
const mixinSym = Symbol('pino.mixin')
|
||||
|
||||
const lsCacheSym = Symbol('pino.lsCache')
|
||||
const chindingsSym = Symbol('pino.chindings')
|
||||
|
||||
const asJsonSym = Symbol('pino.asJson')
|
||||
const writeSym = Symbol('pino.write')
|
||||
const redactFmtSym = Symbol('pino.redactFmt')
|
||||
|
||||
const timeSym = Symbol('pino.time')
|
||||
const timeSliceIndexSym = Symbol('pino.timeSliceIndex')
|
||||
const streamSym = Symbol('pino.stream')
|
||||
const stringifySym = Symbol('pino.stringify')
|
||||
const stringifySafeSym = Symbol('pino.stringifySafe')
|
||||
const stringifiersSym = Symbol('pino.stringifiers')
|
||||
const endSym = Symbol('pino.end')
|
||||
const formatOptsSym = Symbol('pino.formatOpts')
|
||||
const messageKeySym = Symbol('pino.messageKey')
|
||||
const errorKeySym = Symbol('pino.errorKey')
|
||||
const nestedKeySym = Symbol('pino.nestedKey')
|
||||
const nestedKeyStrSym = Symbol('pino.nestedKeyStr')
|
||||
const mixinMergeStrategySym = Symbol('pino.mixinMergeStrategy')
|
||||
const msgPrefixSym = Symbol('pino.msgPrefix')
|
||||
|
||||
const wildcardFirstSym = Symbol('pino.wildcardFirst')
|
||||
|
||||
// public symbols, no need to use the same pino
|
||||
// version for these
|
||||
const serializersSym = Symbol.for('pino.serializers')
|
||||
const formattersSym = Symbol.for('pino.formatters')
|
||||
const hooksSym = Symbol.for('pino.hooks')
|
||||
const needsMetadataGsym = Symbol.for('pino.metadata')
|
||||
|
||||
module.exports = {
|
||||
setLevelSym,
|
||||
getLevelSym,
|
||||
levelValSym,
|
||||
levelCompSym,
|
||||
useLevelLabelsSym,
|
||||
mixinSym,
|
||||
lsCacheSym,
|
||||
chindingsSym,
|
||||
asJsonSym,
|
||||
writeSym,
|
||||
serializersSym,
|
||||
redactFmtSym,
|
||||
timeSym,
|
||||
timeSliceIndexSym,
|
||||
streamSym,
|
||||
stringifySym,
|
||||
stringifySafeSym,
|
||||
stringifiersSym,
|
||||
endSym,
|
||||
formatOptsSym,
|
||||
messageKeySym,
|
||||
errorKeySym,
|
||||
nestedKeySym,
|
||||
wildcardFirstSym,
|
||||
needsMetadataGsym,
|
||||
useOnlyCustomLevelsSym,
|
||||
formattersSym,
|
||||
hooksSym,
|
||||
nestedKeyStrSym,
|
||||
mixinMergeStrategySym,
|
||||
msgPrefixSym
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
declare module "node:domain" {
|
||||
import { EventEmitter } from "node:events";
|
||||
/**
|
||||
* The `Domain` class encapsulates the functionality of routing errors and
|
||||
* uncaught exceptions to the active `Domain` object.
|
||||
*
|
||||
* To handle the errors that it catches, listen to its `'error'` event.
|
||||
*/
|
||||
class Domain extends EventEmitter {
|
||||
/**
|
||||
* An array of event emitters that have been explicitly added to the domain.
|
||||
*/
|
||||
members: EventEmitter[];
|
||||
/**
|
||||
* The `enter()` method is plumbing used by the `run()`, `bind()`, and `intercept()` methods to set the active domain. It sets `domain.active` and `process.domain` to the domain, and implicitly
|
||||
* pushes the domain onto the domain
|
||||
* stack managed by the domain module (see {@link exit} for details on the
|
||||
* domain stack). The call to `enter()` delimits the beginning of a chain of
|
||||
* asynchronous calls and I/O operations bound to a domain.
|
||||
*
|
||||
* Calling `enter()` changes only the active domain, and does not alter the domain
|
||||
* itself. `enter()` and `exit()` can be called an arbitrary number of times on a
|
||||
* single domain.
|
||||
*/
|
||||
enter(): void;
|
||||
/**
|
||||
* The `exit()` method exits the current domain, popping it off the domain stack.
|
||||
* Any time execution is going to switch to the context of a different chain of
|
||||
* asynchronous calls, it's important to ensure that the current domain is exited.
|
||||
* The call to `exit()` delimits either the end of or an interruption to the chain
|
||||
* of asynchronous calls and I/O operations bound to a domain.
|
||||
*
|
||||
* If there are multiple, nested domains bound to the current execution context, `exit()` will exit any domains nested within this domain.
|
||||
*
|
||||
* Calling `exit()` changes only the active domain, and does not alter the domain
|
||||
* itself. `enter()` and `exit()` can be called an arbitrary number of times on a
|
||||
* single domain.
|
||||
*/
|
||||
exit(): void;
|
||||
/**
|
||||
* Run the supplied function in the context of the domain, implicitly
|
||||
* binding all event emitters, timers, and low-level requests that are
|
||||
* created in that context. Optionally, arguments can be passed to
|
||||
* the function.
|
||||
*
|
||||
* This is the most basic way to use a domain.
|
||||
*
|
||||
* ```js
|
||||
* import domain from 'node:domain';
|
||||
* import fs from 'node:fs';
|
||||
* const d = domain.create();
|
||||
* d.on('error', (er) => {
|
||||
* console.error('Caught error!', er);
|
||||
* });
|
||||
* d.run(() => {
|
||||
* process.nextTick(() => {
|
||||
* setTimeout(() => { // Simulating some various async stuff
|
||||
* fs.open('non-existent file', 'r', (er, fd) => {
|
||||
* if (er) throw er;
|
||||
* // proceed...
|
||||
* });
|
||||
* }, 100);
|
||||
* });
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* In this example, the `d.on('error')` handler will be triggered, rather
|
||||
* than crashing the program.
|
||||
*/
|
||||
run<T>(fn: (...args: any[]) => T, ...args: any[]): T;
|
||||
/**
|
||||
* Explicitly adds an emitter to the domain. If any event handlers called by
|
||||
* the emitter throw an error, or if the emitter emits an `'error'` event, it
|
||||
* will be routed to the domain's `'error'` event, just like with implicit
|
||||
* binding.
|
||||
*
|
||||
* If the `EventEmitter` was already bound to a domain, it is removed from that
|
||||
* one, and bound to this one instead.
|
||||
* @param emitter emitter to be added to the domain
|
||||
*/
|
||||
add(emitter: EventEmitter): void;
|
||||
/**
|
||||
* The opposite of {@link add}. Removes domain handling from the
|
||||
* specified emitter.
|
||||
* @param emitter emitter to be removed from the domain
|
||||
*/
|
||||
remove(emitter: EventEmitter): void;
|
||||
/**
|
||||
* The returned function will be a wrapper around the supplied callback
|
||||
* function. When the returned function is called, any errors that are
|
||||
* thrown will be routed to the domain's `'error'` event.
|
||||
*
|
||||
* ```js
|
||||
* const d = domain.create();
|
||||
*
|
||||
* function readSomeFile(filename, cb) {
|
||||
* fs.readFile(filename, 'utf8', d.bind((er, data) => {
|
||||
* // If this throws, it will also be passed to the domain.
|
||||
* return cb(er, data ? JSON.parse(data) : null);
|
||||
* }));
|
||||
* }
|
||||
*
|
||||
* d.on('error', (er) => {
|
||||
* // An error occurred somewhere. If we throw it now, it will crash the program
|
||||
* // with the normal line number and stack message.
|
||||
* });
|
||||
* ```
|
||||
* @param callback The callback function
|
||||
* @return The bound function
|
||||
*/
|
||||
bind<T extends Function>(callback: T): T;
|
||||
/**
|
||||
* This method is almost identical to {@link bind}. However, in
|
||||
* addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function.
|
||||
*
|
||||
* In this way, the common `if (err) return callback(err);` pattern can be replaced
|
||||
* with a single error handler in a single place.
|
||||
*
|
||||
* ```js
|
||||
* const d = domain.create();
|
||||
*
|
||||
* function readSomeFile(filename, cb) {
|
||||
* fs.readFile(filename, 'utf8', d.intercept((data) => {
|
||||
* // Note, the first argument is never passed to the
|
||||
* // callback since it is assumed to be the 'Error' argument
|
||||
* // and thus intercepted by the domain.
|
||||
*
|
||||
* // If this throws, it will also be passed to the domain
|
||||
* // so the error-handling logic can be moved to the 'error'
|
||||
* // event on the domain instead of being repeated throughout
|
||||
* // the program.
|
||||
* return cb(null, JSON.parse(data));
|
||||
* }));
|
||||
* }
|
||||
*
|
||||
* d.on('error', (er) => {
|
||||
* // An error occurred somewhere. If we throw it now, it will crash the program
|
||||
* // with the normal line number and stack message.
|
||||
* });
|
||||
* ```
|
||||
* @param callback The callback function
|
||||
* @return The intercepted function
|
||||
*/
|
||||
intercept<T extends Function>(callback: T): T;
|
||||
}
|
||||
function create(): Domain;
|
||||
}
|
||||
declare module "domain" {
|
||||
export * from "node:domain";
|
||||
}
|
||||
@@ -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: "ký tự", verb: "có" },
|
||||
file: { unit: "byte", verb: "có" },
|
||||
array: { unit: "phần tử", verb: "có" },
|
||||
set: { unit: "phần tử", verb: "có" },
|
||||
};
|
||||
function getSizing(origin) {
|
||||
return Sizable[origin] ?? null;
|
||||
}
|
||||
const FormatDictionary = {
|
||||
regex: "đầu vào",
|
||||
email: "địa chỉ 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: "ngày giờ ISO",
|
||||
date: "ngày ISO",
|
||||
time: "giờ ISO",
|
||||
duration: "khoảng thời gian ISO",
|
||||
ipv4: "địa chỉ IPv4",
|
||||
ipv6: "địa chỉ IPv6",
|
||||
cidrv4: "dải IPv4",
|
||||
cidrv6: "dải IPv6",
|
||||
base64: "chuỗi mã hóa base64",
|
||||
base64url: "chuỗi mã hóa base64url",
|
||||
json_string: "chuỗi JSON",
|
||||
e164: "số E.164",
|
||||
jwt: "JWT",
|
||||
template_literal: "đầu vào",
|
||||
};
|
||||
const TypeDictionary = {
|
||||
nan: "NaN",
|
||||
number: "số",
|
||||
array: "mảng",
|
||||
};
|
||||
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 `Đầu vào không hợp lệ: mong đợi instanceof ${issue.expected}, nhận được ${received}`;
|
||||
}
|
||||
return `Đầu vào không hợp lệ: mong đợi ${expected}, nhận được ${received}`;
|
||||
}
|
||||
case "invalid_value":
|
||||
if (issue.values.length === 1)
|
||||
return `Đầu vào không hợp lệ: mong đợi ${util.stringifyPrimitive(issue.values[0])}`;
|
||||
return `Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${util.joinValues(issue.values, "|")}`;
|
||||
case "too_big": {
|
||||
const adj = issue.inclusive ? "<=" : "<";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing)
|
||||
return `Quá lớn: mong đợi ${issue.origin ?? "giá trị"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "phần tử"}`;
|
||||
return `Quá lớn: mong đợi ${issue.origin ?? "giá trị"} ${adj}${issue.maximum.toString()}`;
|
||||
}
|
||||
case "too_small": {
|
||||
const adj = issue.inclusive ? ">=" : ">";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing) {
|
||||
return `Quá nhỏ: mong đợi ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;
|
||||
}
|
||||
return `Quá nhỏ: mong đợi ${issue.origin} ${adj}${issue.minimum.toString()}`;
|
||||
}
|
||||
case "invalid_format": {
|
||||
const _issue = issue;
|
||||
if (_issue.format === "starts_with")
|
||||
return `Chuỗi không hợp lệ: phải bắt đầu bằng "${_issue.prefix}"`;
|
||||
if (_issue.format === "ends_with")
|
||||
return `Chuỗi không hợp lệ: phải kết thúc bằng "${_issue.suffix}"`;
|
||||
if (_issue.format === "includes")
|
||||
return `Chuỗi không hợp lệ: phải bao gồm "${_issue.includes}"`;
|
||||
if (_issue.format === "regex")
|
||||
return `Chuỗi không hợp lệ: phải khớp với mẫu ${_issue.pattern}`;
|
||||
return `${FormatDictionary[_issue.format] ?? issue.format} không hợp lệ`;
|
||||
}
|
||||
case "not_multiple_of":
|
||||
return `Số không hợp lệ: phải là bội số của ${issue.divisor}`;
|
||||
case "unrecognized_keys":
|
||||
return `Khóa không được nhận dạng: ${util.joinValues(issue.keys, ", ")}`;
|
||||
case "invalid_key":
|
||||
return `Khóa không hợp lệ trong ${issue.origin}`;
|
||||
case "invalid_union":
|
||||
return "Đầu vào không hợp lệ";
|
||||
case "invalid_element":
|
||||
return `Giá trị không hợp lệ trong ${issue.origin}`;
|
||||
default:
|
||||
return `Đầu vào không hợp lệ`;
|
||||
}
|
||||
};
|
||||
};
|
||||
function default_1() {
|
||||
return {
|
||||
localeError: error(),
|
||||
};
|
||||
}
|
||||
module.exports = exports.default;
|
||||
@@ -0,0 +1,21 @@
|
||||
'use strict'
|
||||
|
||||
const { register } = require('../..')
|
||||
const assert = require('assert')
|
||||
|
||||
function setup () {
|
||||
const obj = { foo: 'bar' }
|
||||
register(obj, shutdown)
|
||||
}
|
||||
|
||||
let shutdownCalled = false
|
||||
function shutdown (obj) {
|
||||
shutdownCalled = true
|
||||
assert.strictEqual(obj.foo, 'bar')
|
||||
}
|
||||
|
||||
setup()
|
||||
|
||||
process.on('exit', function () {
|
||||
assert.strictEqual(shutdownCalled, true)
|
||||
})
|
||||
@@ -0,0 +1,376 @@
|
||||
/**
|
||||
* Hex, bytes and number utilities.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import {
|
||||
abytes as abytes_,
|
||||
bytesToHex as bytesToHex_,
|
||||
concatBytes as concatBytes_,
|
||||
hexToBytes as hexToBytes_,
|
||||
isBytes as isBytes_,
|
||||
} from '@noble/hashes/utils.js';
|
||||
export {
|
||||
abytes,
|
||||
anumber,
|
||||
bytesToHex,
|
||||
bytesToUtf8,
|
||||
concatBytes,
|
||||
hexToBytes,
|
||||
isBytes,
|
||||
randomBytes,
|
||||
utf8ToBytes,
|
||||
} from '@noble/hashes/utils.js';
|
||||
const _0n = /* @__PURE__ */ BigInt(0);
|
||||
const _1n = /* @__PURE__ */ BigInt(1);
|
||||
export type Hex = Uint8Array | string; // hex strings are accepted for simplicity
|
||||
export type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve
|
||||
export type CHash = {
|
||||
(message: Uint8Array | string): Uint8Array;
|
||||
blockLen: number;
|
||||
outputLen: number;
|
||||
create(opts?: { dkLen?: number }): any; // For shake
|
||||
};
|
||||
export type FHash = (message: Uint8Array | string) => Uint8Array;
|
||||
|
||||
export function abool(title: string, value: boolean): void {
|
||||
if (typeof value !== 'boolean') throw new Error(title + ' boolean expected, got ' + value);
|
||||
}
|
||||
|
||||
// tmp name until v2
|
||||
export function _abool2(value: boolean, title: string = ''): boolean {
|
||||
if (typeof value !== 'boolean') {
|
||||
const prefix = title && `"${title}"`;
|
||||
throw new Error(prefix + 'expected boolean, got type=' + typeof value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// tmp name until v2
|
||||
/** Asserts something is Uint8Array. */
|
||||
export function _abytes2(value: Uint8Array, length?: number, title: string = ''): Uint8Array {
|
||||
const bytes = isBytes_(value);
|
||||
const len = value?.length;
|
||||
const needsLen = length !== undefined;
|
||||
if (!bytes || (needsLen && len !== length)) {
|
||||
const prefix = title && `"${title}" `;
|
||||
const ofLen = needsLen ? ` of length ${length}` : '';
|
||||
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
||||
throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// Used in weierstrass, der
|
||||
export function numberToHexUnpadded(num: number | bigint): string {
|
||||
const hex = num.toString(16);
|
||||
return hex.length & 1 ? '0' + hex : hex;
|
||||
}
|
||||
|
||||
export function hexToNumber(hex: string): bigint {
|
||||
if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);
|
||||
return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian
|
||||
}
|
||||
|
||||
// BE: Big Endian, LE: Little Endian
|
||||
export function bytesToNumberBE(bytes: Uint8Array): bigint {
|
||||
return hexToNumber(bytesToHex_(bytes));
|
||||
}
|
||||
export function bytesToNumberLE(bytes: Uint8Array): bigint {
|
||||
abytes_(bytes);
|
||||
return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));
|
||||
}
|
||||
|
||||
export function numberToBytesBE(n: number | bigint, len: number): Uint8Array {
|
||||
return hexToBytes_(n.toString(16).padStart(len * 2, '0'));
|
||||
}
|
||||
export function numberToBytesLE(n: number | bigint, len: number): Uint8Array {
|
||||
return numberToBytesBE(n, len).reverse();
|
||||
}
|
||||
// Unpadded, rarely used
|
||||
export function numberToVarBytesBE(n: number | bigint): Uint8Array {
|
||||
return hexToBytes_(numberToHexUnpadded(n));
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes hex string or Uint8Array, converts to Uint8Array.
|
||||
* Validates output length.
|
||||
* Will throw error for other types.
|
||||
* @param title descriptive title for an error e.g. 'secret key'
|
||||
* @param hex hex string or Uint8Array
|
||||
* @param expectedLength optional, will compare to result array's length
|
||||
* @returns
|
||||
*/
|
||||
export function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {
|
||||
let res: Uint8Array;
|
||||
if (typeof hex === 'string') {
|
||||
try {
|
||||
res = hexToBytes_(hex);
|
||||
} catch (e) {
|
||||
throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
|
||||
}
|
||||
} else if (isBytes_(hex)) {
|
||||
// Uint8Array.from() instead of hash.slice() because node.js Buffer
|
||||
// is instance of Uint8Array, and its slice() creates **mutable** copy
|
||||
res = Uint8Array.from(hex);
|
||||
} else {
|
||||
throw new Error(title + ' must be hex string or Uint8Array');
|
||||
}
|
||||
const len = res.length;
|
||||
if (typeof expectedLength === 'number' && len !== expectedLength)
|
||||
throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
|
||||
return res;
|
||||
}
|
||||
|
||||
// Compares 2 u8a-s in kinda constant time
|
||||
export function equalBytes(a: Uint8Array, b: Uint8Array): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
let diff = 0;
|
||||
for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
|
||||
return diff === 0;
|
||||
}
|
||||
/**
|
||||
* Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
|
||||
* and Buffer#slice creates mutable copy. Never use Buffers!
|
||||
*/
|
||||
export function copyBytes(bytes: Uint8Array): Uint8Array {
|
||||
return Uint8Array.from(bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
|
||||
* Should be safe to use for things expected to be ASCII.
|
||||
* Returns exact same result as utf8ToBytes for ASCII or throws.
|
||||
*/
|
||||
export function asciiToBytes(ascii: string): Uint8Array {
|
||||
return Uint8Array.from(ascii, (c, i) => {
|
||||
const charCode = c.charCodeAt(0);
|
||||
if (c.length !== 1 || charCode > 127) {
|
||||
throw new Error(
|
||||
`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`
|
||||
);
|
||||
}
|
||||
return charCode;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
|
||||
*/
|
||||
// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;
|
||||
/**
|
||||
* Converts bytes to string using UTF8 encoding.
|
||||
* @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
|
||||
*/
|
||||
// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;
|
||||
|
||||
// Is positive bigint
|
||||
const isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;
|
||||
|
||||
export function inRange(n: bigint, min: bigint, max: bigint): boolean {
|
||||
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts min <= n < max. NOTE: It's < max and not <= max.
|
||||
* @example
|
||||
* aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
|
||||
*/
|
||||
export function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {
|
||||
// Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
|
||||
// consider P=256n, min=0n, max=P
|
||||
// - a for min=0 would require -1: `inRange('x', x, -1n, P)`
|
||||
// - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
|
||||
// - our way is the cleanest: `inRange('x', x, 0n, P)
|
||||
if (!inRange(n, min, max))
|
||||
throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
|
||||
}
|
||||
|
||||
// Bit operations
|
||||
|
||||
/**
|
||||
* Calculates amount of bits in a bigint.
|
||||
* Same as `n.toString(2).length`
|
||||
* TODO: merge with nLength in modular
|
||||
*/
|
||||
export function bitLen(n: bigint): number {
|
||||
let len;
|
||||
for (len = 0; n > _0n; n >>= _1n, len += 1);
|
||||
return len;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets single bit at position.
|
||||
* NOTE: first bit position is 0 (same as arrays)
|
||||
* Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
|
||||
*/
|
||||
export function bitGet(n: bigint, pos: number): bigint {
|
||||
return (n >> BigInt(pos)) & _1n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets single bit at position.
|
||||
*/
|
||||
export function bitSet(n: bigint, pos: number, value: boolean): bigint {
|
||||
return n | ((value ? _1n : _0n) << BigInt(pos));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate mask for N bits. Not using ** operator with bigints because of old engines.
|
||||
* Same as BigInt(`0b${Array(i).fill('1').join('')}`)
|
||||
*/
|
||||
export const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;
|
||||
|
||||
// DRBG
|
||||
|
||||
type Pred<T> = (v: Uint8Array) => T | undefined;
|
||||
/**
|
||||
* Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
|
||||
* @returns function that will call DRBG until 2nd arg returns something meaningful
|
||||
* @example
|
||||
* const drbg = createHmacDRBG<Key>(32, 32, hmac);
|
||||
* drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
|
||||
*/
|
||||
export function createHmacDrbg<T>(
|
||||
hashLen: number,
|
||||
qByteLen: number,
|
||||
hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array
|
||||
): (seed: Uint8Array, predicate: Pred<T>) => T {
|
||||
if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');
|
||||
if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');
|
||||
if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');
|
||||
// Step B, Step C: set hashLen to 8*ceil(hlen/8)
|
||||
const u8n = (len: number) => new Uint8Array(len); // creates Uint8Array
|
||||
const u8of = (byte: number) => Uint8Array.of(byte); // another shortcut
|
||||
let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
|
||||
let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
|
||||
let i = 0; // Iterations counter, will throw when over 1000
|
||||
const reset = () => {
|
||||
v.fill(1);
|
||||
k.fill(0);
|
||||
i = 0;
|
||||
};
|
||||
const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
|
||||
const reseed = (seed = u8n(0)) => {
|
||||
// HMAC-DRBG reseed() function. Steps D-G
|
||||
k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
|
||||
v = h(); // v = hmac(k || v)
|
||||
if (seed.length === 0) return;
|
||||
k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
|
||||
v = h(); // v = hmac(k || v)
|
||||
};
|
||||
const gen = () => {
|
||||
// HMAC-DRBG generate() function
|
||||
if (i++ >= 1000) throw new Error('drbg: tried 1000 values');
|
||||
let len = 0;
|
||||
const out: Uint8Array[] = [];
|
||||
while (len < qByteLen) {
|
||||
v = h();
|
||||
const sl = v.slice();
|
||||
out.push(sl);
|
||||
len += v.length;
|
||||
}
|
||||
return concatBytes_(...out);
|
||||
};
|
||||
const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {
|
||||
reset();
|
||||
reseed(seed); // Steps D-G
|
||||
let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]
|
||||
while (!(res = pred(gen()))) reseed();
|
||||
reset();
|
||||
return res;
|
||||
};
|
||||
return genUntil;
|
||||
}
|
||||
|
||||
// Validating curves and fields
|
||||
|
||||
const validatorFns = {
|
||||
bigint: (val: any): boolean => typeof val === 'bigint',
|
||||
function: (val: any): boolean => typeof val === 'function',
|
||||
boolean: (val: any): boolean => typeof val === 'boolean',
|
||||
string: (val: any): boolean => typeof val === 'string',
|
||||
stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes_(val),
|
||||
isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),
|
||||
array: (val: any): boolean => Array.isArray(val),
|
||||
field: (val: any, object: any): any => (object as any).Fp.isValid(val),
|
||||
hash: (val: any): boolean => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
|
||||
} as const;
|
||||
type Validator = keyof typeof validatorFns;
|
||||
type ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };
|
||||
// type Record<K extends string | number | symbol, T> = { [P in K]: T; }
|
||||
|
||||
export function validateObject<T extends Record<string, any>>(
|
||||
object: T,
|
||||
validators: ValMap<T>,
|
||||
optValidators: ValMap<T> = {}
|
||||
): T {
|
||||
const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {
|
||||
const checkVal = validatorFns[type];
|
||||
if (typeof checkVal !== 'function') throw new Error('invalid validator function');
|
||||
|
||||
const val = object[fieldName as keyof typeof object];
|
||||
if (isOptional && val === undefined) return;
|
||||
if (!checkVal(val, object)) {
|
||||
throw new Error(
|
||||
'param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val
|
||||
);
|
||||
}
|
||||
};
|
||||
for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);
|
||||
for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);
|
||||
return object;
|
||||
}
|
||||
// validate type tests
|
||||
// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
|
||||
// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
|
||||
// // Should fail type-check
|
||||
// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
|
||||
// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
|
||||
// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
|
||||
// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
|
||||
|
||||
export function isHash(val: CHash): boolean {
|
||||
return typeof val === 'function' && Number.isSafeInteger(val.outputLen);
|
||||
}
|
||||
export function _validateObject(
|
||||
object: Record<string, any>,
|
||||
fields: Record<string, string>,
|
||||
optFields: Record<string, string> = {}
|
||||
): void {
|
||||
if (!object || typeof object !== 'object') throw new Error('expected valid options object');
|
||||
type Item = keyof typeof object;
|
||||
function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {
|
||||
const val = object[fieldName];
|
||||
if (isOpt && val === undefined) return;
|
||||
const current = typeof val;
|
||||
if (current !== expectedType || val === null)
|
||||
throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
|
||||
}
|
||||
Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
|
||||
Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
|
||||
}
|
||||
|
||||
/**
|
||||
* throws not implemented error
|
||||
*/
|
||||
export const notImplemented = (): never => {
|
||||
throw new Error('not implemented');
|
||||
};
|
||||
|
||||
/**
|
||||
* Memoizes (caches) computation result.
|
||||
* Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
|
||||
*/
|
||||
export function memoized<T extends object, R, O extends any[]>(
|
||||
fn: (arg: T, ...args: O) => R
|
||||
): (arg: T, ...args: O) => R {
|
||||
const map = new WeakMap<T, R>();
|
||||
return (arg: T, ...args: O): R => {
|
||||
const val = map.get(arg);
|
||||
if (val !== undefined) return val;
|
||||
const computed = fn(arg, ...args);
|
||||
map.set(arg, computed);
|
||||
return computed;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
# xtend
|
||||
|
||||
[![browser support][3]][4]
|
||||
|
||||
[](http://github.com/badges/stability-badges)
|
||||
|
||||
Extend like a boss
|
||||
|
||||
xtend is a basic utility library which allows you to extend an object by appending all of the properties from each object in a list. When there are identical properties, the right-most property takes precedence.
|
||||
|
||||
## Examples
|
||||
|
||||
```js
|
||||
var extend = require("xtend")
|
||||
|
||||
// extend returns a new object. Does not mutate arguments
|
||||
var combination = extend({
|
||||
a: "a",
|
||||
b: "c"
|
||||
}, {
|
||||
b: "b"
|
||||
})
|
||||
// { a: "a", b: "b" }
|
||||
```
|
||||
|
||||
## Stability status: Locked
|
||||
|
||||
## MIT Licensed
|
||||
|
||||
|
||||
[3]: http://ci.testling.com/Raynos/xtend.png
|
||||
[4]: http://ci.testling.com/Raynos/xtend
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,85 @@
|
||||
'use strict'
|
||||
|
||||
const bench = require('fastbench')
|
||||
const SonicBoom = require('sonic-boom')
|
||||
const ThreadStream = require('.')
|
||||
const Console = require('console').Console
|
||||
const fs = require('fs')
|
||||
const { join } = require('path')
|
||||
|
||||
const core = fs.createWriteStream('/dev/null')
|
||||
const fd = fs.openSync('/dev/null', 'w')
|
||||
const sonic = new SonicBoom({ fd })
|
||||
const sonicSync = new SonicBoom({ fd, sync: true })
|
||||
const out = fs.createWriteStream('/dev/null')
|
||||
const dummyConsole = new Console(out)
|
||||
const threadStreamSync = new ThreadStream({
|
||||
filename: join(__dirname, 'test', 'to-file.js'),
|
||||
workerData: { dest: '/dev/null' },
|
||||
bufferSize: 4 * 1024 * 1024,
|
||||
sync: true
|
||||
})
|
||||
const threadStreamAsync = new ThreadStream({
|
||||
filename: join(__dirname, 'test', 'to-file.js'),
|
||||
workerData: { dest: '/dev/null' },
|
||||
bufferSize: 4 * 1024 * 1024,
|
||||
sync: false
|
||||
})
|
||||
|
||||
const MAX = 10000
|
||||
|
||||
let str = ''
|
||||
|
||||
for (let i = 0; i < 100; i++) {
|
||||
str += 'hello'
|
||||
}
|
||||
|
||||
setTimeout(doBench, 100)
|
||||
|
||||
const run = bench([
|
||||
function benchThreadStreamSync (cb) {
|
||||
for (let i = 0; i < MAX; i++) {
|
||||
threadStreamSync.write(str)
|
||||
}
|
||||
setImmediate(cb)
|
||||
},
|
||||
function benchThreadStreamAsync (cb) {
|
||||
threadStreamAsync.once('drain', cb)
|
||||
for (let i = 0; i < MAX; i++) {
|
||||
threadStreamAsync.write(str)
|
||||
}
|
||||
},
|
||||
function benchSonic (cb) {
|
||||
sonic.once('drain', cb)
|
||||
for (let i = 0; i < MAX; i++) {
|
||||
sonic.write(str)
|
||||
}
|
||||
},
|
||||
function benchSonicSync (cb) {
|
||||
sonicSync.once('drain', cb)
|
||||
for (let i = 0; i < MAX; i++) {
|
||||
sonicSync.write(str)
|
||||
}
|
||||
},
|
||||
function benchCore (cb) {
|
||||
core.once('drain', cb)
|
||||
for (let i = 0; i < MAX; i++) {
|
||||
core.write(str)
|
||||
}
|
||||
},
|
||||
function benchConsole (cb) {
|
||||
for (let i = 0; i < MAX; i++) {
|
||||
dummyConsole.log(str)
|
||||
}
|
||||
setImmediate(cb)
|
||||
}
|
||||
], 1000)
|
||||
|
||||
function doBench () {
|
||||
run(function () {
|
||||
run(function () {
|
||||
// TODO figure out why it does not shut down
|
||||
process.exit(0)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
{
|
||||
"name": "eslint-visitor-keys",
|
||||
"version": "5.0.1",
|
||||
"description": "Constants and utilities about visitor keys to traverse AST.",
|
||||
"type": "module",
|
||||
"main": "dist/eslint-visitor-keys.cjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": [
|
||||
{
|
||||
"import": "./lib/index.js",
|
||||
"require": "./dist/eslint-visitor-keys.cjs"
|
||||
},
|
||||
"./dist/eslint-visitor-keys.cjs"
|
||||
],
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"dist/index.d.ts",
|
||||
"dist/visitor-keys.d.ts",
|
||||
"dist/eslint-visitor-keys.cjs",
|
||||
"dist/eslint-visitor-keys.d.cts",
|
||||
"lib"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^20.19.0 || ^22.13.0 || >=24"
|
||||
},
|
||||
"devDependencies": {
|
||||
"rollup-plugin-dts": "^6.2.3",
|
||||
"tsd": "^0.33.0"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "npm run build:cjs && npm run build:types",
|
||||
"build:cjs": "rollup -c",
|
||||
"build:debug": "npm run build:cjs -- -m && npm run build:types",
|
||||
"build:types": "tsc -v && tsc",
|
||||
"test": "mocha \"tests/**/*.test.cjs\" && mocha \"tests/**/*.test.js\" && npm run test:types",
|
||||
"test:coverage": "c8 npm test",
|
||||
"test:types": "tsd"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/eslint/js.git",
|
||||
"directory": "packages/eslint-visitor-keys"
|
||||
},
|
||||
"funding": "https://opencollective.com/eslint",
|
||||
"keywords": [
|
||||
"eslint"
|
||||
],
|
||||
"author": "Toru Nagashima (https://github.com/mysticatea)",
|
||||
"license": "Apache-2.0",
|
||||
"bugs": {
|
||||
"url": "https://github.com/eslint/js/issues"
|
||||
},
|
||||
"homepage": "https://github.com/eslint/js/blob/main/packages/eslint-visitor-keys/README.md",
|
||||
"sideEffects": false
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import pino from '../../..'
|
||||
|
||||
const transport = pino.transport({
|
||||
target: 'pino/file'
|
||||
})
|
||||
const logger = pino(transport)
|
||||
|
||||
logger.info('Hello')
|
||||
|
||||
process.exit(0)
|
||||
@@ -0,0 +1,69 @@
|
||||
import { a as makeBuiltinPluginCallable, n as BuiltinPlugin, t as normalizedStringOrRegex } from "./normalize-string-or-regex-BxRYnPRv.mjs";
|
||||
//#region src/builtin-plugin/constructors.ts
|
||||
function viteModulePreloadPolyfillPlugin(config) {
|
||||
return new BuiltinPlugin("builtin:vite-module-preload-polyfill", config);
|
||||
}
|
||||
function viteDynamicImportVarsPlugin(config) {
|
||||
if (config) {
|
||||
config.include = normalizedStringOrRegex(config.include);
|
||||
config.exclude = normalizedStringOrRegex(config.exclude);
|
||||
}
|
||||
return new BuiltinPlugin("builtin:vite-dynamic-import-vars", config);
|
||||
}
|
||||
function viteImportGlobPlugin(config) {
|
||||
return new BuiltinPlugin("builtin:vite-import-glob", config);
|
||||
}
|
||||
function viteReporterPlugin(config) {
|
||||
return new BuiltinPlugin("builtin:vite-reporter", config);
|
||||
}
|
||||
function viteLoadFallbackPlugin() {
|
||||
return new BuiltinPlugin("builtin:vite-load-fallback");
|
||||
}
|
||||
function viteJsonPlugin(config) {
|
||||
const builtinPlugin = new BuiltinPlugin("builtin:vite-json", config);
|
||||
return makeBuiltinPluginCallable(builtinPlugin);
|
||||
}
|
||||
function viteBuildImportAnalysisPlugin(config) {
|
||||
return new BuiltinPlugin("builtin:vite-build-import-analysis", config);
|
||||
}
|
||||
function viteResolvePlugin(config) {
|
||||
const builtinPlugin = new BuiltinPlugin("builtin:vite-resolve", {
|
||||
...config,
|
||||
yarnPnp: typeof process === "object" && !!process.versions?.pnp
|
||||
});
|
||||
return makeBuiltinPluginCallable(builtinPlugin);
|
||||
}
|
||||
function isolatedDeclarationPlugin(config) {
|
||||
return new BuiltinPlugin("builtin:isolated-declaration", config);
|
||||
}
|
||||
function viteWebWorkerPostPlugin() {
|
||||
return new BuiltinPlugin("builtin:vite-web-worker-post");
|
||||
}
|
||||
/**
|
||||
* A plugin that converts CommonJS require() calls for external dependencies into ESM import statements.
|
||||
*
|
||||
* @see https://rolldown.rs/builtin-plugins/esm-external-require
|
||||
* @category Builtin Plugins
|
||||
*/
|
||||
function esmExternalRequirePlugin(config) {
|
||||
const plugin = new BuiltinPlugin("builtin:esm-external-require", config);
|
||||
plugin.enforce = "pre";
|
||||
return plugin;
|
||||
}
|
||||
/**
|
||||
* This plugin should not be used for Rolldown.
|
||||
*/
|
||||
function oxcRuntimePlugin() {
|
||||
const builtinPlugin = new BuiltinPlugin("builtin:oxc-runtime");
|
||||
return makeBuiltinPluginCallable(builtinPlugin);
|
||||
}
|
||||
function viteReactRefreshWrapperPlugin(config) {
|
||||
if (config) {
|
||||
config.include = normalizedStringOrRegex(config.include);
|
||||
config.exclude = normalizedStringOrRegex(config.exclude);
|
||||
}
|
||||
const builtinPlugin = new BuiltinPlugin("builtin:vite-react-refresh-wrapper", config);
|
||||
return makeBuiltinPluginCallable(builtinPlugin);
|
||||
}
|
||||
//#endregion
|
||||
export { viteDynamicImportVarsPlugin as a, viteLoadFallbackPlugin as c, viteReporterPlugin as d, viteResolvePlugin as f, viteBuildImportAnalysisPlugin as i, viteModulePreloadPolyfillPlugin as l, isolatedDeclarationPlugin as n, viteImportGlobPlugin as o, viteWebWorkerPostPlugin as p, oxcRuntimePlugin as r, viteJsonPlugin as s, esmExternalRequirePlugin as t, viteReactRefreshWrapperPlugin as u };
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Represents default log level values
|
||||
*
|
||||
* @enum {number}
|
||||
*/
|
||||
const DEFAULT_LEVELS = {
|
||||
trace: 10,
|
||||
debug: 20,
|
||||
info: 30,
|
||||
warn: 40,
|
||||
error: 50,
|
||||
fatal: 60
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents sort order direction: `ascending` or `descending`
|
||||
*
|
||||
* @enum {string}
|
||||
*/
|
||||
const SORTING_ORDER = {
|
||||
ASC: 'ASC',
|
||||
DESC: 'DESC'
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_LEVELS,
|
||||
SORTING_ORDER
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
'use strict'
|
||||
|
||||
let Document = require('./document')
|
||||
let LazyResult = require('./lazy-result')
|
||||
let NoWorkResult = require('./no-work-result')
|
||||
let Root = require('./root')
|
||||
|
||||
class Processor {
|
||||
constructor(plugins = []) {
|
||||
this.version = '8.5.26'
|
||||
this.plugins = this.normalize(plugins)
|
||||
}
|
||||
|
||||
normalize(plugins) {
|
||||
let normalized = []
|
||||
for (let i of plugins) {
|
||||
if (i.postcss === true) {
|
||||
i = i()
|
||||
} else if (i.postcss) {
|
||||
i = i.postcss
|
||||
}
|
||||
|
||||
if (typeof i === 'object' && Array.isArray(i.plugins)) {
|
||||
normalized = normalized.concat(i.plugins)
|
||||
} else if (typeof i === 'object' && i.postcssPlugin) {
|
||||
normalized.push(i)
|
||||
} else if (typeof i === 'function') {
|
||||
normalized.push(i)
|
||||
} else if (typeof i === 'object' && (i.parse || i.stringify)) {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
throw new Error(
|
||||
'PostCSS syntaxes cannot be used as plugins. Instead, please use ' +
|
||||
'one of the syntax/parser/stringifier options as outlined ' +
|
||||
'in your PostCSS runner documentation.'
|
||||
)
|
||||
}
|
||||
} else {
|
||||
throw new Error(i + ' is not a PostCSS plugin')
|
||||
}
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
process(css, opts = {}) {
|
||||
if (
|
||||
!this.plugins.length &&
|
||||
!opts.parser &&
|
||||
!opts.stringifier &&
|
||||
!opts.syntax
|
||||
) {
|
||||
return new NoWorkResult(this, css, opts)
|
||||
} else {
|
||||
return new LazyResult(this, css, opts)
|
||||
}
|
||||
}
|
||||
|
||||
use(plugin) {
|
||||
this.plugins = this.plugins.concat(this.normalize([plugin]))
|
||||
return this
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Processor
|
||||
Processor.default = Processor
|
||||
|
||||
Root.registerProcessor(Processor)
|
||||
Document.registerProcessor(Processor)
|
||||
@@ -0,0 +1,9 @@
|
||||
'use strict'
|
||||
|
||||
const Range = require('../classes/range')
|
||||
const intersects = (r1, r2, options) => {
|
||||
r1 = new Range(r1, options)
|
||||
r2 = new Range(r2, options)
|
||||
return r1.intersects(r2, options)
|
||||
}
|
||||
module.exports = intersects
|
||||
@@ -0,0 +1,11 @@
|
||||
Copyright 2019 Eugene Lazutkin
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -0,0 +1,17 @@
|
||||
'use strict'
|
||||
|
||||
const test = require('node:test')
|
||||
const assert = require('node:assert')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
|
||||
const pino = require('../..')()
|
||||
|
||||
test('should be the same as package.json', () => {
|
||||
const json = JSON.parse(
|
||||
fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'))
|
||||
.toString('utf8')
|
||||
)
|
||||
|
||||
assert.equal(pino.version, json.version)
|
||||
})
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user