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,601 @@
"use strict";
// import { $ZodType } from "./schemas.js";
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.$ZodCheckOverwrite = exports.$ZodCheckMimeType = exports.$ZodCheckProperty = exports.$ZodCheckEndsWith = exports.$ZodCheckStartsWith = exports.$ZodCheckIncludes = exports.$ZodCheckUpperCase = exports.$ZodCheckLowerCase = exports.$ZodCheckRegex = exports.$ZodCheckStringFormat = exports.$ZodCheckLengthEquals = exports.$ZodCheckMinLength = exports.$ZodCheckMaxLength = exports.$ZodCheckSizeEquals = exports.$ZodCheckMinSize = exports.$ZodCheckMaxSize = exports.$ZodCheckBigIntFormat = exports.$ZodCheckNumberFormat = exports.$ZodCheckMultipleOf = exports.$ZodCheckGreaterThan = exports.$ZodCheckLessThan = exports.$ZodCheck = void 0;
const core = __importStar(require("./core.cjs"));
const regexes = __importStar(require("./regexes.cjs"));
const util = __importStar(require("./util.cjs"));
exports.$ZodCheck = core.$constructor("$ZodCheck", (inst, def) => {
var _a;
inst._zod ?? (inst._zod = {});
inst._zod.def = def;
(_a = inst._zod).onattach ?? (_a.onattach = []);
});
const numericOriginMap = {
number: "number",
bigint: "bigint",
object: "date",
};
exports.$ZodCheckLessThan = core.$constructor("$ZodCheckLessThan", (inst, def) => {
exports.$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
if (def.value < curr) {
if (def.inclusive)
bag.maximum = def.value;
else
bag.exclusiveMaximum = def.value;
}
});
inst._zod.check = (payload) => {
if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
return;
}
payload.issues.push({
origin,
code: "too_big",
maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
input: payload.value,
inclusive: def.inclusive,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckGreaterThan = core.$constructor("$ZodCheckGreaterThan", (inst, def) => {
exports.$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
if (def.value > curr) {
if (def.inclusive)
bag.minimum = def.value;
else
bag.exclusiveMinimum = def.value;
}
});
inst._zod.check = (payload) => {
if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
return;
}
payload.issues.push({
origin,
code: "too_small",
minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
input: payload.value,
inclusive: def.inclusive,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckMultipleOf =
/*@__PURE__*/ core.$constructor("$ZodCheckMultipleOf", (inst, def) => {
exports.$ZodCheck.init(inst, def);
inst._zod.onattach.push((inst) => {
var _a;
(_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
});
inst._zod.check = (payload) => {
if (typeof payload.value !== typeof def.value)
throw new Error("Cannot mix number and bigint in multiple_of check.");
const isMultiple = typeof payload.value === "bigint"
? payload.value % def.value === BigInt(0)
: util.floatSafeRemainder(payload.value, def.value) === 0;
if (isMultiple)
return;
payload.issues.push({
origin: typeof payload.value,
code: "not_multiple_of",
divisor: def.value,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckNumberFormat = core.$constructor("$ZodCheckNumberFormat", (inst, def) => {
exports.$ZodCheck.init(inst, def); // no format checks
def.format = def.format || "float64";
const isInt = def.format?.includes("int");
const origin = isInt ? "int" : "number";
const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.format = def.format;
bag.minimum = minimum;
bag.maximum = maximum;
if (isInt)
bag.pattern = regexes.integer;
});
inst._zod.check = (payload) => {
const input = payload.value;
if (isInt) {
if (!Number.isInteger(input)) {
// invalid_format issue
// payload.issues.push({
// expected: def.format,
// format: def.format,
// code: "invalid_format",
// input,
// inst,
// });
// invalid_type issue
payload.issues.push({
expected: origin,
format: def.format,
code: "invalid_type",
continue: false,
input,
inst,
});
return;
// not_multiple_of issue
// payload.issues.push({
// code: "not_multiple_of",
// origin: "number",
// input,
// inst,
// divisor: 1,
// });
}
if (!Number.isSafeInteger(input)) {
if (input > 0) {
// too_big
payload.issues.push({
input,
code: "too_big",
maximum: Number.MAX_SAFE_INTEGER,
note: "Integers must be within the safe integer range.",
inst,
origin,
inclusive: true,
continue: !def.abort,
});
}
else {
// too_small
payload.issues.push({
input,
code: "too_small",
minimum: Number.MIN_SAFE_INTEGER,
note: "Integers must be within the safe integer range.",
inst,
origin,
inclusive: true,
continue: !def.abort,
});
}
return;
}
}
if (input < minimum) {
payload.issues.push({
origin: "number",
input,
code: "too_small",
minimum,
inclusive: true,
inst,
continue: !def.abort,
});
}
if (input > maximum) {
payload.issues.push({
origin: "number",
input,
code: "too_big",
maximum,
inclusive: true,
inst,
continue: !def.abort,
});
}
};
});
exports.$ZodCheckBigIntFormat = core.$constructor("$ZodCheckBigIntFormat", (inst, def) => {
exports.$ZodCheck.init(inst, def); // no format checks
const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.format = def.format;
bag.minimum = minimum;
bag.maximum = maximum;
});
inst._zod.check = (payload) => {
const input = payload.value;
if (input < minimum) {
payload.issues.push({
origin: "bigint",
input,
code: "too_small",
minimum: minimum,
inclusive: true,
inst,
continue: !def.abort,
});
}
if (input > maximum) {
payload.issues.push({
origin: "bigint",
input,
code: "too_big",
maximum,
inclusive: true,
inst,
continue: !def.abort,
});
}
};
});
exports.$ZodCheckMaxSize = core.$constructor("$ZodCheckMaxSize", (inst, def) => {
var _a;
exports.$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = (payload) => {
const val = payload.value;
return !util.nullish(val) && val.size !== undefined;
});
inst._zod.onattach.push((inst) => {
const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);
if (def.maximum < curr)
inst._zod.bag.maximum = def.maximum;
});
inst._zod.check = (payload) => {
const input = payload.value;
const size = input.size;
if (size <= def.maximum)
return;
payload.issues.push({
origin: util.getSizableOrigin(input),
code: "too_big",
maximum: def.maximum,
inclusive: true,
input,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckMinSize = core.$constructor("$ZodCheckMinSize", (inst, def) => {
var _a;
exports.$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = (payload) => {
const val = payload.value;
return !util.nullish(val) && val.size !== undefined;
});
inst._zod.onattach.push((inst) => {
const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);
if (def.minimum > curr)
inst._zod.bag.minimum = def.minimum;
});
inst._zod.check = (payload) => {
const input = payload.value;
const size = input.size;
if (size >= def.minimum)
return;
payload.issues.push({
origin: util.getSizableOrigin(input),
code: "too_small",
minimum: def.minimum,
inclusive: true,
input,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckSizeEquals = core.$constructor("$ZodCheckSizeEquals", (inst, def) => {
var _a;
exports.$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = (payload) => {
const val = payload.value;
return !util.nullish(val) && val.size !== undefined;
});
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.minimum = def.size;
bag.maximum = def.size;
bag.size = def.size;
});
inst._zod.check = (payload) => {
const input = payload.value;
const size = input.size;
if (size === def.size)
return;
const tooBig = size > def.size;
payload.issues.push({
origin: util.getSizableOrigin(input),
...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }),
inclusive: true,
exact: true,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckMaxLength = core.$constructor("$ZodCheckMaxLength", (inst, def) => {
var _a;
exports.$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = (payload) => {
const val = payload.value;
return !util.nullish(val) && val.length !== undefined;
});
inst._zod.onattach.push((inst) => {
const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);
if (def.maximum < curr)
inst._zod.bag.maximum = def.maximum;
});
inst._zod.check = (payload) => {
const input = payload.value;
const length = input.length;
if (length <= def.maximum)
return;
const origin = util.getLengthableOrigin(input);
payload.issues.push({
origin,
code: "too_big",
maximum: def.maximum,
inclusive: true,
input,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckMinLength = core.$constructor("$ZodCheckMinLength", (inst, def) => {
var _a;
exports.$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = (payload) => {
const val = payload.value;
return !util.nullish(val) && val.length !== undefined;
});
inst._zod.onattach.push((inst) => {
const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);
if (def.minimum > curr)
inst._zod.bag.minimum = def.minimum;
});
inst._zod.check = (payload) => {
const input = payload.value;
const length = input.length;
if (length >= def.minimum)
return;
const origin = util.getLengthableOrigin(input);
payload.issues.push({
origin,
code: "too_small",
minimum: def.minimum,
inclusive: true,
input,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckLengthEquals = core.$constructor("$ZodCheckLengthEquals", (inst, def) => {
var _a;
exports.$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = (payload) => {
const val = payload.value;
return !util.nullish(val) && val.length !== undefined;
});
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.minimum = def.length;
bag.maximum = def.length;
bag.length = def.length;
});
inst._zod.check = (payload) => {
const input = payload.value;
const length = input.length;
if (length === def.length)
return;
const origin = util.getLengthableOrigin(input);
const tooBig = length > def.length;
payload.issues.push({
origin,
...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }),
inclusive: true,
exact: true,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckStringFormat = core.$constructor("$ZodCheckStringFormat", (inst, def) => {
var _a, _b;
exports.$ZodCheck.init(inst, def);
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.format = def.format;
if (def.pattern) {
bag.patterns ?? (bag.patterns = new Set());
bag.patterns.add(def.pattern);
}
});
if (def.pattern)
(_a = inst._zod).check ?? (_a.check = (payload) => {
def.pattern.lastIndex = 0;
if (def.pattern.test(payload.value))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: def.format,
input: payload.value,
...(def.pattern ? { pattern: def.pattern.toString() } : {}),
inst,
continue: !def.abort,
});
});
else
(_b = inst._zod).check ?? (_b.check = () => { });
});
exports.$ZodCheckRegex = core.$constructor("$ZodCheckRegex", (inst, def) => {
exports.$ZodCheckStringFormat.init(inst, def);
inst._zod.check = (payload) => {
def.pattern.lastIndex = 0;
if (def.pattern.test(payload.value))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "regex",
input: payload.value,
pattern: def.pattern.toString(),
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckLowerCase = core.$constructor("$ZodCheckLowerCase", (inst, def) => {
def.pattern ?? (def.pattern = regexes.lowercase);
exports.$ZodCheckStringFormat.init(inst, def);
});
exports.$ZodCheckUpperCase = core.$constructor("$ZodCheckUpperCase", (inst, def) => {
def.pattern ?? (def.pattern = regexes.uppercase);
exports.$ZodCheckStringFormat.init(inst, def);
});
exports.$ZodCheckIncludes = core.$constructor("$ZodCheckIncludes", (inst, def) => {
exports.$ZodCheck.init(inst, def);
const escapedRegex = util.escapeRegex(def.includes);
const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
def.pattern = pattern;
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.patterns ?? (bag.patterns = new Set());
bag.patterns.add(pattern);
});
inst._zod.check = (payload) => {
if (payload.value.includes(def.includes, def.position))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "includes",
includes: def.includes,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckStartsWith = core.$constructor("$ZodCheckStartsWith", (inst, def) => {
exports.$ZodCheck.init(inst, def);
const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);
def.pattern ?? (def.pattern = pattern);
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.patterns ?? (bag.patterns = new Set());
bag.patterns.add(pattern);
});
inst._zod.check = (payload) => {
if (payload.value.startsWith(def.prefix))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "starts_with",
prefix: def.prefix,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckEndsWith = core.$constructor("$ZodCheckEndsWith", (inst, def) => {
exports.$ZodCheck.init(inst, def);
const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);
def.pattern ?? (def.pattern = pattern);
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.patterns ?? (bag.patterns = new Set());
bag.patterns.add(pattern);
});
inst._zod.check = (payload) => {
if (payload.value.endsWith(def.suffix))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "ends_with",
suffix: def.suffix,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
///////////////////////////////////
///// $ZodCheckProperty /////
///////////////////////////////////
function handleCheckPropertyResult(result, payload, property) {
if (result.issues.length) {
payload.issues.push(...util.prefixIssues(property, result.issues));
}
}
exports.$ZodCheckProperty = core.$constructor("$ZodCheckProperty", (inst, def) => {
exports.$ZodCheck.init(inst, def);
inst._zod.check = (payload) => {
const result = def.schema._zod.run({
value: payload.value[def.property],
issues: [],
}, {});
if (result instanceof Promise) {
return result.then((result) => handleCheckPropertyResult(result, payload, def.property));
}
handleCheckPropertyResult(result, payload, def.property);
return;
};
});
exports.$ZodCheckMimeType = core.$constructor("$ZodCheckMimeType", (inst, def) => {
exports.$ZodCheck.init(inst, def);
const mimeSet = new Set(def.mime);
inst._zod.onattach.push((inst) => {
inst._zod.bag.mime = def.mime;
});
inst._zod.check = (payload) => {
if (mimeSet.has(payload.value.type))
return;
payload.issues.push({
code: "invalid_value",
values: def.mime,
input: payload.value.type,
inst,
continue: !def.abort,
});
};
});
exports.$ZodCheckOverwrite = core.$constructor("$ZodCheckOverwrite", (inst, def) => {
exports.$ZodCheck.init(inst, def);
inst._zod.check = (payload) => {
payload.value = def.tx(payload.value);
};
});

View File

@@ -0,0 +1,57 @@
{
"reg": {
"name": "reg",
"browser": "Mobile Safari 10.0.0 (iOS 10.3.0)",
"suite": "escape-long",
"hz": 402089.26277975074,
"success": true,
"fastest": false,
"rme": 0.009840618321492465,
"rhz": 0.33427940860849686,
"sampleSize": 176
},
"fn if": {
"name": "fn if",
"browser": "Mobile Safari 10.0.0 (iOS 10.3.0)",
"suite": "escape-long",
"hz": 92081.06960950758,
"success": true,
"fastest": false,
"rme": 0.00906764573748056,
"rhz": 0.07655216973541666,
"sampleSize": 177
},
"fn if reverse": {
"name": "fn if reverse",
"browser": "Mobile Safari 10.0.0 (iOS 10.3.0)",
"suite": "escape-long",
"hz": 82352.01198595639,
"success": true,
"fastest": false,
"rme": 0.016802527454663683,
"rhz": 0.06846385718950287,
"sampleSize": 174
},
"escape31": {
"name": "escape31",
"browser": "Mobile Safari 10.0.0 (iOS 10.3.0)",
"suite": "escape-long",
"hz": 92918.88649108761,
"success": true,
"fastest": false,
"rme": 0.01548384596707835,
"rhz": 0.07724869400905834,
"sampleSize": 178
},
"native": {
"name": "native",
"browser": "Mobile Safari 10.0.0 (iOS 10.3.0)",
"suite": "escape-long",
"hz": 1202853.8175699352,
"success": true,
"fastest": true,
"rme": 0.009327160436626335,
"rhz": 1,
"sampleSize": 176
}
}

View File

@@ -0,0 +1,120 @@
{
"name": "pino",
"version": "10.3.1",
"description": "super fast, all natural json logger",
"main": "pino.js",
"type": "commonjs",
"types": "pino.d.ts",
"browser": "./browser.js",
"scripts": {
"borp": "borp --timeout 60000 --coverage --check-coverage --lines 95 --functions 95 --branches 95 --statements 95",
"docs": "docsify serve",
"browser-test": "airtap --local 8080 test/browser*test.js",
"lint": "eslint .",
"prepublishOnly": "node test/internals/version.test.js",
"test": "npm run lint && npm run transpile && npm run borp && jest test/jest && npm run test-types",
"test-ci": "npm run lint && npm run transpile && npm run borp && npm run test-types",
"test-ci-pnpm": "pnpm run lint && npm run transpile && borp --timeout 60000 && pnpm run test-types",
"test-ci-yarn-pnp": "yarn run lint && npm run transpile && borp --timeout 60000",
"test-types": "tsc && tsd && ts-node test/types/pino.ts && attw --pack .",
"test:smoke": "smoker smoke:pino && smoker smoke:browser && smoker smoke:file",
"smoke:pino": "node ./pino.js",
"smoke:browser": "node ./browser.js",
"smoke:file": "node ./file.js",
"transpile": "node ./test/fixtures/ts/transpile.cjs",
"cov-ui": "tap --ts --coverage-report=html",
"bench": "node benchmarks/utils/runbench all",
"bench-basic": "node benchmarks/utils/runbench basic",
"bench-object": "node benchmarks/utils/runbench object",
"bench-deep-object": "node benchmarks/utils/runbench deep-object",
"bench-multi-arg": "node benchmarks/utils/runbench multi-arg",
"bench-long-string": "node benchmarks/utils/runbench long-string",
"bench-child": "node benchmarks/utils/runbench child",
"bench-child-child": "node benchmarks/utils/runbench child-child",
"bench-child-creation": "node benchmarks/utils/runbench child-creation",
"bench-formatters": "node benchmarks/utils/runbench formatters",
"update-bench-doc": "node benchmarks/utils/generate-benchmark-doc > docs/benchmarks.md"
},
"bin": {
"pino": "./bin.js"
},
"precommit": "test",
"repository": {
"type": "git",
"url": "git+https://github.com/pinojs/pino.git"
},
"keywords": [
"fast",
"logger",
"stream",
"json"
],
"author": "Matteo Collina <hello@matteocollina.com>",
"contributors": [
"David Mark Clements <huperekchuno@googlemail.com>",
"James Sumners <james.sumners@gmail.com>",
"Thomas Watson Steen <w@tson.dk> (https://twitter.com/wa7son)"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/pinojs/pino/issues"
},
"homepage": "https://getpino.io",
"devDependencies": {
"@arethetypeswrong/cli": "^0.18.1",
"@matteo.collina/tspl": "^0.2.0",
"@types/flush-write-stream": "^1.0.0",
"@types/node": "^25.0.3",
"airtap": "5.0.0",
"bole": "^5.0.5",
"borp": "^0.21.0",
"bunyan": "^1.8.14",
"debug": "^4.3.4",
"docsify-cli": "^4.4.4",
"eslint": "^9.37.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-n": "17.23.2",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^6.0.0",
"execa": "^5.0.0",
"fastbench": "^1.0.1",
"flush-write-stream": "^2.0.0",
"import-fresh": "^3.2.1",
"jest": "^30.0.3",
"log": "^6.0.0",
"loglevel": "^1.6.7",
"midnight-smoker": "1.1.1",
"neostandard": "^0.12.2",
"pino-pretty": "^13.0.0",
"pre-commit": "^1.2.2",
"proxyquire": "^2.1.3",
"pump": "^3.0.0",
"rimraf": "^6.0.1",
"semver": "^7.3.7",
"split2": "^4.0.0",
"steed": "^1.1.3",
"strip-ansi": "^6.0.0",
"tape": "^5.5.3",
"through2": "^4.0.0",
"ts-node": "^10.9.1",
"tsd": "^0.33.0",
"typescript": "~5.9.2",
"winston": "^3.7.2"
},
"dependencies": {
"atomic-sleep": "^1.0.0",
"on-exit-leak-free": "^2.1.0",
"pino-abstract-transport": "^3.0.0",
"pino-std-serializers": "^7.0.0",
"process-warning": "^5.0.0",
"quick-format-unescaped": "^4.0.3",
"real-require": "^0.2.0",
"safe-stable-stringify": "^2.3.1",
"@pinojs/redact": "^0.4.0",
"sonic-boom": "^4.0.1",
"thread-stream": "^4.0.0"
},
"tsd": {
"directory": "test/types"
}
}

View File

@@ -0,0 +1,239 @@
'use strict';
module.exports = {
copy: copy,
checkDataType: checkDataType,
checkDataTypes: checkDataTypes,
coerceToTypes: coerceToTypes,
toHash: toHash,
getProperty: getProperty,
escapeQuotes: escapeQuotes,
equal: require('fast-deep-equal'),
ucs2length: require('./ucs2length'),
varOccurences: varOccurences,
varReplace: varReplace,
schemaHasRules: schemaHasRules,
schemaHasRulesExcept: schemaHasRulesExcept,
schemaUnknownRules: schemaUnknownRules,
toQuotedString: toQuotedString,
getPathExpr: getPathExpr,
getPath: getPath,
getData: getData,
unescapeFragment: unescapeFragment,
unescapeJsonPointer: unescapeJsonPointer,
escapeFragment: escapeFragment,
escapeJsonPointer: escapeJsonPointer
};
function copy(o, to) {
to = to || {};
for (var key in o) to[key] = o[key];
return to;
}
function checkDataType(dataType, data, strictNumbers, negate) {
var EQUAL = negate ? ' !== ' : ' === '
, AND = negate ? ' || ' : ' && '
, OK = negate ? '!' : ''
, NOT = negate ? '' : '!';
switch (dataType) {
case 'null': return data + EQUAL + 'null';
case 'array': return OK + 'Array.isArray(' + data + ')';
case 'object': return '(' + OK + data + AND +
'typeof ' + data + EQUAL + '"object"' + AND +
NOT + 'Array.isArray(' + data + '))';
case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
NOT + '(' + data + ' % 1)' +
AND + data + EQUAL + data +
(strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' +
(strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
}
}
function checkDataTypes(dataTypes, data, strictNumbers) {
switch (dataTypes.length) {
case 1: return checkDataType(dataTypes[0], data, strictNumbers, true);
default:
var code = '';
var types = toHash(dataTypes);
if (types.array && types.object) {
code = types.null ? '(': '(!' + data + ' || ';
code += 'typeof ' + data + ' !== "object")';
delete types.null;
delete types.array;
delete types.object;
}
if (types.number) delete types.integer;
for (var t in types)
code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true);
return code;
}
}
var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);
function coerceToTypes(optionCoerceTypes, dataTypes) {
if (Array.isArray(dataTypes)) {
var types = [];
for (var i=0; i<dataTypes.length; i++) {
var t = dataTypes[i];
if (COERCE_TO_TYPES[t]) types[types.length] = t;
else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t;
}
if (types.length) return types;
} else if (COERCE_TO_TYPES[dataTypes]) {
return [dataTypes];
} else if (optionCoerceTypes === 'array' && dataTypes === 'array') {
return ['array'];
}
}
function toHash(arr) {
var hash = {};
for (var i=0; i<arr.length; i++) hash[arr[i]] = true;
return hash;
}
var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
var SINGLE_QUOTE = /'|\\/g;
function getProperty(key) {
return typeof key == 'number'
? '[' + key + ']'
: IDENTIFIER.test(key)
? '.' + key
: "['" + escapeQuotes(key) + "']";
}
function escapeQuotes(str) {
return str.replace(SINGLE_QUOTE, '\\$&')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\f/g, '\\f')
.replace(/\t/g, '\\t');
}
function varOccurences(str, dataVar) {
dataVar += '[^0-9]';
var matches = str.match(new RegExp(dataVar, 'g'));
return matches ? matches.length : 0;
}
function varReplace(str, dataVar, expr) {
dataVar += '([^0-9])';
expr = expr.replace(/\$/g, '$$$$');
return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
}
function schemaHasRules(schema, rules) {
if (typeof schema == 'boolean') return !schema;
for (var key in schema) if (rules[key]) return true;
}
function schemaHasRulesExcept(schema, rules, exceptKeyword) {
if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not';
for (var key in schema) if (key != exceptKeyword && rules[key]) return true;
}
function schemaUnknownRules(schema, rules) {
if (typeof schema == 'boolean') return;
for (var key in schema) if (!rules[key]) return key;
}
function toQuotedString(str) {
return '\'' + escapeQuotes(str) + '\'';
}
function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
var path = jsonPointers // false by default
? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')')
: (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'');
return joinPaths(currentPath, path);
}
function getPath(currentPath, prop, jsonPointers) {
var path = jsonPointers // false by default
? toQuotedString('/' + escapeJsonPointer(prop))
: toQuotedString(getProperty(prop));
return joinPaths(currentPath, path);
}
var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, lvl, paths) {
var up, jsonPointer, data, matches;
if ($data === '') return 'rootData';
if ($data[0] == '/') {
if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data);
jsonPointer = $data;
data = 'rootData';
} else {
matches = $data.match(RELATIVE_JSON_POINTER);
if (!matches) throw new Error('Invalid JSON-pointer: ' + $data);
up = +matches[1];
jsonPointer = matches[2];
if (jsonPointer == '#') {
if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
return paths[lvl - up];
}
if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
data = 'data' + ((lvl - up) || '');
if (!jsonPointer) return data;
}
var expr = data;
var segments = jsonPointer.split('/');
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
if (segment) {
data += getProperty(unescapeJsonPointer(segment));
expr += ' && ' + data;
}
}
return expr;
}
function joinPaths (a, b) {
if (a == '""') return b;
return (a + ' + ' + b).replace(/([^\\])' \+ '/g, '$1');
}
function unescapeFragment(str) {
return unescapeJsonPointer(decodeURIComponent(str));
}
function escapeFragment(str) {
return encodeURIComponent(escapeJsonPointer(str));
}
function escapeJsonPointer(str) {
return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
function unescapeJsonPointer(str) {
return str.replace(/~1/g, '/').replace(/~0/g, '~');
}

View File

@@ -0,0 +1,245 @@
{
"name": "eslint",
"version": "10.8.1",
"author": "Nicholas C. Zakas <nicholas+npm@nczconsulting.com>",
"description": "An AST-based pattern checker for JavaScript.",
"type": "commonjs",
"bin": {
"eslint": "./bin/eslint.js"
},
"main": "./lib/api.js",
"types": "./lib/types/index.d.ts",
"exports": {
".": {
"types": "./lib/types/index.d.ts",
"default": "./lib/api.js"
},
"./config": {
"types": "./lib/types/config-api.d.ts",
"default": "./lib/config-api.js"
},
"./package.json": "./package.json",
"./use-at-your-own-risk": {
"types": "./lib/types/use-at-your-own-risk.d.ts",
"default": "./lib/unsupported-api.js"
},
"./rules": {
"types": "./lib/types/rules.d.ts"
},
"./universal": {
"types": "./lib/types/universal.d.ts",
"default": "./lib/universal.js"
}
},
"typesVersions": {
"*": {
"use-at-your-own-risk": [
"./lib/types/use-at-your-own-risk.d.ts"
],
"rules": [
"./lib/types/rules.d.ts"
],
"universal": [
"./lib/types/universal.d.ts"
],
"config": [
"./lib/types/config-api.d.ts"
]
}
},
"scripts": {
"build:docs:update-links": "node tools/fetch-docs-links.js",
"build:site": "node Makefile.js gensite",
"build:webpack": "node Makefile.js webpack",
"build:readme": "node tools/update-readme.js",
"build:rules-index": "node Makefile.js generateRuleIndexPage",
"fmt": "prettier --write .",
"fmt:check": "prettier --check .",
"lint": "node Makefile.js lint",
"lint:docs:js": "node Makefile.js lintDocsJS",
"lint:docs:rule-examples": "node Makefile.js checkRuleExamples",
"lint:unused": "knip",
"lint:fix": "node Makefile.js lint -- fix",
"lint:fix:docs:js": "node Makefile.js lintDocsJS -- fix",
"lint:rule-types": "node tools/update-rule-type-headers.js --check",
"lint:types": "attw --pack",
"release:generate:alpha": "node Makefile.js generatePrerelease -- alpha",
"release:generate:beta": "node Makefile.js generatePrerelease -- beta",
"release:generate:latest": "node Makefile.js generateRelease -- latest",
"release:generate:maintenance": "node Makefile.js generateRelease -- maintenance",
"release:generate:rc": "node Makefile.js generatePrerelease -- rc",
"release:publish": "node Makefile.js publishRelease",
"test": "node Makefile.js test",
"test:browser": "node Makefile.js cypress",
"test:cli": "mocha",
"test:ecosystem": "node tools/test-ecosystem/index.mjs",
"test:ecosystem:update": "node tools/test-ecosystem/update.mjs",
"test:emfile": "node tools/check-emfile-handling.js",
"test:fuzz": "node Makefile.js fuzz",
"test:performance": "node Makefile.js perf",
"test:pnpm": "cd tests/pnpm && node check.js && pnpm install && pnpm exec tsc",
"test:types": "tsc -p tests/lib/types/tsconfig.json && npm run test:types --workspaces --if-present",
"test:types:5.3": "npx -p typescript@5.3 -y -- tsc -p tsconfig.types-legacy.json",
"test:types:5.x": "npx -p typescript@5.x -y -- tsc -p tsconfig.types.json",
"test:types:7.x": "npx -p @typescript/native-preview@latest -y -- tsgo -p tsconfig.types.json",
"test:types:all": "npm run test:types && npm run test:types:5.3 && npm run test:types:5.x && npm run test:types:7.x"
},
"allowScripts": {
"core-js": false,
"cypress": false,
"re2": true,
"yorkie": true
},
"workspaces": [
"packages/*"
],
"gitHooks": {
"pre-commit": "lint-staged"
},
"lint-staged": {
"*.{js,json,jsonc,json5,yml,yaml}": [
"eslint --fix",
"prettier --write"
],
"docs/src/**/*.md": [
"markdownlint-cli2 --fix",
"prettier --write"
],
"!({{*.,**/*.}{js,json,jsonc,json5,yml,yaml},docs/src/**/*.md})": "prettier --write --ignore-unknown",
"lib/rules/*.js": [
"node tools/update-eslint-all.js",
"node tools/update-eslint-recommended.js",
"node tools/update-rule-type-headers.js",
"git add packages/js/src/configs/*.js lib/types/rules.d.ts"
],
"docs/src/rules/*.md": [
"node tools/check-rule-examples.js",
"node tools/fetch-docs-links.js",
"git add docs/src/_data/further_reading_links.json"
],
"docs/**/*.svg": "npx -y svgo -r --multipass"
},
"files": [
"LICENSE",
"README.md",
"bin",
"conf",
"lib",
"messages"
],
"repository": "eslint/eslint",
"funding": "https://eslint.org/donate",
"homepage": "https://eslint.org",
"bugs": "https://github.com/eslint/eslint/issues/",
"dependencies": {
"@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.2",
"@eslint/config-array": "^0.23.5",
"@eslint/config-helpers": "^0.7.0",
"@eslint/core": "^1.2.1",
"@eslint/plugin-kit": "^0.7.2",
"@humanfs/node": "^0.16.6",
"@humanwhocodes/module-importer": "^1.0.1",
"@humanwhocodes/retry": "^0.4.2",
"@types/estree": "^1.0.6",
"ajv": "^6.14.0",
"cross-spawn": "^7.0.6",
"debug": "^4.3.2",
"escape-string-regexp": "^4.0.0",
"eslint-scope": "^9.1.2",
"eslint-visitor-keys": "^5.0.1",
"espree": "^11.2.0",
"esquery": "^1.7.0",
"esutils": "^2.0.2",
"fast-deep-equal": "^3.1.3",
"file-entry-cache": "^8.0.0",
"find-up": "^5.0.0",
"glob-parent": "^6.0.2",
"ignore": "^5.2.0",
"imurmurhash": "^0.1.4",
"is-glob": "^4.0.0",
"json-stable-stringify-without-jsonify": "^1.0.1",
"minimatch": "^10.2.5",
"natural-compare": "^1.4.0",
"optionator": "^0.9.3"
},
"devDependencies": {
"@arethetypeswrong/cli": "^0.18.3",
"@babel/core": "^7.4.3",
"@babel/preset-env": "^7.4.3",
"@cypress/webpack-preprocessor": "^6.0.2",
"@eslint/eslintrc": "^3.3.6",
"@eslint/json": "^2.0.1",
"@types/esquery": "^1.5.4",
"@types/node": "^22.13.14",
"@typescript-eslint/parser": "^8.58.2",
"babel-loader": "^8.0.5",
"c8": "^11.0.0",
"chai": "^4.0.1",
"cheerio": "^0.22.0",
"common-tags": "^1.8.0",
"core-js": "^3.1.3",
"cypress": "^14.1.0",
"ejs": "^3.0.2",
"eslint": "file:.",
"eslint-config-eslint": "file:packages/eslint-config-eslint",
"eslint-plugin-eslint-plugin": "^7.3.2",
"eslint-plugin-expect-type": "^0.6.0",
"eslint-plugin-yml": "^1.14.0",
"eslint-release": "^3.3.0",
"eslint-rule-extender": "^0.0.1",
"eslump": "^3.0.0",
"esprima": "^4.0.1",
"fs-teardown": "^0.1.3",
"glob": "^10.0.0",
"globals": "^16.2.0",
"got": "^11.8.3",
"gray-matter": "^4.0.3",
"jiti": "^2.6.1",
"knip": "^6.13.1",
"lint-staged": "^11.0.0",
"markdown-it": "^14.2.0",
"markdown-it-container": "^4.0.0",
"markdownlint-cli2": "^0.22.0",
"marked": "^4.0.8",
"metascraper": "^5.25.7",
"metascraper-description": "^5.25.7",
"metascraper-image": "^5.29.3",
"metascraper-logo": "^5.25.7",
"metascraper-logo-favicon": "^5.25.7",
"metascraper-title": "^5.25.7",
"mocha": "^11.7.1",
"node-polyfill-webpack-plugin": "^1.0.3",
"npm-license": "^0.3.3",
"prettier": "3.9.6",
"progress": "^2.0.3",
"proxyquire": "^2.0.1",
"regenerator-runtime": "^0.14.0",
"semver": "^7.5.3",
"shelljs": "^0.10.0",
"sinon": "^11.0.0",
"typescript": "^6.0.3",
"webpack": "^5.109.2",
"webpack-cli": "^4.5.0",
"yorkie": "^2.0.0"
},
"peerDependencies": {
"jiti": "*"
},
"peerDependenciesMeta": {
"jiti": {
"optional": true
}
},
"keywords": [
"ast",
"lint",
"javascript",
"ecmascript",
"espree"
],
"license": "MIT",
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=24"
}
}

View File

@@ -0,0 +1,8 @@
function _tagged_template_literal_loose(strings, raw) {
if (!raw) raw = strings.slice(0);
strings.raw = raw;
return strings;
}
export { _tagged_template_literal_loose as _ };

View File

@@ -0,0 +1,4 @@
export const Headers: typeof globalThis.Headers = globalThis.Headers;
export const Request: typeof globalThis.Request = globalThis.Request;
export const Response: typeof globalThis.Response = globalThis.Response;
export default globalThis.fetch;

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"file":"stack-trace.d.ts","sourceRoot":"","sources":["../../src/stack-trace.ts"],"names":[],"mappings":"AAAA,wBAAgB,qBAAqB,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,OAAO,KAAK,CAAC,iBAAiB,CAAC,GAAG,IAAI,CAI/F"}

View File

@@ -0,0 +1,52 @@
{
"name": "ieee754",
"description": "Read/write IEEE754 floating point numbers from/to a Buffer or array-like object",
"version": "1.2.1",
"author": {
"name": "Feross Aboukhadijeh",
"email": "feross@feross.org",
"url": "https://feross.org"
},
"contributors": [
"Romain Beauxis <toots@rastageeks.org>"
],
"devDependencies": {
"airtap": "^3.0.0",
"standard": "*",
"tape": "^5.0.1"
},
"keywords": [
"IEEE 754",
"buffer",
"convert",
"floating point",
"ieee754"
],
"license": "BSD-3-Clause",
"main": "index.js",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "git://github.com/feross/ieee754.git"
},
"scripts": {
"test": "standard && npm run test-node && npm run test-browser",
"test-browser": "airtap -- test/*.js",
"test-browser-local": "airtap --local -- test/*.js",
"test-node": "tape test/*.js"
},
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
]
}

View File

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

View File

@@ -0,0 +1,125 @@
[Build]: http://img.shields.io/travis/litejs/natural-compare-lite.png
[Coverage]: http://img.shields.io/coveralls/litejs/natural-compare-lite.png
[1]: https://travis-ci.org/litejs/natural-compare-lite
[2]: https://coveralls.io/r/litejs/natural-compare-lite
[npm package]: https://npmjs.org/package/natural-compare-lite
[GitHub repo]: https://github.com/litejs/natural-compare-lite
@version 1.4.0
@date 2015-10-26
@stability 3 - Stable
Natural Compare &ndash; [![Build][]][1] [![Coverage][]][2]
===============
Compare strings containing a mix of letters and numbers
in the way a human being would in sort order.
This is described as a "natural ordering".
```text
Standard sorting: Natural order sorting:
img1.png img1.png
img10.png img2.png
img12.png img10.png
img2.png img12.png
```
String.naturalCompare returns a number indicating
whether a reference string comes before or after or is the same
as the given string in sort order.
Use it with builtin sort() function.
### Installation
- In browser
```html
<script src=min.natural-compare.js></script>
```
- In node.js: `npm install natural-compare-lite`
```javascript
require("natural-compare-lite")
```
### Usage
```javascript
// Simple case sensitive example
var a = ["z1.doc", "z10.doc", "z17.doc", "z2.doc", "z23.doc", "z3.doc"];
a.sort(String.naturalCompare);
// ["z1.doc", "z2.doc", "z3.doc", "z10.doc", "z17.doc", "z23.doc"]
// Use wrapper function for case insensitivity
a.sort(function(a, b){
return String.naturalCompare(a.toLowerCase(), b.toLowerCase());
})
// In most cases we want to sort an array of objects
var a = [ {"street":"350 5th Ave", "room":"A-1021"}
, {"street":"350 5th Ave", "room":"A-21046-b"} ];
// sort by street, then by room
a.sort(function(a, b){
return String.naturalCompare(a.street, b.street) || String.naturalCompare(a.room, b.room);
})
// When text transformation is needed (eg toLowerCase()),
// it is best for performance to keep
// transformed key in that object.
// There are no need to do text transformation
// on each comparision when sorting.
var a = [ {"make":"Audi", "model":"A6"}
, {"make":"Kia", "model":"Rio"} ];
// sort by make, then by model
a.map(function(car){
car.sort_key = (car.make + " " + car.model).toLowerCase();
})
a.sort(function(a, b){
return String.naturalCompare(a.sort_key, b.sort_key);
})
```
- Works well with dates in ISO format eg "Rev 2012-07-26.doc".
### Custom alphabet
It is possible to configure a custom alphabet
to achieve a desired order.
```javascript
// Estonian alphabet
String.alphabet = "ABDEFGHIJKLMNOPRSŠZŽTUVÕÄÖÜXYabdefghijklmnoprsšzžtuvõäöüxy"
["t", "z", "x", "õ"].sort(String.naturalCompare)
// ["z", "t", "õ", "x"]
// Russian alphabet
String.alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя"
["Ё", "А", "Б"].sort(String.naturalCompare)
// ["А", "Б", "Ё"]
```
External links
--------------
- [GitHub repo][https://github.com/litejs/natural-compare-lite]
- [jsperf test](http://jsperf.com/natural-sort-2/12)
Licence
-------
Copyright (c) 2012-2015 Lauri Rooden &lt;lauri@rooden.ee&gt;
[The MIT License](http://lauri.rooden.ee/mit-license.txt)

View File

@@ -0,0 +1,32 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABILITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
interface PromiseConstructor {
/**
* Takes a callback of any kind (returns or throws, synchronously or asynchronously) and wraps its result
* in a Promise.
*
* @param callbackFn A function that is called synchronously. It can do anything: either return
* a value, throw an error, or return a promise.
* @param args Additional arguments, that will be passed to the callback.
*
* @returns A Promise that is:
* - Already fulfilled, if the callback synchronously returns a value.
* - Already rejected, if the callback synchronously throws an error.
* - Asynchronously fulfilled or rejected, if the callback returns a promise.
*/
try<T, U extends unknown[]>(callbackFn: (...args: U) => T | PromiseLike<T>, ...args: U): Promise<Awaited<T>>;
}

View File

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

View File

@@ -0,0 +1,27 @@
import type { TSESTree } from '@typescript-eslint/types';
import type { VisitorOptions } from './VisitorBase';
import { VisitorBase } from './VisitorBase';
export type PatternVisitorCallback = (pattern: TSESTree.Identifier, info: {
assignments: (TSESTree.AssignmentExpression | TSESTree.AssignmentPattern)[];
rest: boolean;
topLevel: boolean;
}) => void;
export type PatternVisitorOptions = VisitorOptions;
export declare class PatternVisitor extends VisitorBase {
#private;
readonly rightHandNodes: TSESTree.Node[];
constructor(options: PatternVisitorOptions, rootPattern: TSESTree.Node, callback: PatternVisitorCallback);
static isPattern(node: TSESTree.Node): node is TSESTree.ArrayPattern | TSESTree.AssignmentPattern | TSESTree.Identifier | TSESTree.ObjectPattern | TSESTree.RestElement | TSESTree.SpreadElement;
protected ArrayExpression(node: TSESTree.ArrayExpression): void;
protected ArrayPattern(pattern: TSESTree.ArrayPattern): void;
protected AssignmentExpression(node: TSESTree.AssignmentExpression): void;
protected AssignmentPattern(pattern: TSESTree.AssignmentPattern): void;
protected CallExpression(node: TSESTree.CallExpression): void;
protected Decorator(): void;
protected Identifier(pattern: TSESTree.Identifier): void;
protected MemberExpression(node: TSESTree.MemberExpression): void;
protected Property(property: TSESTree.Property): void;
protected RestElement(pattern: TSESTree.RestElement): void;
protected SpreadElement(node: TSESTree.SpreadElement): void;
protected TSTypeAnnotation(): void;
}

View File

@@ -0,0 +1,8 @@
"use strict";
var id = 0;
function _class_private_field_loose_key(name) {
return "__private_" + id++ + "_" + name;
}
exports._ = _class_private_field_loose_key;

View File

@@ -0,0 +1,130 @@
/**
* @fileoverview Define utility functions for token store.
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Finds the index of the first token which is after the given location.
* If it was not found, this returns `tokens.length`.
* @param {(Token|Comment)[]} tokens It searches the token in this list.
* @param {number} location The location to search.
* @returns {number} The found index or `tokens.length`.
*/
function search(tokens, location) {
for (
let minIndex = 0, maxIndex = tokens.length - 1;
minIndex <= maxIndex;
) {
/*
* Calculate the index in the middle between minIndex and maxIndex.
* `| 0` is used to round a fractional value down to the nearest integer: this is similar to
* using `Math.trunc()` or `Math.floor()`, but performance tests have shown this method to
* be faster.
*/
const index = ((minIndex + maxIndex) / 2) | 0;
const token = tokens[index];
const tokenStartLocation = token.range[0];
if (location <= tokenStartLocation) {
if (index === minIndex) {
return index;
}
maxIndex = index;
} else {
minIndex = index + 1;
}
}
return tokens.length;
}
/**
* Gets the index of the `startLoc` in `tokens`.
* `startLoc` can be the value of `node.range[1]`, so this checks about `startLoc - 1` as well.
* @param {(Token|Comment)[]} tokens The tokens to find an index.
* @param {Object} indexMap The map from locations to indices.
* @param {number} startLoc The location to get an index.
* @returns {number} The index.
*/
function getFirstIndex(tokens, indexMap, startLoc) {
if (startLoc === -1) {
return 0;
}
if (startLoc in indexMap) {
return indexMap[startLoc];
}
if (startLoc - 1 in indexMap) {
const index = indexMap[startLoc - 1];
const token = tokens[index];
// If the mapped index is out of bounds, the returned cursor index will point after the end of the tokens array.
if (!token) {
return tokens.length;
}
/*
* For the map of "comment's location -> token's index", it points the next token of a comment.
* In that case, +1 is unnecessary.
*/
if (token.range[0] >= startLoc) {
return index;
}
return index + 1;
}
// Program node that doesn't start/end with a token or comment
if (startLoc === 0) {
return 0;
}
return tokens.length;
}
/**
* Gets the index of the `endLoc` in `tokens`.
* The information of end locations are recorded at `endLoc - 1` in `indexMap`, so this checks about `endLoc - 1` as well.
* @param {(Token|Comment)[]} tokens The tokens to find an index.
* @param {Object} indexMap The map from locations to indices.
* @param {number} endLoc The location to get an index.
* @returns {number} The index.
*/
function getLastIndex(tokens, indexMap, endLoc) {
if (endLoc === -1) {
return tokens.length - 1;
}
if (endLoc in indexMap) {
return indexMap[endLoc] - 1;
}
if (endLoc - 1 in indexMap) {
const index = indexMap[endLoc - 1];
const token = tokens[index];
// If the mapped index is out of bounds, the returned cursor index will point before the end of the tokens array.
if (!token) {
return tokens.length - 1;
}
/*
* For the map of "comment's location -> token's index", it points the next token of a comment.
* In that case, -1 is necessary.
*/
if (token.range[1] > endLoc) {
return index - 1;
}
return index;
}
// Program node that doesn't start/end with a token or comment
if (endLoc === 0) {
return -1;
}
return tokens.length - 1;
}
//------------------------------------------------------------------------------
// Exports
//------------------------------------------------------------------------------
module.exports = { search, getFirstIndex, getLastIndex };

View File

@@ -0,0 +1,4 @@
function _nullishReceiverError(r) {
throw new TypeError("Cannot set property of null or undefined.");
}
module.exports = _nullishReceiverError, module.exports.__esModule = true, module.exports["default"] = module.exports;

View File

@@ -0,0 +1,43 @@
'use strict'
// Pino's primary usage writes ndjson to `stdout`:
const pino = require('..')()
// However, if "human readable" output is desired,
// `pino-pretty` can be provided as the destination
// stream by uncommenting the following line in place
// of the previous declaration:
// const pino = require('..')(require('pino-pretty')())
pino.info('hello world')
pino.error('this is at error level')
pino.info('the answer is %d', 42)
pino.info({ obj: 42 }, 'hello world')
pino.info({ obj: 42, b: 2 }, 'hello world')
pino.info({ nested: { obj: 42 } }, 'nested')
setImmediate(() => {
pino.info('after setImmediate')
})
pino.error(new Error('an error'))
const child = pino.child({ a: 'property' })
child.info('hello child!')
const childsChild = child.child({ another: 'property' })
childsChild.info('hello baby..')
pino.debug('this should be mute')
pino.level = 'trace'
pino.debug('this is a debug statement')
pino.child({ another: 'property' }).debug('this is a debug statement via child')
pino.trace('this is a trace statement')
pino.debug('this is a "debug" statement with "')
pino.info(new Error('kaboom'))
pino.info(null)
pino.info(new Error('kaboom'), 'with', 'a', 'message')

View File

@@ -0,0 +1 @@
{"version":3,"file":"objectFlags.js","sourceRoot":"","sources":["../../src/enums/objectFlags.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAC/F,MAAM,CAAC,IAAI,WAAgB,CAAC;AAC5B,CAAC,UAAU,WAAW;IAClB,WAAW,CAAC,WAAW,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,MAAM,CAAC;IAC9C,WAAW,CAAC,WAAW,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC;IAChD,WAAW,CAAC,WAAW,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,GAAG,WAAW,CAAC;IACxD,WAAW,CAAC,WAAW,CAAC,WAAW,CAA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Key } from '../utils.ts';
import { type AffinePoint, type BasicCurve, type CurveLengths, type CurvePoint, type CurvePointCons } from './curve.ts';
import { type IField, type NLength } from './modular.ts';
export type { AffinePoint };
export type HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;
type EndoBasis = [[bigint, bigint], [bigint, bigint]];
/**
* When Weierstrass curve has `a=0`, it becomes Koblitz curve.
* Koblitz curves allow using **efficiently-computable GLV endomorphism ψ**.
* Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
* For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
*
* Endomorphism consists of beta, lambda and splitScalar:
*
* 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`
* 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`
* 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)`
* 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than
* one 256-bit multiplication.
*
* where
* * beta: β ∈ Fₚ with β³ = 1, β ≠ 1
* * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1
* * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.
* Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)`
*
* Check out `test/misc/endomorphism.js` and
* [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).
*/
export type EndomorphismOpts = {
beta: bigint;
basises?: EndoBasis;
splitScalar?: (k: bigint) => {
k1neg: boolean;
k1: bigint;
k2neg: boolean;
k2: bigint;
};
};
export type ScalarEndoParts = {
k1neg: boolean;
k1: bigint;
k2neg: boolean;
k2: bigint;
};
/**
* Splits scalar for GLV endomorphism.
*/
export declare function _splitEndoScalar(k: bigint, basis: EndoBasis, n: bigint): ScalarEndoParts;
export type ECDSASigFormat = 'compact' | 'recovered' | 'der';
export type ECDSARecoverOpts = {
prehash?: boolean;
};
export type ECDSAVerifyOpts = {
prehash?: boolean;
lowS?: boolean;
format?: ECDSASigFormat;
};
export type ECDSASignOpts = {
prehash?: boolean;
lowS?: boolean;
format?: ECDSASigFormat;
extraEntropy?: Uint8Array | boolean;
};
/** Instance methods for 3D XYZ projective points. */
export interface WeierstrassPoint<T> extends CurvePoint<T, WeierstrassPoint<T>> {
/** projective X coordinate. Different from affine x. */
readonly X: T;
/** projective Y coordinate. Different from affine y. */
readonly Y: T;
/** projective z coordinate */
readonly Z: T;
/** affine x coordinate. Different from projective X. */
get x(): T;
/** affine y coordinate. Different from projective Y. */
get y(): T;
/** Encodes point using IEEE P1363 (DER) encoding. First byte is 2/3/4. Default = isCompressed. */
toBytes(isCompressed?: boolean): Uint8Array;
toHex(isCompressed?: boolean): string;
/** @deprecated use `.X` */
readonly px: T;
/** @deprecated use `.Y` */
readonly py: T;
/** @deprecated use `.Z` */
readonly pz: T;
/** @deprecated use `toBytes` */
toRawBytes(isCompressed?: boolean): Uint8Array;
/** @deprecated use `multiplyUnsafe` */
multiplyAndAddUnsafe(Q: WeierstrassPoint<T>, a: bigint, b: bigint): WeierstrassPoint<T> | undefined;
/** @deprecated use `p.y % 2n === 0n` */
hasEvenY(): boolean;
/** @deprecated use `p.precompute(windowSize)` */
_setWindowSize(windowSize: number): void;
}
/** Static methods for 3D XYZ projective points. */
export interface WeierstrassPointCons<T> extends CurvePointCons<WeierstrassPoint<T>> {
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
new (X: T, Y: T, Z: T): WeierstrassPoint<T>;
CURVE(): WeierstrassOpts<T>;
/** @deprecated use `Point.BASE.multiply(Point.Fn.fromBytes(privateKey))` */
fromPrivateKey(privateKey: PrivKey): WeierstrassPoint<T>;
/** @deprecated use `import { normalizeZ } from '@noble/curves/abstract/curve.js';` */
normalizeZ(points: WeierstrassPoint<T>[]): WeierstrassPoint<T>[];
/** @deprecated use `import { pippenger } from '@noble/curves/abstract/curve.js';` */
msm(points: WeierstrassPoint<T>[], scalars: bigint[]): WeierstrassPoint<T>;
}
/**
* Weierstrass curve options.
*
* * p: prime characteristic (order) of finite field, in which arithmetics is done
* * n: order of prime subgroup a.k.a total amount of valid curve points
* * h: cofactor, usually 1. h*n is group order; n is subgroup order
* * a: formula param, must be in field of p
* * b: formula param, must be in field of p
* * Gx: x coordinate of generator point a.k.a. base point
* * Gy: y coordinate of generator point
*/
export type WeierstrassOpts<T> = Readonly<{
p: bigint;
n: bigint;
h: bigint;
a: T;
b: T;
Gx: T;
Gy: T;
}>;
export type WeierstrassExtraOpts<T> = Partial<{
Fp: IField<T>;
Fn: IField<bigint>;
allowInfinityPoint: boolean;
endo: EndomorphismOpts;
isTorsionFree: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => boolean;
clearCofactor: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => WeierstrassPoint<T>;
fromBytes: (bytes: Uint8Array) => AffinePoint<T>;
toBytes: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>, isCompressed: boolean) => Uint8Array;
}>;
/**
* Options for ECDSA signatures over a Weierstrass curve.
*
* * lowS: (default: true) whether produced / verified signatures occupy low half of ecdsaOpts.p. Prevents malleability.
* * hmac: (default: noble-hashes hmac) function, would be used to init hmac-drbg for k generation.
* * randomBytes: (default: webcrypto os-level CSPRNG) custom method for fetching secure randomness.
* * bits2int, bits2int_modN: used in sigs, sometimes overridden by curves
*/
export type ECDSAOpts = Partial<{
lowS: boolean;
hmac: HmacFnSync;
randomBytes: (bytesLength?: number) => Uint8Array;
bits2int: (bytes: Uint8Array) => bigint;
bits2int_modN: (bytes: Uint8Array) => bigint;
}>;
/**
* Elliptic Curve Diffie-Hellman interface.
* Provides keygen, secret-to-public conversion, calculating shared secrets.
*/
export interface ECDH {
keygen: (seed?: Uint8Array) => {
secretKey: Uint8Array;
publicKey: Uint8Array;
};
getPublicKey: (secretKey: PrivKey, isCompressed?: boolean) => Uint8Array;
getSharedSecret: (secretKeyA: PrivKey, publicKeyB: Hex, isCompressed?: boolean) => Uint8Array;
Point: WeierstrassPointCons<bigint>;
utils: {
isValidSecretKey: (secretKey: PrivKey) => boolean;
isValidPublicKey: (publicKey: Uint8Array, isCompressed?: boolean) => boolean;
randomSecretKey: (seed?: Uint8Array) => Uint8Array;
/** @deprecated use `randomSecretKey` */
randomPrivateKey: (seed?: Uint8Array) => Uint8Array;
/** @deprecated use `isValidSecretKey` */
isValidPrivateKey: (secretKey: PrivKey) => boolean;
/** @deprecated use `Point.Fn.fromBytes()` */
normPrivateKeyToScalar: (key: PrivKey) => bigint;
/** @deprecated use `point.precompute()` */
precompute: (windowSize?: number, point?: WeierstrassPoint<bigint>) => WeierstrassPoint<bigint>;
};
lengths: CurveLengths;
}
/**
* ECDSA interface.
* Only supported for prime fields, not Fp2 (extension fields).
*/
export interface ECDSA extends ECDH {
sign: (message: Hex, secretKey: PrivKey, opts?: ECDSASignOpts) => ECDSASigRecovered;
verify: (signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array, opts?: ECDSAVerifyOpts) => boolean;
recoverPublicKey(signature: Uint8Array, message: Uint8Array, opts?: ECDSARecoverOpts): Uint8Array;
Signature: ECDSASignatureCons;
}
export declare class DERErr extends Error {
constructor(m?: string);
}
export type IDER = {
Err: typeof DERErr;
_tlv: {
encode: (tag: number, data: string) => string;
decode(tag: number, data: Uint8Array): {
v: Uint8Array;
l: Uint8Array;
};
};
_int: {
encode(num: bigint): string;
decode(data: Uint8Array): bigint;
};
toSig(hex: string | Uint8Array): {
r: bigint;
s: bigint;
};
hexFromSig(sig: {
r: bigint;
s: bigint;
}): string;
};
/**
* ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
*
* [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
*
* Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
*/
export declare const DER: IDER;
export declare function _normFnElement(Fn: IField<bigint>, key: PrivKey): bigint;
/**
* Creates weierstrass Point constructor, based on specified curve options.
*
* @example
```js
const opts = {
p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
h: BigInt(1),
a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
};
const p256_Point = weierstrass(opts);
```
*/
export declare function weierstrassN<T>(params: WeierstrassOpts<T>, extraOpts?: WeierstrassExtraOpts<T>): WeierstrassPointCons<T>;
/** Methods of ECDSA signature instance. */
export interface ECDSASignature {
readonly r: bigint;
readonly s: bigint;
readonly recovery?: number;
addRecoveryBit(recovery: number): ECDSASigRecovered;
hasHighS(): boolean;
toBytes(format?: string): Uint8Array;
toHex(format?: string): string;
/** @deprecated */
assertValidity(): void;
/** @deprecated */
normalizeS(): ECDSASignature;
/** @deprecated use standalone method `curve.recoverPublicKey(sig.toBytes('recovered'), msg)` */
recoverPublicKey(msgHash: Hex): WeierstrassPoint<bigint>;
/** @deprecated use `.toBytes('compact')` */
toCompactRawBytes(): Uint8Array;
/** @deprecated use `.toBytes('compact')` */
toCompactHex(): string;
/** @deprecated use `.toBytes('der')` */
toDERRawBytes(): Uint8Array;
/** @deprecated use `.toBytes('der')` */
toDERHex(): string;
}
export type ECDSASigRecovered = ECDSASignature & {
readonly recovery: number;
};
/** Methods of ECDSA signature constructor. */
export type ECDSASignatureCons = {
new (r: bigint, s: bigint, recovery?: number): ECDSASignature;
fromBytes(bytes: Uint8Array, format?: ECDSASigFormat): ECDSASignature;
fromHex(hex: string, format?: ECDSASigFormat): ECDSASignature;
/** @deprecated use `.fromBytes(bytes, 'compact')` */
fromCompact(hex: Hex): ECDSASignature;
/** @deprecated use `.fromBytes(bytes, 'der')` */
fromDER(hex: Hex): ECDSASignature;
};
/**
* Implementation of the Shallue and van de Woestijne method for any weierstrass curve.
* TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.
* b = True and y = sqrt(u / v) if (u / v) is square in F, and
* b = False and y = sqrt(Z * (u / v)) otherwise.
* @param Fp
* @param Z
* @returns
*/
export declare function SWUFpSqrtRatio<T>(Fp: IField<T>, Z: T): (u: T, v: T) => {
isValid: boolean;
value: T;
};
/**
* Simplified Shallue-van de Woestijne-Ulas Method
* https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2
*/
export declare function mapToCurveSimpleSWU<T>(Fp: IField<T>, opts: {
A: T;
B: T;
Z: T;
}): (u: T) => {
x: T;
y: T;
};
/**
* Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
* This helper ensures no signature functionality is present. Less code, smaller bundle size.
*/
export declare function ecdh(Point: WeierstrassPointCons<bigint>, ecdhOpts?: {
randomBytes?: (bytesLength?: number) => Uint8Array;
}): ECDH;
/**
* Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
* We need `hash` for 2 features:
* 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
* 2. k generation in `sign`, using HMAC-drbg(hash)
*
* ECDSAOpts are only rarely needed.
*
* @example
* ```js
* const p256_Point = weierstrass(...);
* const p256_sha256 = ecdsa(p256_Point, sha256);
* const p256_sha224 = ecdsa(p256_Point, sha224);
* const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
* ```
*/
export declare function ecdsa(Point: WeierstrassPointCons<bigint>, hash: CHash, ecdsaOpts?: ECDSAOpts): ECDSA;
/** @deprecated use ECDSASignature */
export type SignatureType = ECDSASignature;
/** @deprecated use ECDSASigRecovered */
export type RecoveredSignatureType = ECDSASigRecovered;
/** @deprecated switch to Uint8Array signatures in format 'compact' */
export type SignatureLike = {
r: bigint;
s: bigint;
};
export type ECDSAExtraEntropy = Hex | boolean;
/** @deprecated use `ECDSAExtraEntropy` */
export type Entropy = Hex | boolean;
export type BasicWCurve<T> = BasicCurve<T> & {
a: T;
b: T;
allowedPrivateKeyLengths?: readonly number[];
wrapPrivateKey?: boolean;
endo?: EndomorphismOpts;
isTorsionFree?: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => boolean;
clearCofactor?: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => WeierstrassPoint<T>;
};
/** @deprecated use ECDSASignOpts */
export type SignOpts = ECDSASignOpts;
/** @deprecated use ECDSASignOpts */
export type VerOpts = ECDSAVerifyOpts;
/** @deprecated use WeierstrassPoint */
export type ProjPointType<T> = WeierstrassPoint<T>;
/** @deprecated use WeierstrassPointCons */
export type ProjConstructor<T> = WeierstrassPointCons<T>;
/** @deprecated use ECDSASignatureCons */
export type SignatureConstructor = ECDSASignatureCons;
export type CurvePointsType<T> = BasicWCurve<T> & {
fromBytes?: (bytes: Uint8Array) => AffinePoint<T>;
toBytes?: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>, isCompressed: boolean) => Uint8Array;
};
export type CurvePointsTypeWithLength<T> = Readonly<CurvePointsType<T> & Partial<NLength>>;
export type CurvePointsRes<T> = {
Point: WeierstrassPointCons<T>;
/** @deprecated use `Point.CURVE()` */
CURVE: CurvePointsType<T>;
/** @deprecated use `Point` */
ProjectivePoint: WeierstrassPointCons<T>;
/** @deprecated use `Point.Fn.fromBytes(privateKey)` */
normPrivateKeyToScalar: (key: PrivKey) => bigint;
/** @deprecated */
weierstrassEquation: (x: T) => T;
/** @deprecated use `Point.Fn.isValidNot0(num)` */
isWithinCurveOrder: (num: bigint) => boolean;
};
/** @deprecated use `Uint8Array` */
export type PubKey = Hex | WeierstrassPoint<bigint>;
export type CurveType = BasicWCurve<bigint> & {
hash: CHash;
hmac?: HmacFnSync;
randomBytes?: (bytesLength?: number) => Uint8Array;
lowS?: boolean;
bits2int?: (bytes: Uint8Array) => bigint;
bits2int_modN?: (bytes: Uint8Array) => bigint;
};
export type CurveFn = {
/** @deprecated use `Point.CURVE()` */
CURVE: CurvePointsType<bigint>;
keygen: ECDSA['keygen'];
getPublicKey: ECDSA['getPublicKey'];
getSharedSecret: ECDSA['getSharedSecret'];
sign: ECDSA['sign'];
verify: ECDSA['verify'];
Point: WeierstrassPointCons<bigint>;
/** @deprecated use `Point` */
ProjectivePoint: WeierstrassPointCons<bigint>;
Signature: ECDSASignatureCons;
utils: ECDSA['utils'];
lengths: ECDSA['lengths'];
};
/** @deprecated use `weierstrass` in newer releases */
export declare function weierstrassPoints<T>(c: CurvePointsTypeWithLength<T>): CurvePointsRes<T>;
export type WsPointComposed<T> = {
CURVE: WeierstrassOpts<T>;
curveOpts: WeierstrassExtraOpts<T>;
};
export type WsComposed = {
/** @deprecated use `Point.CURVE()` */
CURVE: WeierstrassOpts<bigint>;
hash: CHash;
curveOpts: WeierstrassExtraOpts<bigint>;
ecdsaOpts: ECDSAOpts;
};
export declare function _legacyHelperEquat<T>(Fp: IField<T>, a: T, b: T): (x: T) => T;
export declare function weierstrass(c: CurveType): CurveFn;
//# sourceMappingURL=weierstrass.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"tower.d.ts","sourceRoot":"","sources":["../../src/abstract/tower.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,KAAK,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAO/E,MAAM,MAAM,WAAW,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAC3C,MAAM,MAAM,EAAE,GAAG,MAAM,CAAC;AAGxB,MAAM,MAAM,GAAG,GAAG;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,CAAC;AAC7C,MAAM,MAAM,SAAS,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAA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F,wBAAgB,OAAO,CAAC,IAAI,EAAE,WAAW,GAAG;IAC1C,EAAE,EAAE,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;IAC/E,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,OAAO,CAAC;CACf,CAMA"}

View File

@@ -0,0 +1,56 @@
import { n as __toESM, t as require_binding } from "./shared/binding-Zhafd14U.mjs";
import { n as onExit, t as watch } from "./shared/watch-BNCfUBmW.mjs";
import { T as VERSION, s as RolldownMagicString } from "./shared/bindingify-input-options-C-Zsy1EG.mjs";
import { t as rolldown } from "./shared/rolldown-DiYVDns9.mjs";
import { t as defineConfig } from "./shared/define-config-Demdg3_4.mjs";
import { isMainThread } from "node:worker_threads";
//#region src/setup.ts
var import_binding = /* @__PURE__ */ __toESM(require_binding(), 1);
if (isMainThread) {
const subscriberGuard = (0, import_binding.initTraceSubscriber)();
onExit(() => {
subscriberGuard?.close();
});
}
//#endregion
//#region src/constants/index.ts
/**
* Runtime helper module ID
*/
const RUNTIME_MODULE_ID = "\0rolldown/runtime.js";
//#endregion
//#region src/api/build.ts
/**
* The API similar to esbuild's `build` function.
*
* @example
* ```js
* import { build } from 'rolldown';
*
* const result = await build({
* input: 'src/main.js',
* output: {
* file: 'bundle.js',
* },
* });
* console.log(result);
* ```
*
* @experimental
* @category Programmatic APIs
*/
async function build(options) {
if (Array.isArray(options)) return Promise.all(options.map((opts) => build(opts)));
else {
const { output, write = true, ...inputOptions } = options;
const build = await rolldown(inputOptions);
try {
if (write) return await build.write(output);
else return await build.generate(output);
} finally {
await build.close();
}
}
}
//#endregion
export { RUNTIME_MODULE_ID, RolldownMagicString, VERSION, build, defineConfig, rolldown, watch };

View File

@@ -0,0 +1,12 @@
import type { TSESLint } from '@typescript-eslint/utils';
export type Options = [
{
fixToUnknown?: boolean;
ignoreRestArgs?: boolean;
}
];
export type MessageIds = 'suggestNever' | 'suggestPropertyKey' | 'suggestUnknown' | 'unexpectedAny';
declare const _default: TSESLint.RuleModule<MessageIds, Options, import("../../rules").ESLintPluginDocs, TSESLint.RuleListener> & {
name: string;
};
export default _default;

View File

@@ -0,0 +1,106 @@
"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 __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.expectTypeOf = void 0;
__exportStar(require("./branding"), exports); // backcompat, consider removing in next major version
__exportStar(require("./messages"), exports); // backcompat, consider removing in next major version
__exportStar(require("./overloads"), exports);
__exportStar(require("./utils"), exports); // backcompat, consider removing in next major version
const fn = () => true;
/**
* Similar to Jest's `expect`, but with type-awareness.
* Gives you access to a number of type-matchers that let you make assertions about the
* form of a reference or generic type parameter.
*
* @example
* ```ts
* import { foo, bar } from '../foo'
* import { expectTypeOf } from 'expect-type'
*
* test('foo types', () => {
* // make sure `foo` has type { a: number }
* expectTypeOf(foo).toMatchTypeOf({ a: 1 })
* expectTypeOf(foo).toHaveProperty('a').toBeNumber()
*
* // make sure `bar` is a function taking a string:
* expectTypeOf(bar).parameter(0).toBeString()
* expectTypeOf(bar).returns.not.toBeAny()
* })
* ```
*
* @description
* See the [full docs](https://npmjs.com/package/expect-type#documentation) for lots more examples.
*/
const expectTypeOf = (_actual) => {
const nonFunctionProperties = [
'parameters',
'returns',
'resolves',
'not',
'items',
'constructorParameters',
'thisParameter',
'instance',
'guards',
'asserts',
];
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
function createBranded() {
return {
inspect: () => true,
configure: () => createBranded(),
toEqualTypeOf: fn,
};
}
const obj = {
toBeAny: fn,
toBeUnknown: fn,
toBeNever: fn,
toBeFunction: fn,
toBeObject: fn,
toBeArray: fn,
toBeString: fn,
toBeNumber: fn,
toBeBoolean: fn,
toBeVoid: fn,
toBeSymbol: fn,
toBeNull: fn,
toBeUndefined: fn,
toBeNullable: fn,
toBeBigInt: fn,
toMatchTypeOf: fn,
toEqualTypeOf: fn,
toBeConstructibleWith: fn,
toMatchObjectType: fn,
toExtend: fn,
map: exports.expectTypeOf,
toBeCallableWith: exports.expectTypeOf,
extract: exports.expectTypeOf,
exclude: exports.expectTypeOf,
pick: exports.expectTypeOf,
omit: exports.expectTypeOf,
toHaveProperty: exports.expectTypeOf,
parameter: exports.expectTypeOf,
get branded() {
return createBranded();
},
};
/* eslint-enable @typescript-eslint/no-unsafe-assignment */
const getterProperties = nonFunctionProperties;
getterProperties.forEach((prop) => Object.defineProperty(obj, prop, { get: () => (0, exports.expectTypeOf)({}) }));
return obj;
};
exports.expectTypeOf = expectTypeOf;

View File

@@ -0,0 +1,30 @@
'use strict'
module.exports = getPropertyValue
const splitPropertyKey = require('./split-property-key')
/**
* Gets a specified property from an object if it exists.
*
* @param {object} obj The object to be searched.
* @param {string|string[]} property A string, or an array of strings, identifying
* the property to be retrieved from the object.
* Accepts nested properties delimited by a `.`.
* Delimiter can be escaped to preserve property names that contain the delimiter.
* e.g. `'prop1.prop2'` or `'prop2\.domain\.corp.prop2'`.
*
* @returns {*}
*/
function getPropertyValue (obj, property) {
const props = Array.isArray(property) ? property : splitPropertyKey(property)
for (const prop of props) {
if (!Object.prototype.hasOwnProperty.call(obj, prop)) {
return
}
obj = obj[prop]
}
return obj
}

View File

@@ -0,0 +1,109 @@
/**
* Miscellaneous, rarely used curves.
* jubjub, babyjubjub, pallas, vesta.
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { blake256 } from '@noble/hashes/blake1.js';
import { blake2s } from '@noble/hashes/blake2.js';
import { sha256, sha512 } from '@noble/hashes/sha2.js';
import { concatBytes, utf8ToBytes } from '@noble/hashes/utils.js';
import { twistedEdwards, } from "./abstract/edwards.js";
import { Field, mod } from "./abstract/modular.js";
import { weierstrass } from "./abstract/weierstrass.js";
import { bls12_381_Fr } from "./bls12-381.js";
import { bn254_Fr } from "./bn254.js";
// Jubjub curves have 𝔽p over scalar fields of other curves. They are friendly to ZK proofs.
// jubjub Fp = bls n. babyjubjub Fp = bn254 n.
// verify manually, check bls12-381.ts and bn254.ts.
const jubjub_CURVE = {
p: bls12_381_Fr.ORDER,
n: BigInt('0xe7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb7'),
h: BigInt(8),
a: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000'),
d: BigInt('0x2a9318e74bfa2b48f5fd9207e6bd7fd4292d7f6d37579d2601065fd6d6343eb1'),
Gx: BigInt('0x11dafe5d23e1218086a365b99fbf3d3be72f6afd7d1f72623e6b071492d1122b'),
Gy: BigInt('0x1d523cf1ddab1a1793132e78c866c0c33e26ba5cc220fed7cc3f870e59d292aa'),
};
/** Curve over scalar field of bls12-381. jubjub Fp = bls n */
export const jubjub = /* @__PURE__ */ twistedEdwards({
...jubjub_CURVE,
Fp: bls12_381_Fr,
hash: sha512,
});
const babyjubjub_CURVE = {
p: bn254_Fr.ORDER,
n: BigInt('0x30644e72e131a029b85045b68181585d59f76dc1c90770533b94bee1c9093788'),
h: BigInt(8),
a: BigInt('168700'),
d: BigInt('168696'),
Gx: BigInt('0x23343e3445b673d38bcba38f25645adb494b1255b1162bb40f41a59f4d4b45e'),
Gy: BigInt('0xc19139cb84c680a6e14116da06056174a0cfa121e6e5c2450f87d64fc000001'),
};
/** Curve over scalar field of bn254. babyjubjub Fp = bn254 n */
export const babyjubjub = /* @__PURE__ */ twistedEdwards({
...babyjubjub_CURVE,
Fp: bn254_Fr,
hash: blake256,
});
const jubjub_gh_first_block = utf8ToBytes('096b36a5804bfacef1691e173c366a47ff5ba84a44f26ddd7e8d9f79d5b42df0');
// Returns point at JubJub curve which is prime order and not zero
export function jubjub_groupHash(tag, personalization) {
const h = blake2s.create({ personalization, dkLen: 32 });
h.update(jubjub_gh_first_block);
h.update(tag);
// NOTE: returns ExtendedPoint, in case it will be multiplied later
let p = jubjub.Point.fromBytes(h.digest());
// NOTE: cannot replace with isSmallOrder, returns Point*8
p = p.multiply(jubjub_CURVE.h);
if (p.equals(jubjub.Point.ZERO))
throw new Error('Point has small order');
return p;
}
// No secret data is leaked here at all.
// It operates over public data:
// const G_SPEND = jubjub.findGroupHash(Uint8Array.of(), utf8ToBytes('Item_G_'));
export function jubjub_findGroupHash(m, personalization) {
const tag = concatBytes(m, Uint8Array.of(0));
const hashes = [];
for (let i = 0; i < 256; i++) {
tag[tag.length - 1] = i;
try {
hashes.push(jubjub_groupHash(tag, personalization));
}
catch (e) { }
}
if (!hashes.length)
throw new Error('findGroupHash tag overflow');
return hashes[0];
}
// Pasta curves. See [Spec](https://o1-labs.github.io/proof-systems/specs/pasta.html).
export const pasta_p = BigInt('0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001');
export const pasta_q = BigInt('0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001');
/**
* @deprecated
*/
export const pallas = weierstrass({
a: BigInt(0),
b: BigInt(5),
Fp: Field(pasta_p),
n: pasta_q,
Gx: mod(BigInt(-1), pasta_p),
Gy: BigInt(2),
h: BigInt(1),
hash: sha256,
});
/**
* @deprecated
*/
export const vesta = weierstrass({
a: BigInt(0),
b: BigInt(5),
Fp: Field(pasta_q),
n: pasta_p,
Gx: mod(BigInt(-1), pasta_q),
Gy: BigInt(2),
h: BigInt(1),
hash: sha256,
});
//# sourceMappingURL=misc.js.map

View File

@@ -0,0 +1,76 @@
'use strict'
const bench = require('fastbench')
const pino = require('../../')
const fs = require('node:fs')
const dest = fs.createWriteStream('/dev/null')
const plog = pino(dest)
delete require.cache[require.resolve('../../')]
const plogDest = require('../../')(pino.destination('/dev/null'))
delete require.cache[require.resolve('../../')]
const plogAsync = require('../../')(pino.destination({ dest: '/dev/null', sync: false }))
const deep = require('../../package.json')
deep.deep = JSON.parse(JSON.stringify(deep))
deep.deep.deep = JSON.parse(JSON.stringify(deep))
const longStr = JSON.stringify(deep)
const max = 10
const run = bench([
function benchPinoLongString (cb) {
for (var i = 0; i < max; i++) {
plog.info(longStr)
}
setImmediate(cb)
},
function benchPinoDestLongString (cb) {
for (var i = 0; i < max; i++) {
plogDest.info(longStr)
}
setImmediate(cb)
},
function benchPinoAsyncLongString (cb) {
for (var i = 0; i < max; i++) {
plogAsync.info(longStr)
}
setImmediate(cb)
},
function benchPinoDeepObj (cb) {
for (var i = 0; i < max; i++) {
plog.info(deep)
}
setImmediate(cb)
},
function benchPinoDestDeepObj (cb) {
for (var i = 0; i < max; i++) {
plogDest.info(deep)
}
setImmediate(cb)
},
function benchPinoAsyncDeepObj (cb) {
for (var i = 0; i < max; i++) {
plogAsync.info(deep)
}
setImmediate(cb)
},
function benchPinoInterpolateDeep (cb) {
for (var i = 0; i < max; i++) {
plog.info('hello %j', deep)
}
setImmediate(cb)
},
function benchPinoDestInterpolateDeep (cb) {
for (var i = 0; i < max; i++) {
plogDest.info('hello %j', deep)
}
setImmediate(cb)
},
function benchPinoAsyncInterpolateDeep (cb) {
for (var i = 0; i < max; i++) {
plogAsync.info('hello %j', deep)
}
setImmediate(cb)
}
], 1000)
run(run)

View File

@@ -0,0 +1,891 @@
/**
* @fileoverview Restrict usage of specified node imports.
* @author Guy Ellis
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Format import names for error messages.
* @param {string[]} importNames The import names to format.
* @returns {string} The formatted import names.
*/
function formatImportNames(importNames) {
return new Intl.ListFormat("en-US").format(
importNames.map(name => `'${name}'`),
);
}
/**
* Returns "is" or "are" based on the number of import names.
* @param {string[]} importNames The import names to check.
* @returns {string} "is" if one import name, otherwise "are".
*/
function isOrAre(importNames) {
return importNames.length === 1 ? "is" : "are";
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const ignore = require("ignore");
const arrayOfStringsOrObjects = {
type: "array",
items: {
anyOf: [
{ type: "string" },
{
type: "object",
properties: {
name: { type: "string" },
message: {
type: "string",
minLength: 1,
},
importNames: {
type: "array",
items: {
type: "string",
},
},
allowImportNames: {
type: "array",
items: {
type: "string",
},
},
allowTypeImports: {
type: "boolean",
description:
"Whether to allow type-only imports for a path.",
},
},
additionalProperties: false,
required: ["name"],
not: { required: ["importNames", "allowImportNames"] },
},
],
},
uniqueItems: true,
};
const arrayOfStringsOrObjectPatterns = {
anyOf: [
{
type: "array",
items: {
type: "string",
},
uniqueItems: true,
},
{
type: "array",
items: {
type: "object",
properties: {
importNames: {
type: "array",
items: {
type: "string",
},
minItems: 1,
uniqueItems: true,
},
allowImportNames: {
type: "array",
items: {
type: "string",
},
minItems: 1,
uniqueItems: true,
},
group: {
type: "array",
items: {
type: "string",
},
minItems: 1,
uniqueItems: true,
},
regex: {
type: "string",
},
importNamePattern: {
type: "string",
},
allowImportNamePattern: {
type: "string",
},
message: {
type: "string",
minLength: 1,
},
caseSensitive: {
type: "boolean",
},
allowTypeImports: {
type: "boolean",
description:
"Whether to allow type-only imports for a pattern.",
},
},
additionalProperties: false,
not: {
anyOf: [
{ required: ["importNames", "allowImportNames"] },
{
required: [
"importNamePattern",
"allowImportNamePattern",
],
},
{ required: ["importNames", "allowImportNamePattern"] },
{ required: ["importNamePattern", "allowImportNames"] },
{
required: [
"allowImportNames",
"allowImportNamePattern",
],
},
],
},
oneOf: [{ required: ["group"] }, { required: ["regex"] }],
},
uniqueItems: true,
},
],
};
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Disallow specified modules when loaded by `import`",
dialects: ["JavaScript", "TypeScript"],
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-restricted-imports",
},
messages: {
path: "'{{importSource}}' import is restricted from being used.",
pathWithCustomMessage:
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
"'{{importSource}}' import is restricted from being used. {{customMessage}}",
patterns:
"'{{importSource}}' import is restricted from being used by a pattern.",
patternWithCustomMessage:
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
"'{{importSource}}' import is restricted from being used by a pattern. {{customMessage}}",
patternAndImportName:
"'{{importName}}' import from '{{importSource}}' is restricted from being used by a pattern.",
patternAndImportNameWithCustomMessage:
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
"'{{importName}}' import from '{{importSource}}' is restricted from being used by a pattern. {{customMessage}}",
patternAndEverything:
"* import is invalid because {{importNames}} from '{{importSource}}' {{isOrAre}} restricted from being used by a pattern.",
patternAndEverythingWithRegexImportName:
"* import is invalid because import name matching '{{importNames}}' pattern from '{{importSource}}' is restricted from being used.",
patternAndEverythingWithCustomMessage:
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
"* import is invalid because {{importNames}} from '{{importSource}}' {{isOrAre}} restricted from being used by a pattern. {{customMessage}}",
patternAndEverythingWithRegexImportNameAndCustomMessage:
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
"* import is invalid because import name matching '{{importNames}}' pattern from '{{importSource}}' is restricted from being used. {{customMessage}}",
everything:
"* import is invalid because {{importNames}} from '{{importSource}}' {{isOrAre}} restricted.",
everythingWithCustomMessage:
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
"* import is invalid because {{importNames}} from '{{importSource}}' {{isOrAre}} restricted. {{customMessage}}",
importName:
"'{{importName}}' import from '{{importSource}}' is restricted.",
importNameWithCustomMessage:
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
"'{{importName}}' import from '{{importSource}}' is restricted. {{customMessage}}",
allowedImportName:
"'{{importName}}' import from '{{importSource}}' is restricted because only {{allowedImportNames}} {{isOrAre}} allowed.",
allowedImportNameWithCustomMessage:
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
"'{{importName}}' import from '{{importSource}}' is restricted because only {{allowedImportNames}} {{isOrAre}} allowed. {{customMessage}}",
everythingWithAllowImportNames:
"* import is invalid because only {{allowedImportNames}} from '{{importSource}}' {{isOrAre}} allowed.",
everythingWithAllowImportNamesAndCustomMessage:
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
"* import is invalid because only {{allowedImportNames}} from '{{importSource}}' {{isOrAre}} allowed. {{customMessage}}",
allowedImportNamePattern:
"'{{importName}}' import from '{{importSource}}' is restricted because only imports that match the pattern '{{allowedImportNamePattern}}' are allowed from '{{importSource}}'.",
allowedImportNamePatternWithCustomMessage:
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
"'{{importName}}' import from '{{importSource}}' is restricted because only imports that match the pattern '{{allowedImportNamePattern}}' are allowed from '{{importSource}}'. {{customMessage}}",
everythingWithAllowedImportNamePattern:
"* import is invalid because only imports that match the pattern '{{allowedImportNamePattern}}' from '{{importSource}}' are allowed.",
everythingWithAllowedImportNamePatternWithCustomMessage:
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
"* import is invalid because only imports that match the pattern '{{allowedImportNamePattern}}' from '{{importSource}}' are allowed. {{customMessage}}",
},
schema: {
anyOf: [
arrayOfStringsOrObjects,
{
type: "array",
items: [
{
type: "object",
properties: {
paths: arrayOfStringsOrObjects,
patterns: arrayOfStringsOrObjectPatterns,
},
additionalProperties: false,
},
],
additionalItems: false,
},
],
},
},
create(context) {
const sourceCode = context.sourceCode;
const options = Array.isArray(context.options) ? context.options : [];
const isPathAndPatternsObject =
typeof options[0] === "object" &&
(Object.hasOwn(options[0], "paths") ||
Object.hasOwn(options[0], "patterns"));
const restrictedPaths =
(isPathAndPatternsObject ? options[0].paths : context.options) ||
[];
const groupedRestrictedPaths = restrictedPaths.reduce(
(memo, importSource) => {
const path =
typeof importSource === "string"
? importSource
: importSource.name;
if (!memo[path]) {
memo[path] = [];
}
if (typeof importSource === "string") {
memo[path].push({});
} else {
memo[path].push({
message: importSource.message,
importNames: importSource.importNames,
allowImportNames: importSource.allowImportNames,
allowTypeImports: importSource.allowTypeImports,
});
}
return memo;
},
Object.create(null),
);
// Handle patterns too, either as strings or groups
let restrictedPatterns =
(isPathAndPatternsObject ? options[0].patterns : []) || [];
// standardize to array of objects if we have an array of strings
if (
restrictedPatterns.length > 0 &&
typeof restrictedPatterns[0] === "string"
) {
restrictedPatterns = [{ group: restrictedPatterns }];
}
// relative paths are supported for this rule
const restrictedPatternGroups = restrictedPatterns.map(
({
group,
regex,
message,
caseSensitive,
importNames,
importNamePattern,
allowImportNames,
allowImportNamePattern,
allowTypeImports,
}) => ({
...(group
? {
matcher: ignore({
allowRelativePaths: true,
ignorecase: !caseSensitive,
}).add(group),
}
: {}),
...(typeof regex === "string"
? {
regexMatcher: new RegExp(
regex,
caseSensitive ? "u" : "iu",
),
}
: {}),
customMessage: message,
importNames,
importNamePattern,
allowImportNames,
allowImportNamePattern,
allowTypeImports,
}),
);
// if no imports are restricted we don't need to check
if (
Object.keys(restrictedPaths).length === 0 &&
restrictedPatternGroups.length === 0
) {
return {};
}
/**
* Check if the node is a type-only import
* @param {ASTNode} node The node to check
* @returns {boolean} Whether the node is a type-only import
*/
function isTypeOnlyImport(node) {
return (
node.importKind === "type" ||
(node.specifiers?.length > 0 &&
node.specifiers.every(
specifier => specifier.importKind === "type",
))
);
}
/**
* Check if a specifier is type-only
* @param {ASTNode} specifier The specifier to check
* @returns {boolean} Whether the specifier is type-only
*/
function isTypeOnlySpecifier(specifier) {
return (
specifier.importKind === "type" ||
specifier.exportKind === "type"
);
}
/**
* Check if the node is a type-only export
* @param {ASTNode} node The node to check
* @returns {boolean} Whether the node is a type-only export
*/
function isTypeOnlyExport(node) {
return (
node.exportKind === "type" ||
(node.specifiers?.length > 0 &&
node.specifiers.every(
specifier => specifier.exportKind === "type",
))
);
}
/**
* Report a restricted path.
* @param {string} importSource path of the import
* @param {Map<string,Object[]>} importNames Map of import names that are being imported
* @param {node} node representing the restricted path reference
* @returns {void}
* @private
*/
function checkRestrictedPathAndReport(importSource, importNames, node) {
if (!Object.hasOwn(groupedRestrictedPaths, importSource)) {
return;
}
groupedRestrictedPaths[importSource].forEach(
restrictedPathEntry => {
const customMessage = restrictedPathEntry.message;
const restrictedImportNames =
restrictedPathEntry.importNames;
const allowedImportNames =
restrictedPathEntry.allowImportNames;
const allowTypeImports =
restrictedPathEntry.allowTypeImports;
// Skip if this is a type-only import and it's allowed for this specific entry
if (
allowTypeImports &&
(node.type === "ImportDeclaration" ||
node.type === "TSImportEqualsDeclaration") &&
isTypeOnlyImport(node)
) {
return;
}
// Skip if this is a type-only export and it's allowed for this specific entry
if (
allowTypeImports &&
(node.type === "ExportNamedDeclaration" ||
node.type === "ExportAllDeclaration") &&
isTypeOnlyExport(node)
) {
return;
}
if (!restrictedImportNames && !allowedImportNames) {
context.report({
node,
messageId: customMessage
? "pathWithCustomMessage"
: "path",
data: {
importSource,
customMessage,
},
});
return;
}
importNames.forEach((specifiers, importName) => {
if (importName === "*") {
const [specifier] = specifiers;
if (restrictedImportNames) {
context.report({
node,
messageId: customMessage
? "everythingWithCustomMessage"
: "everything",
loc: specifier.loc,
data: {
importSource,
importNames: formatImportNames(
restrictedImportNames,
),
isOrAre: isOrAre(restrictedImportNames),
customMessage,
},
});
} else if (allowedImportNames) {
context.report({
node,
messageId: customMessage
? "everythingWithAllowImportNamesAndCustomMessage"
: "everythingWithAllowImportNames",
loc: specifier.loc,
data: {
importSource,
allowedImportNames:
formatImportNames(
allowedImportNames,
),
isOrAre: isOrAre(allowedImportNames),
customMessage,
},
});
}
return;
}
if (
restrictedImportNames &&
restrictedImportNames.includes(importName)
) {
specifiers.forEach(specifier => {
// Skip if this is a type-only import specifier and type imports are allowed
if (
allowTypeImports &&
isTypeOnlySpecifier(specifier.specifier)
) {
return;
}
context.report({
node,
messageId: customMessage
? "importNameWithCustomMessage"
: "importName",
loc: specifier.loc,
data: {
importSource,
customMessage,
importName,
},
});
});
}
if (
allowedImportNames &&
!allowedImportNames.includes(importName)
) {
specifiers.forEach(specifier => {
// Skip if this is a type-only import specifier and type imports are allowed
if (
allowTypeImports &&
isTypeOnlySpecifier(specifier.specifier)
) {
return;
}
context.report({
node,
loc: specifier.loc,
messageId: customMessage
? "allowedImportNameWithCustomMessage"
: "allowedImportName",
data: {
importSource,
customMessage,
importName,
allowedImportNames:
formatImportNames(
allowedImportNames,
),
isOrAre: isOrAre(allowedImportNames),
},
});
});
}
});
},
);
}
/**
* Report a restricted path specifically for patterns.
* @param {node} node representing the restricted path reference
* @param {Object} group contains an Ignore instance for paths, the customMessage to show on failure,
* and any restricted import names that have been specified in the config
* @param {Map<string,Object[]>} importNames Map of import names that are being imported
* @param {string} importSource the import source string
* @returns {void}
* @private
*/
function reportPathForPatterns(node, group, importNames, importSource) {
// Skip if this is a type-only import and it's allowed
if (
group.allowTypeImports &&
(node.type === "ImportDeclaration" ||
node.type === "TSImportEqualsDeclaration") &&
isTypeOnlyImport(node)
) {
return;
}
// Skip if this is a type-only export and it's allowed
if (
group.allowTypeImports &&
(node.type === "ExportNamedDeclaration" ||
node.type === "ExportAllDeclaration") &&
isTypeOnlyExport(node)
) {
return;
}
const customMessage = group.customMessage;
const restrictedImportNames = group.importNames;
const restrictedImportNamePattern = group.importNamePattern
? new RegExp(group.importNamePattern, "u")
: null;
const allowedImportNames = group.allowImportNames;
const allowedImportNamePattern = group.allowImportNamePattern
? new RegExp(group.allowImportNamePattern, "u")
: null;
/**
* If we are not restricting to any specific import names and just the pattern itself,
* report the error and move on
*/
if (
!restrictedImportNames &&
!allowedImportNames &&
!restrictedImportNamePattern &&
!allowedImportNamePattern
) {
context.report({
node,
messageId: customMessage
? "patternWithCustomMessage"
: "patterns",
data: {
importSource,
customMessage,
},
});
return;
}
importNames.forEach((specifiers, importName) => {
if (importName === "*") {
const [specifier] = specifiers;
if (restrictedImportNames) {
context.report({
node,
messageId: customMessage
? "patternAndEverythingWithCustomMessage"
: "patternAndEverything",
loc: specifier.loc,
data: {
importSource,
importNames: formatImportNames(
restrictedImportNames,
),
isOrAre: isOrAre(restrictedImportNames),
customMessage,
},
});
} else if (allowedImportNames) {
context.report({
node,
messageId: customMessage
? "everythingWithAllowImportNamesAndCustomMessage"
: "everythingWithAllowImportNames",
loc: specifier.loc,
data: {
importSource,
allowedImportNames:
formatImportNames(allowedImportNames),
isOrAre: isOrAre(allowedImportNames),
customMessage,
},
});
} else if (allowedImportNamePattern) {
context.report({
node,
messageId: customMessage
? "everythingWithAllowedImportNamePatternWithCustomMessage"
: "everythingWithAllowedImportNamePattern",
loc: specifier.loc,
data: {
importSource,
allowedImportNamePattern,
customMessage,
},
});
} else {
context.report({
node,
messageId: customMessage
? "patternAndEverythingWithRegexImportNameAndCustomMessage"
: "patternAndEverythingWithRegexImportName",
loc: specifier.loc,
data: {
importSource,
importNames: restrictedImportNamePattern,
customMessage,
},
});
}
return;
}
if (
(restrictedImportNames &&
restrictedImportNames.includes(importName)) ||
(restrictedImportNamePattern &&
restrictedImportNamePattern.test(importName))
) {
specifiers.forEach(specifier => {
// Skip if this is a type-only import specifier and type imports are allowed
if (
group.allowTypeImports &&
isTypeOnlySpecifier(specifier.specifier)
) {
return;
}
context.report({
node,
messageId: customMessage
? "patternAndImportNameWithCustomMessage"
: "patternAndImportName",
loc: specifier.loc,
data: {
importSource,
customMessage,
importName,
},
});
});
}
if (
allowedImportNames &&
!allowedImportNames.includes(importName)
) {
specifiers.forEach(specifier => {
// Skip if this is a type-only import specifier and type imports are allowed
if (
group.allowTypeImports &&
isTypeOnlySpecifier(specifier.specifier)
) {
return;
}
context.report({
node,
messageId: customMessage
? "allowedImportNameWithCustomMessage"
: "allowedImportName",
loc: specifier.loc,
data: {
importSource,
customMessage,
importName,
allowedImportNames:
formatImportNames(allowedImportNames),
isOrAre: isOrAre(allowedImportNames),
},
});
});
} else if (
allowedImportNamePattern &&
!allowedImportNamePattern.test(importName)
) {
specifiers.forEach(specifier => {
// Skip if this is a type-only import specifier and type imports are allowed
if (
group.allowTypeImports &&
isTypeOnlySpecifier(specifier.specifier)
) {
return;
}
context.report({
node,
messageId: customMessage
? "allowedImportNamePatternWithCustomMessage"
: "allowedImportNamePattern",
loc: specifier.loc,
data: {
importSource,
customMessage,
importName,
allowedImportNamePattern,
},
});
});
}
});
}
/**
* Check if the given importSource is restricted by a pattern.
* @param {string} importSource path of the import
* @param {Object} group contains a Ignore instance for paths, and the customMessage to show if it fails
* @returns {boolean} whether the variable is a restricted pattern or not
* @private
*/
function isRestrictedPattern(importSource, group) {
return group.regexMatcher
? group.regexMatcher.test(importSource)
: group.matcher.ignores(importSource);
}
/**
* Checks a node to see if any problems should be reported.
* @param {ASTNode} node The node to check.
* @returns {void}
* @private
*/
function checkNode(node) {
const importSource = node.source.value.trim();
const importNames = new Map();
if (node.type === "ExportAllDeclaration") {
const starToken = sourceCode.getFirstToken(node, 1);
importNames.set("*", [{ loc: starToken.loc }]);
} else if (node.specifiers) {
for (const specifier of node.specifiers) {
let name;
const specifierData = { loc: specifier.loc, specifier };
if (specifier.type === "ImportDefaultSpecifier") {
name = "default";
} else if (specifier.type === "ImportNamespaceSpecifier") {
name = "*";
} else if (specifier.imported) {
name = astUtils.getModuleExportName(specifier.imported);
} else if (specifier.local) {
name = astUtils.getModuleExportName(specifier.local);
}
if (typeof name === "string") {
if (importNames.has(name)) {
importNames.get(name).push(specifierData);
} else {
importNames.set(name, [specifierData]);
}
}
}
}
checkRestrictedPathAndReport(importSource, importNames, node);
restrictedPatternGroups.forEach(group => {
if (isRestrictedPattern(importSource, group)) {
reportPathForPatterns(
node,
group,
importNames,
importSource,
);
}
});
}
return {
ImportDeclaration: checkNode,
ExportNamedDeclaration(node) {
if (node.source) {
checkNode(node);
}
},
ExportAllDeclaration: checkNode,
// Add support for TypeScript import equals declarations
TSImportEqualsDeclaration(node) {
if (node.moduleReference.type === "TSExternalModuleReference") {
const importSource = node.moduleReference.expression.value;
const importNames = new Map();
// Use existing logic with the actual node
checkRestrictedPathAndReport(
importSource,
importNames,
node,
);
restrictedPatternGroups.forEach(group => {
if (isRestrictedPattern(importSource, group)) {
reportPathForPatterns(
node,
group,
importNames,
importSource,
);
}
});
}
},
};
},
};

View File

@@ -0,0 +1,117 @@
/**
* License for programmatically and manually incorporated
* documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc
*
* Copyright Node.js contributors. All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
// NOTE: These definitions support Node.js and TypeScript 5.6.
// Reference required TypeScript libraries:
/// <reference lib="es2020" />
/// <reference lib="esnext.disposable" />
// TypeScript library polyfills required for TypeScript <=5.6:
/// <reference path="./compatibility/float16array.d.ts" />
// Definitions for Node.js modules specific to TypeScript <=5.6:
/// <reference path="./globals.typedarray.d.ts" />
/// <reference path="./buffer.buffer.d.ts" />
// Definitions for Node.js modules that are not specific to any version of TypeScript:
/// <reference path="../globals.d.ts" />
/// <reference path="../web-globals/abortcontroller.d.ts" />
/// <reference path="../web-globals/blob.d.ts" />
/// <reference path="../web-globals/console.d.ts" />
/// <reference path="../web-globals/crypto.d.ts" />
/// <reference path="../web-globals/domexception.d.ts" />
/// <reference path="../web-globals/encoding.d.ts" />
/// <reference path="../web-globals/events.d.ts" />
/// <reference path="../web-globals/fetch.d.ts" />
/// <reference path="../web-globals/importmeta.d.ts" />
/// <reference path="../web-globals/messaging.d.ts" />
/// <reference path="../web-globals/navigator.d.ts" />
/// <reference path="../web-globals/performance.d.ts" />
/// <reference path="../web-globals/storage.d.ts" />
/// <reference path="../web-globals/streams.d.ts" />
/// <reference path="../web-globals/timers.d.ts" />
/// <reference path="../web-globals/url.d.ts" />
/// <reference path="../assert.d.ts" />
/// <reference path="../assert/strict.d.ts" />
/// <reference path="../async_hooks.d.ts" />
/// <reference path="../buffer.d.ts" />
/// <reference path="../child_process.d.ts" />
/// <reference path="../cluster.d.ts" />
/// <reference path="../console.d.ts" />
/// <reference path="../constants.d.ts" />
/// <reference path="../crypto.d.ts" />
/// <reference path="../dgram.d.ts" />
/// <reference path="../diagnostics_channel.d.ts" />
/// <reference path="../dns.d.ts" />
/// <reference path="../dns/promises.d.ts" />
/// <reference path="../domain.d.ts" />
/// <reference path="../events.d.ts" />
/// <reference path="../ffi.d.ts" />
/// <reference path="../fs.d.ts" />
/// <reference path="../fs/promises.d.ts" />
/// <reference path="../http.d.ts" />
/// <reference path="../http2.d.ts" />
/// <reference path="../https.d.ts" />
/// <reference path="../inspector.d.ts" />
/// <reference path="../inspector.generated.d.ts" />
/// <reference path="../inspector/promises.d.ts" />
/// <reference path="../module.d.ts" />
/// <reference path="../net.d.ts" />
/// <reference path="../os.d.ts" />
/// <reference path="../path.d.ts" />
/// <reference path="../path/posix.d.ts" />
/// <reference path="../path/win32.d.ts" />
/// <reference path="../perf_hooks.d.ts" />
/// <reference path="../process.d.ts" />
/// <reference path="../punycode.d.ts" />
/// <reference path="../querystring.d.ts" />
/// <reference path="../quic.d.ts" />
/// <reference path="../readline.d.ts" />
/// <reference path="../readline/promises.d.ts" />
/// <reference path="../repl.d.ts" />
/// <reference path="../sea.d.ts" />
/// <reference path="../sqlite.d.ts" />
/// <reference path="../stream.d.ts" />
/// <reference path="../stream/consumers.d.ts" />
/// <reference path="../stream/iter.d.ts" />
/// <reference path="../stream/promises.d.ts" />
/// <reference path="../stream/web.d.ts" />
/// <reference path="../string_decoder.d.ts" />
/// <reference path="../test.d.ts" />
/// <reference path="../test/reporters.d.ts" />
/// <reference path="../timers.d.ts" />
/// <reference path="../timers/promises.d.ts" />
/// <reference path="../tls.d.ts" />
/// <reference path="../trace_events.d.ts" />
/// <reference path="../tty.d.ts" />
/// <reference path="../url.d.ts" />
/// <reference path="../util.d.ts" />
/// <reference path="../util/types.d.ts" />
/// <reference path="../v8.d.ts" />
/// <reference path="../vm.d.ts" />
/// <reference path="../wasi.d.ts" />
/// <reference path="../worker_threads.d.ts" />
/// <reference path="../zlib.d.ts" />
/// <reference path="../zlib/iter.d.ts" />

View File

@@ -0,0 +1,75 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
const getESLintCoreRule_1 = require("../util/getESLintCoreRule");
const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('no-invalid-this');
const defaultOptions = [{ capIsConstructor: true }];
exports.default = (0, util_1.createRule)({
name: 'no-invalid-this',
meta: {
type: 'suggestion',
defaultOptions,
docs: {
description: 'Disallow `this` keywords outside of classes or class-like objects',
extendsBaseRule: true,
},
hasSuggestions: baseRule.meta.hasSuggestions,
messages: baseRule.meta.messages,
schema: baseRule.meta.schema,
},
defaultOptions,
create(context) {
const rules = baseRule.create(context);
/**
* Since function definitions can be nested we use a stack storing if "this" is valid in the current context.
*
* Example:
*
* function a(this: number) { // valid "this"
* function b() {
* console.log(this); // invalid "this"
* }
* }
*
* When parsing the function declaration of "a" the stack will be: [true]
* When parsing the function declaration of "b" the stack will be: [true, false]
*/
const thisIsValidStack = [];
return {
...rules,
AccessorProperty() {
thisIsValidStack.push(true);
},
'AccessorProperty:exit'() {
thisIsValidStack.pop();
},
FunctionDeclaration(node) {
thisIsValidStack.push(node.params.some(param => param.type === utils_1.AST_NODE_TYPES.Identifier && param.name === 'this'));
},
'FunctionDeclaration:exit'() {
thisIsValidStack.pop();
},
FunctionExpression(node) {
thisIsValidStack.push(node.params.some(param => param.type === utils_1.AST_NODE_TYPES.Identifier && param.name === 'this'));
},
'FunctionExpression:exit'() {
thisIsValidStack.pop();
},
PropertyDefinition() {
thisIsValidStack.push(true);
},
'PropertyDefinition:exit'() {
thisIsValidStack.pop();
},
ThisExpression(node) {
const thisIsValidHere = thisIsValidStack[thisIsValidStack.length - 1];
if (thisIsValidHere) {
return;
}
// baseRule's work
rules.ThisExpression(node);
},
};
},
});

View File

@@ -0,0 +1,75 @@
{
"name": "@typescript-eslint/visitor-keys",
"version": "8.67.0",
"description": "Visitor keys used to help traverse the TypeScript-ESTree AST",
"files": [
"dist",
"!**/*.tsbuildinfo"
],
"type": "commonjs",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./package.json": "./package.json"
},
"types": "./dist/index.d.ts",
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"repository": {
"type": "git",
"url": "https://github.com/typescript-eslint/typescript-eslint.git",
"directory": "packages/visitor-keys"
},
"bugs": {
"url": "https://github.com/typescript-eslint/typescript-eslint/issues"
},
"homepage": "https://typescript-eslint.io",
"license": "MIT",
"keywords": [
"eslint",
"typescript",
"estree"
],
"dependencies": {
"eslint-visitor-keys": "^5.0.0",
"@typescript-eslint/types": "8.67.0"
},
"devDependencies": {
"@typescript/native": "npm:typescript@^7.0.2",
"@vitest/coverage-v8": "^4.0.18",
"eslint": "^10.0.0",
"rimraf": "^5.0.10",
"typescript": ">=4.8.4 <6.1.0",
"vitest": "^4.0.18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"nx": {
"name": "visitor-keys",
"includedScripts": [
"clean"
],
"targets": {
"lint": {
"command": "eslint"
},
"typecheck:tsgo": {},
"attw-check": {}
}
},
"scripts": {
"build": "pnpm exec nx build",
"clean": "rimraf dist/ coverage/",
"format": "pnpm -w run format",
"lint": "pnpm -w exec nx lint",
"test": "pnpm -w exec nx test",
"typecheck": "pnpm -w exec nx typecheck",
"typecheck:tsgo": "pnpm -w exec nx typecheck:tsgo",
"attw-check": "pnpm -w exec nx attw-check"
}
}

View File

@@ -0,0 +1,38 @@
"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 __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.typescriptVersionIsAtLeast = exports.getModifiers = exports.getDecorators = void 0;
__exportStar(require("./builtinSymbolLikes"), exports);
__exportStar(require("./containsAllTypesByName"), exports);
__exportStar(require("./getConstrainedTypeAtLocation"), exports);
__exportStar(require("./getContextualType"), exports);
__exportStar(require("./getDeclaration"), exports);
__exportStar(require("./getSourceFileOfNode"), exports);
__exportStar(require("./getTypeName"), exports);
__exportStar(require("./isSymbolFromDefaultLibrary"), exports);
__exportStar(require("./isTypeBrandedLiteralLike"), exports);
__exportStar(require("./isTypeReadonly"), exports);
__exportStar(require("./isUnsafeAssignment"), exports);
__exportStar(require("./predicates"), exports);
__exportStar(require("./propertyTypes"), exports);
__exportStar(require("./requiresQuoting"), exports);
__exportStar(require("./typeFlagUtils"), exports);
__exportStar(require("./TypeOrValueSpecifier"), exports);
__exportStar(require("./discriminateAnyType"), exports);
var typescript_estree_1 = require("@typescript-eslint/typescript-estree");
Object.defineProperty(exports, "getDecorators", { enumerable: true, get: function () { return typescript_estree_1.getDecorators; } });
Object.defineProperty(exports, "getModifiers", { enumerable: true, get: function () { return typescript_estree_1.getModifiers; } });
Object.defineProperty(exports, "typescriptVersionIsAtLeast", { enumerable: true, get: function () { return typescript_estree_1.typescriptVersionIsAtLeast; } });