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 @@
export { _lt as lt, _lte as lte, _gt as gt, _gte as gte, _positive as positive, _negative as negative, _nonpositive as nonpositive, _nonnegative as nonnegative, _multipleOf as multipleOf, _maxSize as maxSize, _minSize as minSize, _size as size, _maxLength as maxLength, _minLength as minLength, _length as length, _regex as regex, _lowercase as lowercase, _uppercase as uppercase, _includes as includes, _startsWith as startsWith, _endsWith as endsWith, _property as property, _mime as mime, _overwrite as overwrite, _normalize as normalize, _trim as trim, _toLowerCase as toLowerCase, _toUpperCase as toUpperCase, _slugify as slugify, } from "../core/index.js";

View File

@@ -0,0 +1,78 @@
{
"name": "esquery",
"version": "1.7.0",
"author": "Joel Feenstra <jrfeenst+esquery@gmail.com>",
"contributors": [],
"description": "A query library for ECMAScript AST using a CSS selector like query language.",
"main": "dist/esquery.min.js",
"module": "dist/esquery.esm.min.js",
"files": [
"dist/*.js",
"dist/*.map",
"parser.js",
"license.txt",
"README.md"
],
"nyc": {
"branches": 100,
"lines": 100,
"functions": 100,
"statements": 100,
"reporter": [
"html",
"text"
],
"exclude": [
"parser.js",
"dist",
"tests"
]
},
"scripts": {
"prepublishOnly": "npm run build && npm test",
"build:parser": "rm parser.js && pegjs --cache --format umd -o \"parser.js\" \"grammar.pegjs\"",
"build:browser": "rollup -c",
"build": "npm run build:parser && npm run build:browser",
"mocha": "mocha --require chai/register-assert --require @babel/register tests",
"test": "nyc npm run mocha && npm run lint",
"test:ci": "npm run mocha",
"lint": "eslint ."
},
"repository": {
"type": "git",
"url": "https://github.com/estools/esquery.git"
},
"bugs": "https://github.com/estools/esquery/issues",
"homepage": "https://github.com/estools/esquery/",
"keywords": [
"ast",
"ecmascript",
"javascript",
"query"
],
"devDependencies": {
"@babel/core": "^7.9.0",
"@babel/preset-env": "^7.9.5",
"@babel/register": "^7.9.0",
"@rollup/plugin-commonjs": "^11.1.0",
"@rollup/plugin-json": "^4.0.2",
"@rollup/plugin-node-resolve": "^7.1.3",
"babel-plugin-transform-es2017-object-entries": "0.0.5",
"chai": "4.2.0",
"eslint": "^6.8.0",
"esprima": "~4.0.1",
"mocha": "7.1.1",
"nyc": "^15.0.1",
"pegjs": "~0.10.0",
"rollup": "^1.32.1",
"rollup-plugin-babel": "^4.4.0",
"rollup-plugin-terser": "^5.3.0"
},
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10"
},
"dependencies": {
"estraverse": "^5.1.0"
}
}

View File

@@ -0,0 +1,281 @@
/**
* Utilities for hex, bytes, CSPRNG.
* @module
*/
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from `crypto` to `cryptoNode`, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
import { crypto } from '@noble/hashes/crypto';
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
export function isBytes(a) {
return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is positive integer. */
export function anumber(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error('positive integer expected, got ' + n);
}
/** Asserts something is Uint8Array. */
export function abytes(b, ...lengths) {
if (!isBytes(b))
throw new Error('Uint8Array expected');
if (lengths.length > 0 && !lengths.includes(b.length))
throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
/** Asserts something is hash */
export function ahash(h) {
if (typeof h !== 'function' || typeof h.create !== 'function')
throw new Error('Hash should be wrapped by utils.createHasher');
anumber(h.outputLen);
anumber(h.blockLen);
}
/** Asserts a hash instance has not been destroyed / finished */
export function aexists(instance, checkFinished = true) {
if (instance.destroyed)
throw new Error('Hash instance has been destroyed');
if (checkFinished && instance.finished)
throw new Error('Hash#digest() has already been called');
}
/** Asserts output is properly-sized byte array */
export function aoutput(out, instance) {
abytes(out);
const min = instance.outputLen;
if (out.length < min) {
throw new Error('digestInto() expects output buffer of length at least ' + min);
}
}
/** Cast u8 / u16 / u32 to u8. */
export function u8(arr) {
return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Cast u8 / u16 / u32 to u32. */
export function u32(arr) {
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
export function clean(...arrays) {
for (let i = 0; i < arrays.length; i++) {
arrays[i].fill(0);
}
}
/** Create DataView of an array for easy byte-level manipulation. */
export function createView(arr) {
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** The rotate right (circular right shift) operation for uint32 */
export function rotr(word, shift) {
return (word << (32 - shift)) | (word >>> shift);
}
/** The rotate left (circular left shift) operation for uint32 */
export function rotl(word, shift) {
return (word << shift) | ((word >>> (32 - shift)) >>> 0);
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
/** The byte swap operation for uint32 */
export function byteSwap(word) {
return (((word << 24) & 0xff000000) |
((word << 8) & 0xff0000) |
((word >>> 8) & 0xff00) |
((word >>> 24) & 0xff));
}
/** Conditionally byte swap if on a big-endian platform */
export const swap8IfBE = isLE
? (n) => n
: (n) => byteSwap(n);
/** @deprecated */
export const byteSwapIfBE = swap8IfBE;
/** In place byte swap for Uint32Array */
export function byteSwap32(arr) {
for (let i = 0; i < arr.length; i++) {
arr[i] = byteSwap(arr[i]);
}
return arr;
}
export const swap32IfBE = isLE
? (u) => u
: byteSwap32;
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
const hasHexBuiltin = /* @__PURE__ */ (() =>
// @ts-ignore
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
// Array where index 0xf0 (240) is mapped to string 'f0'
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
* Convert byte array to hex string. Uses built-in function, when available.
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
*/
export function bytesToHex(bytes) {
abytes(bytes);
// @ts-ignore
if (hasHexBuiltin)
return bytes.toHex();
// pre-caching improves the speed 6x
let hex = '';
for (let i = 0; i < bytes.length; i++) {
hex += hexes[bytes[i]];
}
return hex;
}
// We use optimized technique to convert hex string to byte array
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
function asciiToBase16(ch) {
if (ch >= asciis._0 && ch <= asciis._9)
return ch - asciis._0; // '2' => 50-48
if (ch >= asciis.A && ch <= asciis.F)
return ch - (asciis.A - 10); // 'B' => 66-(65-10)
if (ch >= asciis.a && ch <= asciis.f)
return ch - (asciis.a - 10); // 'b' => 98-(97-10)
return;
}
/**
* Convert hex string to byte array. Uses built-in function, when available.
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
*/
export function hexToBytes(hex) {
if (typeof hex !== 'string')
throw new Error('hex string expected, got ' + typeof hex);
// @ts-ignore
if (hasHexBuiltin)
return Uint8Array.fromHex(hex);
const hl = hex.length;
const al = hl / 2;
if (hl % 2)
throw new Error('hex string expected, got unpadded hex of length ' + hl);
const array = new Uint8Array(al);
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
const n1 = asciiToBase16(hex.charCodeAt(hi));
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
if (n1 === undefined || n2 === undefined) {
const char = hex[hi] + hex[hi + 1];
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
}
array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
}
return array;
}
/**
* There is no setImmediate in browser and setTimeout is slow.
* Call of async fn will return Promise, which will be fullfiled only on
* next scheduler queue processing step and this is exactly what we need.
*/
export const nextTick = async () => { };
/** Returns control to thread each 'tick' ms to avoid blocking. */
export async function asyncLoop(iters, tick, cb) {
let ts = Date.now();
for (let i = 0; i < iters; i++) {
cb(i);
// Date.now() is not monotonic, so in case if clock goes backwards we return return control too
const diff = Date.now() - ts;
if (diff >= 0 && diff < tick)
continue;
await nextTick();
ts += diff;
}
}
/**
* Converts string to bytes using UTF8 encoding.
* @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
*/
export function utf8ToBytes(str) {
if (typeof str !== 'string')
throw new Error('string expected');
return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
* Converts bytes to string using UTF8 encoding.
* @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
*/
export function bytesToUtf8(bytes) {
return new TextDecoder().decode(bytes);
}
/**
* Normalizes (non-hex) string or Uint8Array to Uint8Array.
* Warning: when Uint8Array is passed, it would NOT get copied.
* Keep in mind for future mutable operations.
*/
export function toBytes(data) {
if (typeof data === 'string')
data = utf8ToBytes(data);
abytes(data);
return data;
}
/**
* Helper for KDFs: consumes uint8array or string.
* When string is passed, does utf8 decoding, using TextDecoder.
*/
export function kdfInputToBytes(data) {
if (typeof data === 'string')
data = utf8ToBytes(data);
abytes(data);
return data;
}
/** Copies several Uint8Arrays into one. */
export function concatBytes(...arrays) {
let sum = 0;
for (let i = 0; i < arrays.length; i++) {
const a = arrays[i];
abytes(a);
sum += a.length;
}
const res = new Uint8Array(sum);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const a = arrays[i];
res.set(a, pad);
pad += a.length;
}
return res;
}
export function checkOpts(defaults, opts) {
if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
throw new Error('options should be object or undefined');
const merged = Object.assign(defaults, opts);
return merged;
}
/** For runtime check if class implements interface */
export class Hash {
}
/** Wraps hash function, creating an interface on top of it */
export function createHasher(hashCons) {
const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
const tmp = hashCons();
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = () => hashCons();
return hashC;
}
export function createOptHasher(hashCons) {
const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
const tmp = hashCons({});
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (opts) => hashCons(opts);
return hashC;
}
export function createXOFer(hashCons) {
const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
const tmp = hashCons({});
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (opts) => hashCons(opts);
return hashC;
}
export const wrapConstructor = createHasher;
export const wrapConstructorWithOpts = createOptHasher;
export const wrapXOFConstructorWithOpts = createXOFer;
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
export function randomBytes(bytesLength = 32) {
if (crypto && typeof crypto.getRandomValues === 'function') {
return crypto.getRandomValues(new Uint8Array(bytesLength));
}
// Legacy Node.js compatibility
if (crypto && typeof crypto.randomBytes === 'function') {
return Uint8Array.from(crypto.randomBytes(bytesLength));
}
throw new Error('crypto.getRandomValues must be defined');
}
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1,101 @@
import { expect, expectTypeOf, test } from "vitest";
import { z } from "zod/v4";
test("nonoptional", () => {
const schema = z.string().nonoptional();
expectTypeOf<typeof schema._input>().toEqualTypeOf<string>();
expectTypeOf<typeof schema._output>().toEqualTypeOf<string>();
const result = schema.safeParse(undefined);
expect(result.success).toBe(false);
expect(result).toMatchInlineSnapshot(`
{
"error": [ZodError: [
{
"expected": "string",
"code": "invalid_type",
"path": [],
"message": "Invalid input: expected string, received undefined"
}
]],
"success": false,
}
`);
});
test("nonoptional with default", () => {
const schema = z.string().optional().nonoptional();
expectTypeOf<typeof schema._input>().toEqualTypeOf<string>();
expectTypeOf<typeof schema._output>().toEqualTypeOf<string>();
const result = schema.safeParse(undefined);
expect(result.success).toBe(false);
expect(result).toMatchInlineSnapshot(`
{
"error": [ZodError: [
{
"code": "invalid_type",
"expected": "nonoptional",
"path": [],
"message": "Invalid input: expected nonoptional, received undefined"
}
]],
"success": false,
}
`);
});
test("nonoptional in object", () => {
const schema = z.object({ hi: z.string().optional().nonoptional() });
expectTypeOf<typeof schema._input>().toEqualTypeOf<{ hi: string }>();
expectTypeOf<typeof schema._output>().toEqualTypeOf<{ hi: string }>();
const r1 = schema.safeParse({ hi: "asdf" });
expect(r1.success).toEqual(true);
const r2 = schema.safeParse({ hi: undefined });
// expect(schema.safeParse({ hi: undefined }).success).toEqual(false);
expect(r2.success).toEqual(false);
expect(r2.error).toMatchInlineSnapshot(`
[ZodError: [
{
"code": "invalid_type",
"expected": "nonoptional",
"path": [
"hi"
],
"message": "Invalid input: expected nonoptional, received undefined"
}
]]
`);
const r3 = schema.safeParse({});
expect(r3.success).toEqual(false);
expect(r3.error).toMatchInlineSnapshot(`
[ZodError: [
{
"code": "invalid_type",
"expected": "nonoptional",
"path": [
"hi"
],
"message": "Invalid input: expected nonoptional, received undefined"
}
]]
`);
});
test("encoding", () => {
const schema = z.string().optional().nonoptional();
expect(z.encode(schema, "hello")).toEqual("hello");
expect(() => z.encode(schema, undefined as any)).toThrowErrorMatchingInlineSnapshot(`
[ZodError: [
{
"code": "invalid_type",
"expected": "nonoptional",
"path": [],
"message": "Invalid input: expected nonoptional, received undefined"
}
]]
`);
});

View File

@@ -0,0 +1,8 @@
/**
* @fileoverview API entrypoint for hfs/core
* @author Nicholas C. Zakas
*/
export { Hfs } from "./hfs.js";
export { Path } from "./path.js";
export * from "./errors.js";

View File

@@ -0,0 +1,188 @@
import type * as TSESTree from './generated/ast-spec';
declare module './generated/ast-spec' {
interface BaseNode {
parent: TSESTree.Node;
}
interface Program {
/**
* @remarks This never-used property exists only as a convenience for code that tries to access node parents repeatedly.
*/
parent?: never;
}
interface AccessorPropertyComputedName {
parent: TSESTree.ClassBody;
}
interface AccessorPropertyNonComputedName {
parent: TSESTree.ClassBody;
}
interface TSAbstractAccessorPropertyComputedName {
parent: TSESTree.ClassBody;
}
interface TSAbstractAccessorPropertyNonComputedName {
parent: TSESTree.ClassBody;
}
interface VariableDeclaratorDefiniteAssignment {
parent: TSESTree.VariableDeclaration;
}
interface VariableDeclaratorMaybeInit {
parent: TSESTree.VariableDeclaration;
}
interface VariableDeclaratorNoInit {
parent: TSESTree.VariableDeclaration;
}
interface UsingInForOfDeclarator {
parent: TSESTree.VariableDeclaration;
}
interface UsingInNormalContextDeclarator {
parent: TSESTree.VariableDeclaration;
}
interface CatchClause {
parent: TSESTree.TryStatement;
}
interface ClassBody {
parent: TSESTree.ClassDeclaration | TSESTree.ClassExpression;
}
interface ImportAttribute {
parent: TSESTree.ExportAllDeclaration | TSESTree.ExportNamedDeclaration | TSESTree.ImportDeclaration | TSESTree.TSImportType;
}
interface ImportDefaultSpecifier {
parent: TSESTree.ImportDeclaration;
}
interface ImportNamespaceSpecifier {
parent: TSESTree.ImportDeclaration;
}
interface ImportSpecifier {
parent: TSESTree.ExportAllDeclaration | TSESTree.ExportNamedDeclaration | TSESTree.ImportDeclaration;
}
interface ExportDefaultDeclaration {
parent: TSESTree.BlockStatement | TSESTree.Program | TSESTree.TSModuleBlock;
}
interface ExportNamedDeclarationWithoutSourceWithMultiple {
parent: TSESTree.BlockStatement | TSESTree.Program | TSESTree.TSModuleBlock;
}
interface ExportNamedDeclarationWithoutSourceWithSingle {
parent: TSESTree.BlockStatement | TSESTree.Program | TSESTree.TSModuleBlock;
}
interface ExportNamedDeclarationWithSource {
parent: TSESTree.BlockStatement | TSESTree.Program | TSESTree.TSModuleBlock;
}
interface FunctionDeclarationWithName {
parent: TSESTree.BlockStatement | TSESTree.ExportDefaultDeclaration | TSESTree.ExportNamedDeclaration | TSESTree.Program;
}
interface FunctionDeclarationWithOptionalName {
parent: TSESTree.ExportDefaultDeclaration;
}
interface JSXAttribute {
parent: TSESTree.JSXOpeningElement;
}
interface JSXClosingElement {
parent: TSESTree.JSXElement;
}
interface JSXClosingFragment {
parent: TSESTree.JSXFragment;
}
interface JSXOpeningElement {
parent: TSESTree.JSXElement;
}
interface JSXOpeningFragment {
parent: TSESTree.JSXFragment;
}
interface JSXSpreadAttribute {
parent: TSESTree.JSXOpeningElement;
}
interface MethodDefinitionComputedName {
parent: TSESTree.ClassBody;
}
interface MethodDefinitionNonComputedName {
parent: TSESTree.ClassBody;
}
interface TSAbstractMethodDefinitionComputedName {
parent: TSESTree.ClassBody;
}
interface TSAbstractMethodDefinitionNonComputedName {
parent: TSESTree.ClassBody;
}
interface PropertyComputedName {
parent: TSESTree.ObjectExpression | TSESTree.ObjectPattern;
}
interface PropertyNonComputedName {
parent: TSESTree.ObjectExpression | TSESTree.ObjectPattern;
}
interface PropertyDefinitionComputedName {
parent: TSESTree.ClassBody;
}
interface PropertyDefinitionNonComputedName {
parent: TSESTree.ClassBody;
}
interface TSAbstractPropertyDefinitionComputedName {
parent: TSESTree.ClassBody;
}
interface TSAbstractPropertyDefinitionNonComputedName {
parent: TSESTree.ClassBody;
}
interface SpreadElement {
parent: TSESTree.ArrayExpression | TSESTree.CallExpression | TSESTree.NewExpression | TSESTree.ObjectExpression;
}
interface StaticBlock {
parent: TSESTree.ClassBody;
}
interface SwitchCase {
parent: TSESTree.SwitchStatement;
}
interface TemplateElement {
parent: TSESTree.TemplateLiteral | TSESTree.TSTemplateLiteralType;
}
interface TSCallSignatureDeclaration {
parent: TSESTree.TSInterfaceBody | TSESTree.TSTypeLiteral;
}
interface TSConstructSignatureDeclaration {
parent: TSESTree.TSInterfaceBody | TSESTree.TSTypeLiteral;
}
interface TSClassImplements {
parent: TSESTree.ClassDeclaration | TSESTree.ClassExpression;
}
interface TSEnumBody {
parent: TSESTree.TSEnumDeclaration;
}
interface TSEnumMember {
parent: TSESTree.TSEnumBody;
}
interface TSIndexSignature {
parent: TSESTree.ClassBody | TSESTree.TSInterfaceBody | TSESTree.TSTypeLiteral;
}
interface TSInterfaceBody {
parent: TSESTree.TSInterfaceDeclaration;
}
interface TSInterfaceHeritage {
parent: TSESTree.TSInterfaceBody;
}
interface TSMethodSignatureComputedName {
parent: TSESTree.TSInterfaceBody | TSESTree.TSTypeLiteral;
}
interface TSMethodSignatureNonComputedName {
parent: TSESTree.TSInterfaceBody | TSESTree.TSTypeLiteral;
}
interface TSModuleBlock {
parent: TSESTree.TSModuleDeclaration;
}
interface TSParameterProperty {
parent: TSESTree.FunctionLike;
}
interface TSPropertySignatureComputedName {
parent: TSESTree.TSInterfaceBody | TSESTree.TSTypeLiteral;
}
interface TSPropertySignatureNonComputedName {
parent: TSESTree.TSInterfaceBody | TSESTree.TSTypeLiteral;
}
interface TSTypeParameter {
parent: TSESTree.TSInferType | TSESTree.TSMappedType | TSESTree.TSTypeParameterDeclaration;
}
interface ExportSpecifierWithIdentifierLocal {
parent: TSESTree.ExportNamedDeclaration;
}
interface ExportSpecifierWithStringOrLiteralLocal {
parent: TSESTree.ExportNamedDeclaration;
}
}
export * as TSESTree from './generated/ast-spec';
export type NodeWithParent = Exclude<TSESTree.Node, TSESTree.Program>;

View File

@@ -0,0 +1,167 @@
/**
* @fileoverview Rule to flag use of unnecessary semicolons
* @author Nicholas C. Zakas
* @deprecated in ESLint v8.53.0
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const FixTracker = require("./utils/fix-tracker");
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
deprecated: {
message: "Formatting rules are being moved out of ESLint core.",
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
deprecatedSince: "8.53.0",
availableUntil: "11.0.0",
replacedBy: [
{
message:
"ESLint Stylistic now maintains deprecated stylistic core rules.",
url: "https://eslint.style/guide/migration",
plugin: {
name: "@stylistic/eslint-plugin",
url: "https://eslint.style",
},
rule: {
name: "no-extra-semi",
url: "https://eslint.style/rules/no-extra-semi",
},
},
],
},
type: "suggestion",
docs: {
description: "Disallow unnecessary semicolons",
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-extra-semi",
},
fixable: "code",
schema: [],
messages: {
unexpected: "Unnecessary semicolon.",
},
},
create(context) {
const sourceCode = context.sourceCode;
/**
* Checks if a node or token is fixable.
* A node is fixable if it can be removed without turning a subsequent statement into a directive after fixing other nodes.
* @param {Token} nodeOrToken The node or token to check.
* @returns {boolean} Whether or not the node is fixable.
*/
function isFixable(nodeOrToken) {
const nextToken = sourceCode.getTokenAfter(nodeOrToken);
if (!nextToken || nextToken.type !== "String") {
return true;
}
const stringNode = sourceCode.getNodeByRangeIndex(
nextToken.range[0],
);
return !astUtils.isTopLevelExpressionStatement(stringNode.parent);
}
/**
* Reports an unnecessary semicolon error.
* @param {Node|Token} nodeOrToken A node or a token to be reported.
* @returns {void}
*/
function report(nodeOrToken) {
context.report({
node: nodeOrToken,
messageId: "unexpected",
fix: isFixable(nodeOrToken)
? fixer =>
/*
* Expand the replacement range to include the surrounding
* tokens to avoid conflicting with semi.
* https://github.com/eslint/eslint/issues/7928
*/
new FixTracker(fixer, context.sourceCode)
.retainSurroundingTokens(nodeOrToken)
.remove(nodeOrToken)
: null,
});
}
/**
* Checks for a part of a class body.
* This checks tokens from a specified token to a next MethodDefinition or the end of class body.
* @param {Token} firstToken The first token to check.
* @returns {void}
*/
function checkForPartOfClassBody(firstToken) {
for (
let token = firstToken;
token.type === "Punctuator" &&
!astUtils.isClosingBraceToken(token);
token = sourceCode.getTokenAfter(token)
) {
if (astUtils.isSemicolonToken(token)) {
report(token);
}
}
}
return {
/**
* Reports this empty statement, except if the parent node is a loop.
* @param {Node} node A EmptyStatement node to be reported.
* @returns {void}
*/
EmptyStatement(node) {
const parent = node.parent,
allowedParentTypes = [
"ForStatement",
"ForInStatement",
"ForOfStatement",
"WhileStatement",
"DoWhileStatement",
"IfStatement",
"LabeledStatement",
"WithStatement",
];
if (!allowedParentTypes.includes(parent.type)) {
report(node);
}
},
/**
* Checks tokens from the head of this class body to the first MethodDefinition or the end of this class body.
* @param {Node} node A ClassBody node to check.
* @returns {void}
*/
ClassBody(node) {
checkForPartOfClassBody(sourceCode.getFirstToken(node, 1)); // 0 is `{`.
},
/**
* Checks tokens from this MethodDefinition to the next MethodDefinition or the end of this class body.
* @param {Node} node A MethodDefinition node of the start point.
* @returns {void}
*/
"MethodDefinition, PropertyDefinition, StaticBlock"(node) {
checkForPartOfClassBody(sourceCode.getTokenAfter(node));
},
};
},
};

View File

@@ -0,0 +1,104 @@
// src/index.ts
var b = {
reset: [0, 0],
bold: [1, 22, "\x1B[22m\x1B[1m"],
dim: [2, 22, "\x1B[22m\x1B[2m"],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29],
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39],
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
blackBright: [90, 39],
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39],
bgBlackBright: [100, 49],
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49]
};
function i(e) {
return String(e);
}
i.open = "";
i.close = "";
function p() {
let e = {
isColorSupported: !1,
reset: i
};
for (let r in b)
e[r] = i;
return e;
}
function B() {
let e = typeof process != "undefined" ? process : void 0, r = (e == null ? void 0 : e.env) || {}, a = r.FORCE_TTY !== "false", l = (e == null ? void 0 : e.argv) || [];
return !("NO_COLOR" in r || l.includes("--no-color")) && ("FORCE_COLOR" in r || l.includes("--color") || (e == null ? void 0 : e.platform) === "win32" || a && r.TERM !== "dumb" || "CI" in r) || typeof window != "undefined" && !!window.chrome;
}
function C({ force: e } = {}) {
let r = e || B(), a = (t, o, u, n) => {
let g = "", s = 0;
do
g += t.substring(s, n) + u, s = n + o.length, n = t.indexOf(o, s);
while (~n);
return g + t.substring(s);
}, l = (t, o, u = t) => {
let n = (g) => {
let s = String(g), h = s.indexOf(o, t.length);
return ~h ? t + a(s, o, u, h) + o : t + s + o;
};
return n.open = t, n.close = o, n;
}, c = {
isColorSupported: r
}, f = (t) => `\x1B[${t}m`;
for (let t in b) {
let o = b[t];
c[t] = r ? l(
f(o[0]),
f(o[1]),
o[2]
) : i;
}
return c;
}
var d = C();
function m() {
Object.assign(d, p());
}
function w() {
Object.assign(d, C({ force: !0 }));
}
var y = d;
export {
C as createColors,
y as default,
m as disableDefaultColors,
w as enabledDefaultColors,
p as getDefaultColors,
B as isSupported
};

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,CAAkB,EAClB,CAAkB,EAClB,GAAW,EACX,EAAE;IACF,MAAM,EAAE,GAAG,CAAC,YAAY,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IACvD,MAAM,EAAE,GAAG,CAAC,YAAY,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAEvD,MAAM,CAAC,GAAG,EAAE,KAAK,IAAI,IAAI,EAAE,IAAI,IAAI,IAAI,KAAK,CAAC,EAAE,EAAE,EAAE,EAAE,GAAG,CAAC,CAAA;IAEzD,OAAO,CACL,CAAC,IAAI;QACH,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;QACX,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC;QACT,GAAG,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACvB,IAAI,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACvC,IAAI,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC;KAClC,CACF,CAAA;AACH,CAAC,CAAA;AAED,MAAM,UAAU,GAAG,CAAC,GAAW,EAAE,GAAW,EAAE,EAAE;IAC9C,MAAM,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IACxB,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;AACxB,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,KAAK,GAAG,CACnB,CAAS,EACT,CAAS,EACT,GAAW,EACmB,EAAE;IAChC,IAAI,IAAc,EAChB,GAAuB,EACvB,IAAY,EACZ,KAAK,GAAuB,SAAS,EACrC,MAAoC,CAAA;IACtC,IAAI,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IACvB,IAAI,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAA;IAC/B,IAAI,CAAC,GAAG,EAAE,CAAA;IAEV,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;QACtB,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACZ,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAA;QACjB,CAAC;QACD,IAAI,GAAG,EAAE,CAAA;QACT,IAAI,GAAG,GAAG,CAAC,MAAM,CAAA;QAEjB,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACzB,IAAI,CAAC,KAAK,EAAE,EAAE,CAAC;gBACb,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;gBACZ,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAA;YAC5B,CAAC;iBAAM,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC7B,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;gBACpB,IAAI,CAAC,KAAK,SAAS;oBAAE,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAA;YACvC,CAAC;iBAAM,CAAC;gBACN,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;gBAChB,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,GAAG,IAAI,EAAE,CAAC;oBACpC,IAAI,GAAG,GAAG,CAAA;oBACV,KAAK,GAAG,EAAE,CAAA;gBACZ,CAAC;gBAED,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAA;YAC5B,CAAC;YAED,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;QAClC,CAAC;QAED,IAAI,IAAI,CAAC,MAAM,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACvC,MAAM,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;QACxB,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAA;AACf,CAAC,CAAA","sourcesContent":["export const balanced = (\n a: string | RegExp,\n b: string | RegExp,\n str: string,\n) => {\n const ma = a instanceof RegExp ? maybeMatch(a, str) : a\n const mb = b instanceof RegExp ? maybeMatch(b, str) : b\n\n const r = ma !== null && mb != null && range(ma, mb, str)\n\n return (\n r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + ma.length, r[1]),\n post: str.slice(r[1] + mb.length),\n }\n )\n}\n\nconst maybeMatch = (reg: RegExp, str: string) => {\n const m = str.match(reg)\n return m ? m[0] : null\n}\n\nexport const range = (\n a: string,\n b: string,\n str: string,\n): undefined | [number, number] => {\n let begs: number[],\n beg: number | undefined,\n left: number,\n right: number | undefined = undefined,\n result: undefined | [number, number]\n let ai = str.indexOf(a)\n let bi = str.indexOf(b, ai + 1)\n let i = ai\n\n if (ai >= 0 && bi > 0) {\n if (a === b) {\n return [ai, bi]\n }\n begs = []\n left = str.length\n\n while (i >= 0 && !result) {\n if (i === ai) {\n begs.push(i)\n ai = str.indexOf(a, i + 1)\n } else if (begs.length === 1) {\n const r = begs.pop()\n if (r !== undefined) result = [r, bi]\n } else {\n beg = begs.pop()\n if (beg !== undefined && beg < left) {\n left = beg\n right = bi\n }\n\n bi = str.indexOf(b, i + 1)\n }\n\n i = ai < bi && ai >= 0 ? ai : bi\n }\n\n if (begs.length && right !== undefined) {\n result = [left, right]\n }\n }\n\n return result\n}\n"]}

View File

@@ -0,0 +1 @@
{"version":3,"file":"visitor.js","sourceRoot":"","sources":["../../src/ast/visitor.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAS/C,OAAO,EACH,uBAAuB,EACvB,sBAAsB,GACzB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACH,YAAY,EACZ,YAAY,EACZ,UAAU,GACb,MAAM,SAAS,CAAC;AAEjB,OAAO,EACH,SAAS,EACT,UAAU,GACb,MAAM,wBAAwB,CAAC;AAGhC,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEhG,2EAA2E;AAE3E,SAAS,qBAAqB,CAAI,MAAyB,EAAE,IAAsB;IAC/E,OAAO,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAC3C,CAAC;AAED,SAAS,sBAAsB,CAAI,MAAyB,EAAE,OAAoD,EAAE,KAAkC;IAClJ,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,IAAI,OAAO;QAAE,OAAO,OAAO,CAAC,KAAK,CAAC,CAAC;IACnC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACvB,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;QAC5B,IAAI,MAAM;YAAE,OAAO,MAAM,CAAC;IAC9B,CAAC;IACD,OAAO,SAAS,CAAC;AACrB,CAAC;AAED,qCAAqC;AAErC,SAAS,yCAAyC,CAAI,IAAS,EAAE,MAAyB,EAAE,OAAoD;IAC5I,OAAO,qBAAqB,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC;QAC9C,CAAC,IAAI,CAAC,WAAW;YACb,CAAC,CAAC,qBAAqB,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,qBAAqB,CAAC,MAAM,EAAE,IAAI,CAAC,cAAc,CAAC;YAChG,CAAC,CAAC,qBAAqB,CAAC,MAAM,EAAE,IAAI,CAAC,cAAc,CAAC,IAAI,qBAAqB,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QACrG,sBAAsB,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;AAC9D,CAAC;AAED,OAAO,EAAE,yCAAyC,IAAI,+BAA+B,EAAE,yCAAyC,IAAI,8BAA8B,EAAE,CAAC;AAErK,uCAAuC;AAEvC,SAAS,2CAA2C,CAAC,IAAiC,EAAE,OAAgB;IACpG,MAAM,QAAQ,GAAG,SAAS,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC;IAChE,MAAM,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC;IAC1D,MAAM,eAAe,GAAG,SAAS,CAAC,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;IAC5E,MAAM,QAAQ,GAAG,UAAU,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IACnD,OAAO,IAAI,CAAC,IAAI,KAAK,UAAU,CAAC,iBAAiB;QAC7C,CAAC,CAAC,uBAAuB,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,eAAe,EAAE,QAAQ,CAAC;QAC3E,CAAC,CAAC,sBAAsB,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,eAAe,EAAE,QAAQ,CAAC,CAAC;AACnF,CAAC;AAED,OAAO,EAAE,2CAA2C,IAAI,iCAAiC,EAAE,2CAA2C,IAAI,gCAAgC,EAAE,CAAC"}

View File

@@ -0,0 +1,249 @@
/**
* @fileoverview Restrict usage of specified node modules.
* @author Christian Schulz
* @deprecated in ESLint v7.0.0
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const ignore = require("ignore");
const arrayOfStrings = {
type: "array",
items: { type: "string" },
uniqueItems: true,
};
const arrayOfStringsOrObjects = {
type: "array",
items: {
anyOf: [
{ type: "string" },
{
type: "object",
properties: {
name: { type: "string" },
message: {
type: "string",
minLength: 1,
},
},
additionalProperties: false,
required: ["name"],
},
],
},
uniqueItems: true,
};
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
deprecated: {
message: "Node.js rules were moved out of ESLint core.",
url: "https://eslint.org/docs/latest/use/migrating-to-7.0.0#deprecate-node-rules",
deprecatedSince: "7.0.0",
availableUntil: "11.0.0",
replacedBy: [
{
message:
"eslint-plugin-n now maintains deprecated Node.js-related rules.",
plugin: {
name: "eslint-plugin-n",
url: "https://github.com/eslint-community/eslint-plugin-n",
},
rule: {
name: "no-restricted-require",
url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-restricted-require.md",
},
},
],
},
type: "suggestion",
docs: {
description: "Disallow specified modules when loaded by `require`",
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-restricted-modules",
},
schema: {
anyOf: [
arrayOfStringsOrObjects,
{
type: "array",
items: {
type: "object",
properties: {
paths: arrayOfStringsOrObjects,
patterns: arrayOfStrings,
},
additionalProperties: false,
},
additionalItems: false,
},
],
},
messages: {
defaultMessage: "'{{name}}' module is restricted from being used.",
customMessage:
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
"'{{name}}' module is restricted from being used. {{customMessage}}",
patternMessage:
"'{{name}}' module is restricted from being used by a pattern.",
},
},
create(context) {
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 restrictedPatterns =
(isPathAndPatternsObject ? options[0].patterns : []) || [];
const restrictedPathMessages = restrictedPaths.reduce(
(memo, importName) => {
if (typeof importName === "string") {
memo[importName] = null;
} else {
memo[importName.name] = importName.message;
}
return memo;
},
{},
);
// if no imports are restricted we don't need to check
if (
Object.keys(restrictedPaths).length === 0 &&
restrictedPatterns.length === 0
) {
return {};
}
// relative paths are supported for this rule
const ig = ignore({ allowRelativePaths: true }).add(restrictedPatterns);
/**
* Function to check if a node is a string literal.
* @param {ASTNode} node The node to check.
* @returns {boolean} If the node is a string literal.
*/
function isStringLiteral(node) {
return (
node &&
node.type === "Literal" &&
typeof node.value === "string"
);
}
/**
* Function to check if a node is a require call.
* @param {ASTNode} node The node to check.
* @returns {boolean} If the node is a require call.
*/
function isRequireCall(node) {
return (
node.callee.type === "Identifier" &&
node.callee.name === "require"
);
}
/**
* Extract string from Literal or TemplateLiteral node
* @param {ASTNode} node The node to extract from
* @returns {string|null} Extracted string or null if node doesn't represent a string
*/
function getFirstArgumentString(node) {
if (isStringLiteral(node)) {
return node.value.trim();
}
if (astUtils.isStaticTemplateLiteral(node)) {
return node.quasis[0].value.cooked.trim();
}
return null;
}
/**
* Report a restricted path.
* @param {node} node representing the restricted path reference
* @param {string} name restricted path
* @returns {void}
* @private
*/
function reportPath(node, name) {
const customMessage = restrictedPathMessages[name];
const messageId = customMessage
? "customMessage"
: "defaultMessage";
context.report({
node,
messageId,
data: {
name,
customMessage,
},
});
}
/**
* Check if the given name is a restricted path name
* @param {string} name name of a variable
* @returns {boolean} whether the variable is a restricted path or not
* @private
*/
function isRestrictedPath(name) {
return Object.hasOwn(restrictedPathMessages, name);
}
return {
CallExpression(node) {
if (isRequireCall(node)) {
// node has arguments
if (node.arguments.length) {
const name = getFirstArgumentString(node.arguments[0]);
// if first argument is a string literal or a static string template literal
if (name) {
// check if argument value is in restricted modules array
if (isRestrictedPath(name)) {
reportPath(node, name);
}
if (
restrictedPatterns.length > 0 &&
ig.ignores(name)
) {
context.report({
node,
messageId: "patternMessage",
data: { name },
});
}
}
}
}
},
};
},
};

View File

@@ -0,0 +1,2 @@
export declare function safeCaptureStackTrace(...args: Parameters<typeof Error.captureStackTrace>): void;
//# sourceMappingURL=stack-trace.d.ts.map

View File

@@ -0,0 +1,32 @@
'use strict';
var parse = require('../');
var test = require('tape');
test('short -k=v', function (t) {
t.plan(1);
var argv = parse(['-b=123']);
t.deepEqual(argv, { b: 123, _: [] });
});
test('multi short -k=v', function (t) {
t.plan(1);
var argv = parse(['-a=whatever', '-b=robots']);
t.deepEqual(argv, { a: 'whatever', b: 'robots', _: [] });
});
test('short with embedded equals -k=a=b', function (t) {
t.plan(1);
var argv = parse(['-k=a=b']);
t.deepEqual(argv, { k: 'a=b', _: [] });
});
test('short with later equals like -ab=c', function (t) {
t.plan(1);
var argv = parse(['-ab=c']);
t.deepEqual(argv, { a: true, b: 'c', _: [] });
});

View File

@@ -0,0 +1,11 @@
'use strict';
var parse = require('../');
var test = require('tape');
test('parse with modifier functions', function (t) {
t.plan(1);
var argv = parse(['-b', '123'], { boolean: 'b' });
t.deepEqual(argv, { b: true, _: [123] });
});

View File

@@ -0,0 +1,31 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
test("passing validations", () => {
const example1 = z.custom<number>((x) => typeof x === "number");
example1.parse(1234);
expect(() => example1.parse({})).toThrow();
});
test("string params", () => {
const example1 = z.custom<number>((x) => typeof x !== "number", "customerr");
const result = example1.safeParse(1234);
expect(result.success).toEqual(false);
// @ts-ignore
expect(JSON.stringify(result.error).includes("customerr")).toEqual(true);
});
test("async validations", async () => {
const example1 = z.custom<number>(async (x) => {
return typeof x === "number";
});
const r1 = await example1.safeParseAsync(1234);
expect(r1.success).toEqual(true);
expect(r1.data).toEqual(1234);
const r2 = await example1.safeParseAsync("asdf");
expect(r2.success).toEqual(false);
expect(r2.error!.issues.length).toEqual(1);
});

View File

@@ -0,0 +1,57 @@
'use strict'
const test = require('node:test')
const assert = require('node:assert')
const { join } = require('node:path')
const { readFileSync } = require('node:fs')
const { file } = require('../helper')
const pino = require('../..')
test('thread-stream sync true should log synchronously', async () => {
const outputPath = file()
function getOutputLogLines () {
return (readFileSync(outputPath)).toString().trim().split('\n').map(JSON.parse)
}
const transport = pino.transport({
target: join(__dirname, '..', 'fixtures', 'to-file-transport.js'),
options: { destination: outputPath, flush: true },
sync: true
})
const instance = pino(transport)
var value = { message: 'sync' }
instance.info(value)
instance.info(value)
instance.info(value)
instance.info(value)
instance.info(value)
instance.info(value)
let interrupt = false
let flushData
let loopCounter = 0
// Start a synchronous loop
while (!interrupt && loopCounter < (process.env.MAX_TEST_LOOP_ITERATION || 20000)) {
try {
loopCounter++
const data = getOutputLogLines()
flushData = data
if (data) {
interrupt = true
break
}
} catch (error) {
// File may not exist yet
// Wait till MAX_TEST_LOOP_ITERATION iterations
}
}
if (!interrupt) {
throw new Error('Sync loop did not get interrupt')
}
assert.equal(flushData.length, 6)
})

View File

@@ -0,0 +1,115 @@
/**
* @fileoverview Rule to disallow uses of await inside of loops.
* @author Nat Mote (nmote)
*/
"use strict";
/**
* Check whether it should stop traversing ancestors at the given node.
* @param {ASTNode} node A node to check.
* @returns {boolean} `true` if it should stop traversing.
*/
function isBoundary(node) {
const t = node.type;
return (
t === "FunctionDeclaration" ||
t === "FunctionExpression" ||
t === "ArrowFunctionExpression" ||
/*
* Don't report the await expressions on for-await-of loop since it's
* asynchronous iteration intentionally.
*/
(t === "ForOfStatement" && node.await === true)
);
}
/**
* Check whether the given node is in loop.
* @param {ASTNode} node A node to check.
* @param {ASTNode} parent A parent node to check.
* @returns {boolean} `true` if the node is in loop.
*/
function isLooped(node, parent) {
switch (parent.type) {
case "ForStatement":
return (
node === parent.test ||
node === parent.update ||
node === parent.body
);
case "ForOfStatement":
case "ForInStatement":
return (
node === parent.body ||
(node === parent.left && node.kind === "await using")
);
case "WhileStatement":
case "DoWhileStatement":
return node === parent.test || node === parent.body;
default:
return false;
}
}
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
docs: {
description: "Disallow `await` inside of loops",
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-await-in-loop",
},
schema: [],
messages: {
unexpectedAwait: "Unexpected `await` inside a loop.",
},
},
create(context) {
/**
* Validate an await expression.
* @param {ASTNode} awaitNode An AwaitExpression or ForOfStatement node to validate.
* @returns {void}
*/
function validate(awaitNode) {
if (
awaitNode.type === "VariableDeclaration" &&
awaitNode.kind !== "await using"
) {
return;
}
if (awaitNode.type === "ForOfStatement" && !awaitNode.await) {
return;
}
let node = awaitNode;
let parent = node.parent;
while (parent && !isBoundary(parent)) {
if (isLooped(node, parent)) {
context.report({
node: awaitNode,
messageId: "unexpectedAwait",
});
return;
}
node = parent;
parent = parent.parent;
}
}
return {
AwaitExpression: validate,
ForOfStatement: validate,
VariableDeclaration: validate,
};
},
};

View File

@@ -0,0 +1,14 @@
/**
* Internal blake variable.
* For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1].
*/
export declare const BSIGMA: Uint8Array;
export type Num4 = {
a: number;
b: number;
c: number;
d: number;
};
export declare function G1s(a: number, b: number, c: number, d: number, x: number): Num4;
export declare function G2s(a: number, b: number, c: number, d: number, x: number): Num4;
//# sourceMappingURL=_blake.d.ts.map

View File

@@ -0,0 +1,7 @@
export { FlatESLint } from './eslint/FlatESLint';
export { FlatESLint as ESLint } from './eslint/FlatESLint';
export {
/**
* @deprecated - use ESLint instead
*/
LegacyESLint, } from './eslint/LegacyESLint';

View File

@@ -0,0 +1,86 @@
import { MaybeMockedDeep } from '@vitest/spy';
import { b as ModuleMockOptions, c as ModuleMockFactoryWithHelper, a as MockedModule, T as TestModuleMocker, M as MockerRegistry, d as MockedModuleType, e as ModuleMockContext } from './types.d-BjI5eAwu.js';
import { C as CreateMockInstanceProcedure } from './index.d-B41z0AuW.js';
interface CompilerHintsOptions {
/**
* This is the key used to access the globalThis object in the worker.
* Unlike `globalThisAccessor` in other APIs, this is not injected into the script.
* ```ts
* // globalThisKey: '__my_variable__' produces:
* globalThis['__my_variable__']
* // globalThisKey: '"__my_variable__"' produces:
* globalThis['"__my_variable__"'] // notice double quotes
* ```
* @default '__vitest_mocker__'
*/
globalThisKey?: string;
}
interface ModuleMockerCompilerHints {
hoisted: <T>(factory: () => T) => T;
mock: (path: string | Promise<unknown>, factory?: ModuleMockOptions | ModuleMockFactoryWithHelper) => void;
unmock: (path: string | Promise<unknown>) => void;
doMock: (path: string | Promise<unknown>, factory?: ModuleMockOptions | ModuleMockFactoryWithHelper) => void;
doUnmock: (path: string | Promise<unknown>) => void;
importActual: <T>(path: string) => Promise<T>;
importMock: <T>(path: string) => Promise<MaybeMockedDeep<T>>;
}
declare function createCompilerHints(options?: CompilerHintsOptions): ModuleMockerCompilerHints;
interface ModuleMockerInterceptor {
register: (module: MockedModule) => Promise<void>;
delete: (url: string) => Promise<void>;
invalidate: () => Promise<void>;
}
declare class ModuleMocker implements TestModuleMocker {
private interceptor;
private rpc;
private createMockInstance;
private config;
protected registry: MockerRegistry;
private queue;
private mockedIds;
constructor(interceptor: ModuleMockerInterceptor, rpc: ModuleMockerRPC, createMockInstance: CreateMockInstanceProcedure, config: ModuleMockerConfig);
prepare(): Promise<void>;
resolveFactoryModule(id: string): Promise<Record<string | symbol, any>>;
getFactoryModule(id: string): any;
invalidate(): Promise<void>;
importActual<T>(id: string, importer: string): Promise<T>;
protected getBaseUrl(): string;
importMock<T>(rawId: string, importer: string): Promise<T>;
mockObject(object: Record<string | symbol, any>, moduleType?: "automock" | "autospy"): Record<string | symbol, any>;
mockObject(object: Record<string | symbol, any>, mockExports: Record<string | symbol, any> | undefined, moduleType?: "automock" | "autospy"): Record<string | symbol, any>;
getMockContext(): ModuleMockContext;
queueMock(rawId: string, importer: string, factoryOrOptions?: ModuleMockOptions | (() => any)): void;
queueUnmock(id: string, importer: string): void;
wrapDynamicImport<T>(moduleFactory: () => Promise<T>): Promise<T>;
getMockedModuleById(id: string): MockedModule | undefined;
reset(): void;
private resolveMockPath;
}
interface ResolveIdResult {
id: string;
url: string;
optimized: boolean;
}
interface ResolveMockResult {
mockType: MockedModuleType;
resolvedId: string;
resolvedUrl: string;
redirectUrl?: string | null;
needsInterop?: boolean;
}
interface ModuleMockerRPC {
invalidate: (ids: string[]) => Promise<void>;
resolveId: (id: string, importer: string) => Promise<ResolveIdResult | null>;
resolveMock: (id: string, importer: string, options: {
mock: "spy" | "factory" | "auto";
}) => Promise<ResolveMockResult>;
}
interface ModuleMockerConfig {
root: string;
}
export { ModuleMocker as b, createCompilerHints as f };
export type { CompilerHintsOptions as C, ModuleMockerInterceptor as M, ResolveIdResult as R, ModuleMockerCompilerHints as a, ModuleMockerConfig as c, ModuleMockerRPC as d, ResolveMockResult as e };

View File

@@ -0,0 +1,46 @@
import {
noop,
reject as _reject
} from '../-internal';
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@static
@param {Any} reason value that the returned promise will be rejected with.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
export default function reject(reason) {
/*jshint validthis:true */
let Constructor = this;
let promise = new Constructor(noop);
_reject(promise, reason);
return promise;
}

View File

@@ -0,0 +1,726 @@
declare module "node:module" {
import { URL } from "node:url";
class Module {
constructor(id: string, parent?: Module);
}
interface Module extends NodeJS.Module {}
namespace Module {
export { Module };
}
namespace Module {
/**
* A list of the names of all modules provided by Node.js. Can be used to verify
* if a module is maintained by a third party or not.
*
* Note: the list doesn't contain prefix-only modules like `node:test`.
* @since v9.3.0, v8.10.0, v6.13.0
*/
const builtinModules: readonly string[];
/**
* @since v12.2.0
* @param path Filename to be used to construct the require
* function. Must be a file URL object, file URL string, or absolute path
* string.
*/
function createRequire(path: string | URL): NodeJS.Require;
namespace constants {
/**
* The following constants are returned as the `status` field in the object returned by
* {@link enableCompileCache} to indicate the result of the attempt to enable the
* [module compile cache](https://nodejs.org/docs/latest-v26.x/api/module.html#module-compile-cache).
* @since v22.8.0
*/
namespace compileCacheStatus {
/**
* Node.js has enabled the compile cache successfully. The directory used to store the
* compile cache will be returned in the `directory` field in the
* returned object.
*/
const ENABLED: number;
/**
* The compile cache has already been enabled before, either by a previous call to
* {@link enableCompileCache}, or by the `NODE_COMPILE_CACHE=dir`
* environment variable. The directory used to store the
* compile cache will be returned in the `directory` field in the
* returned object.
*/
const ALREADY_ENABLED: number;
/**
* Node.js fails to enable the compile cache. This can be caused by the lack of
* permission to use the specified directory, or various kinds of file system errors.
* The detail of the failure will be returned in the `message` field in the
* returned object.
*/
const FAILED: number;
/**
* Node.js cannot enable the compile cache because the environment variable
* `NODE_DISABLE_COMPILE_CACHE=1` has been set.
*/
const DISABLED: number;
}
}
interface EnableCompileCacheOptions {
/**
* Optional. Directory to store the compile cache. If not specified,
* the directory specified by the `NODE_COMPILE_CACHE=dir` environment variable
* will be used if it's set, or `path.join(os.tmpdir(), 'node-compile-cache')`
* otherwise.
* @since v25.0.0
*/
directory?: string | undefined;
/**
* Optional. If `true`, enables portable compile cache so that
* the cache can be reused even if the project directory is moved. This is a best-effort
* feature. If not specified, it will depend on whether the environment variable
* `NODE_COMPILE_CACHE_PORTABLE=1` is set.
* @since v25.0.0
*/
portable?: boolean | undefined;
}
interface EnableCompileCacheResult {
/**
* One of the {@link constants.compileCacheStatus}
*/
status: number;
/**
* If Node.js cannot enable the compile cache, this contains
* the error message. Only set if `status` is `module.constants.compileCacheStatus.FAILED`.
*/
message?: string;
/**
* If the compile cache is enabled, this contains the directory
* where the compile cache is stored. Only set if `status` is
* `module.constants.compileCacheStatus.ENABLED` or
* `module.constants.compileCacheStatus.ALREADY_ENABLED`.
*/
directory?: string;
}
/**
* Enable [module compile cache](https://nodejs.org/docs/latest-v26.x/api/module.html#module-compile-cache)
* in the current Node.js instance.
*
* For general use cases, it's recommended to call `module.enableCompileCache()` without
* specifying the `options.directory`, so that the directory can be overridden by the
* `NODE_COMPILE_CACHE` environment variable when necessary.
*
* Since compile cache is supposed to be a optimization that is not mission critical, this
* method is designed to not throw any exception when the compile cache cannot be enabled.
* Instead, it will return an object containing an error message in the `message` field to
* aid debugging. If compile cache is enabled successfully, the `directory` field in the
* returned object contains the path to the directory where the compile cache is stored. The
* `status` field in the returned object would be one of the `module.constants.compileCacheStatus`
* values to indicate the result of the attempt to enable the
* [module compile cache](https://nodejs.org/docs/latest-v26.x/api/module.html#module-compile-cache).
*
* This method only affects the current Node.js instance. To enable it in child worker threads,
* either call this method in child worker threads too, or set the
* `process.env.NODE_COMPILE_CACHE` value to compile cache directory so the behavior can
* be inherited into the child workers. The directory can be obtained either from the
* `directory` field returned by this method, or with {@link getCompileCacheDir}.
* @since v22.8.0
* @param options Optional. If a string is passed, it is considered to be `options.directory`.
*/
function enableCompileCache(options?: string | EnableCompileCacheOptions): EnableCompileCacheResult;
/**
* Flush the [module compile cache](https://nodejs.org/docs/latest-v26.x/api/module.html#module-compile-cache)
* accumulated from modules already loaded
* in the current Node.js instance to disk. This returns after all the flushing
* file system operations come to an end, no matter they succeed or not. If there
* are any errors, this will fail silently, since compile cache misses should not
* interfere with the actual operation of the application.
* @since v22.10.0
*/
function flushCompileCache(): void;
/**
* @since v22.8.0
* @return Path to the [module compile cache](https://nodejs.org/docs/latest-v26.x/api/module.html#module-compile-cache)
* directory if it is enabled, or `undefined` otherwise.
*/
function getCompileCacheDir(): string | undefined;
/**
* ```text
* /path/to/project
* ├ packages/
* ├ bar/
* ├ bar.js
* └ package.json // name = '@foo/bar'
* └ qux/
* ├ node_modules/
* └ some-package/
* └ package.json // name = 'some-package'
* ├ qux.js
* └ package.json // name = '@foo/qux'
* ├ main.js
* └ package.json // name = '@foo'
* ```
* ```js
* // /path/to/project/packages/bar/bar.js
* import { findPackageJSON } from 'node:module';
*
* findPackageJSON('..', import.meta.url);
* // '/path/to/project/package.json'
* // Same result when passing an absolute specifier instead:
* findPackageJSON(new URL('../', import.meta.url));
* findPackageJSON(import.meta.resolve('../'));
*
* findPackageJSON('some-package', import.meta.url);
* // '/path/to/project/packages/bar/node_modules/some-package/package.json'
* // When passing an absolute specifier, you might get a different result if the
* // resolved module is inside a subfolder that has nested `package.json`.
* findPackageJSON(import.meta.resolve('some-package'));
* // '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json'
*
* findPackageJSON('@foo/qux', import.meta.url);
* // '/path/to/project/packages/qux/package.json'
* ```
* @since v22.14.0
* @param specifier The specifier for the module whose `package.json` to
* retrieve. When passing a _bare specifier_, the `package.json` at the root of
* the package is returned. When passing a _relative specifier_ or an _absolute specifier_,
* the closest parent `package.json` is returned.
* @param base The absolute location (`file:` URL string or FS path) of the
* containing module. For CJS, use `__filename` (not `__dirname`!); for ESM, use
* `import.meta.url`. You do not need to pass it if `specifier` is an _absolute specifier_.
* @returns A path if the `package.json` is found. When `startLocation`
* is a package, the package's root `package.json`; when a relative or unresolved, the closest
* `package.json` to the `startLocation`.
*/
function findPackageJSON(specifier: string | URL, base?: string | URL): string | undefined;
/**
* @since v18.6.0, v16.17.0
*/
function isBuiltin(moduleName: string): boolean;
interface RegisterOptions<Data> {
/**
* If you want to resolve `specifier` relative to a
* base URL, such as `import.meta.url`, you can pass that URL here. This
* property is ignored if the `parentURL` is supplied as the second argument.
* @default 'data:'
*/
parentURL?: string | URL | undefined;
/**
* Any arbitrary, cloneable JavaScript value to pass into the
* {@link initialize} hook.
*/
data?: Data | undefined;
/**
* [Transferable objects](https://nodejs.org/docs/latest-v26.x/api/worker_threads.html#portpostmessagevalue-transferlist)
* to be passed into the `initialize` hook.
*/
transferList?: any[] | undefined;
}
/* eslint-disable @definitelytyped/no-unnecessary-generics */
/**
* Register a module that exports hooks that customize Node.js module
* resolution and loading behavior. See
* [Customization hooks](https://nodejs.org/docs/latest-v26.x/api/module.html#customization-hooks).
*
* This feature requires `--allow-worker` if used with the
* [Permission Model](https://nodejs.org/docs/latest-v26.x/api/permissions.html#permission-model).
* @since v20.6.0, v18.19.0
* @deprecated Use `module.registerHooks()` instead.
* @param specifier Customization hooks to be registered; this should be
* the same string that would be passed to `import()`, except that if it is
* relative, it is resolved relative to `parentURL`.
* @param parentURL f you want to resolve `specifier` relative to a base
* URL, such as `import.meta.url`, you can pass that URL here.
*/
function register<Data = any>(
specifier: string | URL,
parentURL?: string | URL,
options?: RegisterOptions<Data>,
): void;
function register<Data = any>(specifier: string | URL, options?: RegisterOptions<Data>): void;
interface RegisterHooksOptions {
/**
* See [load hook](https://nodejs.org/docs/latest-v26.x/api/module.html#loadurl-context-nextload).
* @default undefined
*/
load?: LoadHookSync | undefined;
/**
* See [resolve hook](https://nodejs.org/docs/latest-v26.x/api/module.html#resolvespecifier-context-nextresolve).
* @default undefined
*/
resolve?: ResolveHookSync | undefined;
}
interface ModuleHooks {
/**
* Deregister the hook instance.
*/
deregister(): void;
}
/**
* Register [hooks](https://nodejs.org/docs/latest-v26.x/api/module.html#customization-hooks)
* that customize Node.js module resolution and loading behavior.
* @since v22.15.0
* @experimental
*/
function registerHooks(options: RegisterHooksOptions): ModuleHooks;
interface StripTypeScriptTypesOptions {
/**
* Possible values are:
* * `'strip'` Only strip type annotations without performing the transformation of TypeScript features.
* @default 'strip'
*/
mode?: "strip" | undefined;
/**
* Specifies the source url used in the source map.
*/
sourceUrl?: string | undefined;
}
/**
* `module.stripTypeScriptTypes()` removes type annotations from TypeScript code. It
* can be used to strip type annotations from TypeScript code before running it
* with `vm.runInContext()` or `vm.compileFunction()`.
*
* By default, it will throw an error if the code contains TypeScript features
* that require transformation, such as `enum`s. See [type-stripping](https://nodejs.org/docs/latest-v26.x/api/typescript.md#type-stripping) for more information.
*
* _WARNING_: The output of this function should not be considered stable across Node.js versions,
* due to changes in the TypeScript parser.
*
* ```js
* import { stripTypeScriptTypes } from 'node:module';
* const code = 'const a: number = 1;';
* const strippedCode = stripTypeScriptTypes(code);
* console.log(strippedCode);
* // Prints: const a = 1;
* ```
*
* If `sourceUrl` is provided, it will be used appended as a comment at the end of the output:
*
* ```js
* import { stripTypeScriptTypes } from 'node:module';
* const code = 'const a: number = 1;';
* const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' });
* console.log(strippedCode);
* // Prints: const a = 1\n\n//# sourceURL=source.ts;
* ```
* @since v22.13.0
* @param code The code to strip type annotations from.
* @returns The code with type annotations stripped.
*/
function stripTypeScriptTypes(code: string, options?: StripTypeScriptTypesOptions): string;
/* eslint-enable @definitelytyped/no-unnecessary-generics */
/**
* The `module.syncBuiltinESMExports()` method updates all the live bindings for
* builtin `ES Modules` to match the properties of the `CommonJS` exports. It
* does not add or remove exported names from the `ES Modules`.
*
* ```js
* import fs from 'node:fs';
* import assert from 'node:assert';
* import { syncBuiltinESMExports } from 'node:module';
*
* fs.readFile = newAPI;
*
* delete fs.readFileSync;
*
* function newAPI() {
* // ...
* }
*
* fs.newAPI = newAPI;
*
* syncBuiltinESMExports();
*
* import('node:fs').then((esmFS) => {
* // It syncs the existing readFile property with the new value
* assert.strictEqual(esmFS.readFile, newAPI);
* // readFileSync has been deleted from the required fs
* assert.strictEqual('readFileSync' in fs, false);
* // syncBuiltinESMExports() does not remove readFileSync from esmFS
* assert.strictEqual('readFileSync' in esmFS, true);
* // syncBuiltinESMExports() does not add names
* assert.strictEqual(esmFS.newAPI, undefined);
* });
* ```
* @since v12.12.0
*/
function syncBuiltinESMExports(): void;
interface ImportAttributes extends NodeJS.Dict<string> {
type?: string | undefined;
}
type ImportPhase = "source" | "evaluation";
type ModuleFormat =
| "addon"
| "builtin"
| "commonjs"
| "commonjs-typescript"
| "json"
| "module"
| "module-typescript"
| "wasm";
type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray;
type InitializeHook<Data = any> = (data: Data) => void | Promise<void>;
interface ResolveHookContext {
conditions: string[];
importAttributes: ImportAttributes;
parentURL: string | undefined;
}
interface ResolveFnOutput {
format?: string | null | undefined;
importAttributes?: ImportAttributes | undefined;
shortCircuit?: boolean | undefined;
url: string;
}
type ResolveHook = (
specifier: string,
context: ResolveHookContext,
nextResolve: (
specifier: string,
context?: Partial<ResolveHookContext>,
) => ResolveFnOutput | Promise<ResolveFnOutput>,
) => ResolveFnOutput | Promise<ResolveFnOutput>;
type ResolveHookSync = (
specifier: string,
context: ResolveHookContext,
nextResolve: (
specifier: string,
context?: Partial<ResolveHookContext>,
) => ResolveFnOutput,
) => ResolveFnOutput;
interface LoadHookContext {
conditions: string[];
format: string | null | undefined;
importAttributes: ImportAttributes;
}
interface LoadFnOutput {
format: string | null | undefined;
shortCircuit?: boolean | undefined;
source?: ModuleSource | undefined;
}
type LoadHook = (
url: string,
context: LoadHookContext,
nextLoad: (
url: string,
context?: Partial<LoadHookContext>,
) => LoadFnOutput | Promise<LoadFnOutput>,
) => LoadFnOutput | Promise<LoadFnOutput>;
type LoadHookSync = (
url: string,
context: LoadHookContext,
nextLoad: (
url: string,
context?: Partial<LoadHookContext>,
) => LoadFnOutput,
) => LoadFnOutput;
interface SourceMapsSupport {
/**
* If the source maps support is enabled
*/
enabled: boolean;
/**
* If the support is enabled for files in `node_modules`.
*/
nodeModules: boolean;
/**
* If the support is enabled for generated code from `eval` or `new Function`.
*/
generatedCode: boolean;
}
/**
* This method returns whether the [Source Map v3](https://tc39.es/ecma426/) support for stack
* traces is enabled.
* @since v23.7.0, v22.14.0
*/
function getSourceMapsSupport(): SourceMapsSupport;
/**
* `path` is the resolved path for the file for which a corresponding source map
* should be fetched.
* @since v13.7.0, v12.17.0
* @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise.
*/
function findSourceMap(path: string): SourceMap | undefined;
interface SetSourceMapsSupportOptions {
/**
* If enabling the support for files in `node_modules`.
* @default false
*/
nodeModules?: boolean | undefined;
/**
* If enabling the support for generated code from `eval` or `new Function`.
* @default false
*/
generatedCode?: boolean | undefined;
}
/**
* This function enables or disables the [Source Map v3](https://tc39.es/ecma426/) support for
* stack traces.
*
* It provides same features as launching Node.js process with commandline options
* `--enable-source-maps`, with additional options to alter the support for files
* in `node_modules` or generated codes.
*
* Only source maps in JavaScript files that are loaded after source maps has been
* enabled will be parsed and loaded. Preferably, use the commandline options
* `--enable-source-maps` to avoid losing track of source maps of modules loaded
* before this API call.
* @since v23.7.0, v22.14.0
*/
function setSourceMapsSupport(enabled: boolean, options?: SetSourceMapsSupportOptions): void;
interface SourceMapConstructorOptions {
/**
* @since v21.0.0, v20.5.0
*/
lineLengths?: readonly number[] | undefined;
}
interface SourceMapPayload {
file: string;
version: number;
sources: string[];
sourcesContent: string[];
names: string[];
mappings: string;
sourceRoot: string;
}
interface SourceMapping {
generatedLine: number;
generatedColumn: number;
originalSource: string;
originalLine: number;
originalColumn: number;
}
interface SourceOrigin {
/**
* The name of the range in the source map, if one was provided
*/
name: string | undefined;
/**
* The file name of the original source, as reported in the SourceMap
*/
fileName: string;
/**
* The 1-indexed lineNumber of the corresponding call site in the original source
*/
lineNumber: number;
/**
* The 1-indexed columnNumber of the corresponding call site in the original source
*/
columnNumber: number;
}
/**
* @since v13.7.0, v12.17.0
*/
class SourceMap {
constructor(payload: SourceMapPayload, options?: SourceMapConstructorOptions);
/**
* Getter for the payload used to construct the `SourceMap` instance.
*/
readonly payload: SourceMapPayload;
/**
* Given a line offset and column offset in the generated source
* file, returns an object representing the SourceMap range in the
* original file if found, or an empty object if not.
*
* The object returned contains the following keys:
*
* The returned value represents the raw range as it appears in the
* SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and
* column numbers as they appear in Error messages and CallSite
* objects.
*
* To get the corresponding 1-indexed line and column numbers from a
* lineNumber and columnNumber as they are reported by Error stacks
* and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)`
* @param lineOffset The zero-indexed line number offset in the generated source
* @param columnOffset The zero-indexed column number offset in the generated source
*/
findEntry(lineOffset: number, columnOffset: number): SourceMapping | {};
/**
* Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source,
* find the corresponding call site location in the original source.
*
* If the `lineNumber` and `columnNumber` provided are not found in any source map,
* then an empty object is returned.
* @param lineNumber The 1-indexed line number of the call site in the generated source
* @param columnNumber The 1-indexed column number of the call site in the generated source
*/
findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {};
}
function runMain(main?: string): void;
function wrap(script: string): string;
}
global {
namespace NodeJS {
interface Module {
/**
* The module objects required for the first time by this one.
* @since v0.1.16
*/
children: Module[];
/**
* The `module.exports` object is created by the `Module` system. Sometimes this is
* not acceptable; many want their module to be an instance of some class. To do
* this, assign the desired export object to `module.exports`.
* @since v0.1.16
*/
exports: any;
/**
* The fully resolved filename of the module.
* @since v0.1.16
*/
filename: string;
/**
* The identifier for the module. Typically this is the fully resolved
* filename.
* @since v0.1.16
*/
id: string;
/**
* `true` if the module is running during the Node.js preload
* phase.
* @since v15.4.0, v14.17.0
*/
isPreloading: boolean;
/**
* Whether or not the module is done loading, or is in the process of
* loading.
* @since v0.1.16
*/
loaded: boolean;
/**
* The module that first required this one, or `null` if the current module is the
* entry point of the current process, or `undefined` if the module was loaded by
* something that is not a CommonJS module (e.g. REPL or `import`).
* @since v0.1.16
* @deprecated Please use `require.main` and `module.children` instead.
*/
parent: Module | null | undefined;
/**
* The directory name of the module. This is usually the same as the
* `path.dirname()` of the `module.id`.
* @since v11.14.0
*/
path: string;
/**
* The search paths for the module.
* @since v0.4.0
*/
paths: string[];
/**
* The `module.require()` method provides a way to load a module as if
* `require()` was called from the original module.
* @since v0.5.1
*/
require(id: string): any;
}
interface Require {
/**
* Used to import modules, `JSON`, and local files.
* @since v0.1.13
*/
(id: string): any;
/**
* Modules are cached in this object when they are required. By deleting a key
* value from this object, the next `require` will reload the module.
* This does not apply to
* [native addons](https://nodejs.org/docs/latest-v26.x/api/addons.html),
* for which reloading will result in an error.
* @since v0.3.0
*/
cache: Dict<Module>;
/**
* Instruct `require` on how to handle certain file extensions.
* @since v0.3.0
* @deprecated
*/
extensions: RequireExtensions;
/**
* The `Module` object representing the entry script loaded when the Node.js
* process launched, or `undefined` if the entry point of the program is not a
* CommonJS module.
* @since v0.1.17
*/
main: Module | undefined;
/**
* @since v0.3.0
*/
resolve: RequireResolve;
}
/** @deprecated */
interface RequireExtensions extends Dict<(module: Module, filename: string) => any> {
".js": (module: Module, filename: string) => any;
".json": (module: Module, filename: string) => any;
".node": (module: Module, filename: string) => any;
}
interface RequireResolveOptions {
/**
* Paths to resolve module location from. If present, these
* paths are used instead of the default resolution paths, with the exception
* of
* [GLOBAL\_FOLDERS](https://nodejs.org/docs/latest-v26.x/api/modules.html#loading-from-the-global-folders)
* like `$HOME/.node_modules`, which are
* always included. Each of these paths is used as a starting point for
* the module resolution algorithm, meaning that the `node_modules` hierarchy
* is checked from this location.
* @since v8.9.0
*/
paths?: string[] | undefined;
}
interface RequireResolve {
/**
* Use the internal `require()` machinery to look up the location of a module,
* but rather than loading the module, just return the resolved filename.
*
* If the module can not be found, a `MODULE_NOT_FOUND` error is thrown.
* @since v0.3.0
* @param request The module path to resolve.
*/
(request: string, options?: RequireResolveOptions): string;
/**
* Returns an array containing the paths searched during resolution of `request` or
* `null` if the `request` string references a core module, for example `http` or
* `fs`.
* @since v8.9.0
* @param request The module path whose lookup paths are being retrieved.
*/
paths(request: string): string[] | null;
}
}
/**
* The directory name of the current module. This is the same as the
* `path.dirname()` of the `__filename`.
* @since v0.1.27
*/
var __dirname: string;
/**
* The file name of the current module. This is the current module file's absolute
* path with symlinks resolved.
*
* For a main program this is not necessarily the same as the file name used in the
* command line.
* @since v0.0.1
*/
var __filename: string;
/**
* The `exports` variable is available within a module's file-level scope, and is
* assigned the value of `module.exports` before the module is evaluated.
* @since v0.1.16
*/
var exports: NodeJS.Module["exports"];
/**
* A reference to the current module.
* @since v0.1.16
*/
var module: NodeJS.Module;
/**
* @since v0.1.13
*/
var require: NodeJS.Require;
// Global-scope aliases for backwards compatibility with @types/node <13.0.x
// TODO: consider removing in a future major version update
/** @deprecated Use `NodeJS.Module` instead. */
interface NodeModule extends NodeJS.Module {}
/** @deprecated Use `NodeJS.Require` instead. */
interface NodeRequire extends NodeJS.Require {}
/** @deprecated Use `NodeJS.RequireResolve` instead. */
interface RequireResolve extends NodeJS.RequireResolve {}
}
export = Module;
}
declare module "module" {
import module = require("node:module");
export = module;
}

View File

@@ -0,0 +1,31 @@
/**
* Audited & minimal JS implementation of hash functions, MACs and KDFs. Check out individual modules.
* @module
* @example
```js
import {
sha256, sha384, sha512, sha224, sha512_224, sha512_256
} from '@noble/hashes/sha2';
import {
sha3_224, sha3_256, sha3_384, sha3_512,
keccak_224, keccak_256, keccak_384, keccak_512,
shake128, shake256
} from '@noble/hashes/sha3';
import {
cshake128, cshake256,
turboshake128, turboshake256,
kmac128, kmac256,
tuplehash256, parallelhash256,
k12, m14, keccakprg
} from '@noble/hashes/sha3-addons';
import { blake3 } from '@noble/hashes/blake3';
import { blake2b, blake2s } from '@noble/hashes/blake2';
import { hmac } from '@noble/hashes/hmac';
import { hkdf } from '@noble/hashes/hkdf';
import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2';
import { scrypt, scryptAsync } from '@noble/hashes/scrypt';
import { md5, ripemd160, sha1 } from '@noble/hashes/legacy';
import * as utils from '@noble/hashes/utils';
```
*/
throw new Error('root module cannot be imported: import submodules instead. Check out README');

View File

@@ -0,0 +1,41 @@
"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.withoutProjectParserOptions = exports.version = exports.typescriptVersionIsAtLeast = exports.simpleTraverse = exports.clearCandidateTSConfigRootDirs = exports.addCandidateTSConfigRootDir = exports.parseAndGenerateServices = exports.parse = exports.TSError = exports.createProgram = exports.getCanonicalFileName = void 0;
__exportStar(require("./clear-caches"), exports);
__exportStar(require("./create-program/getScriptKind"), exports);
var shared_1 = require("./create-program/shared");
Object.defineProperty(exports, "getCanonicalFileName", { enumerable: true, get: function () { return shared_1.getCanonicalFileName; } });
var useProvidedPrograms_1 = require("./create-program/useProvidedPrograms");
Object.defineProperty(exports, "createProgram", { enumerable: true, get: function () { return useProvidedPrograms_1.createProgramFromConfigFile; } });
__exportStar(require("./getModifiers"), exports);
var node_utils_1 = require("./node-utils");
Object.defineProperty(exports, "TSError", { enumerable: true, get: function () { return node_utils_1.TSError; } });
var parser_1 = require("./parser");
Object.defineProperty(exports, "parse", { enumerable: true, get: function () { return parser_1.parse; } });
Object.defineProperty(exports, "parseAndGenerateServices", { enumerable: true, get: function () { return parser_1.parseAndGenerateServices; } });
var candidateTSConfigRootDirs_1 = require("./parseSettings/candidateTSConfigRootDirs");
Object.defineProperty(exports, "addCandidateTSConfigRootDir", { enumerable: true, get: function () { return candidateTSConfigRootDirs_1.addCandidateTSConfigRootDir; } });
Object.defineProperty(exports, "clearCandidateTSConfigRootDirs", { enumerable: true, get: function () { return candidateTSConfigRootDirs_1.clearCandidateTSConfigRootDirs; } });
var simple_traverse_1 = require("./simple-traverse");
Object.defineProperty(exports, "simpleTraverse", { enumerable: true, get: function () { return simple_traverse_1.simpleTraverse; } });
__exportStar(require("./ts-estree"), exports);
var version_check_1 = require("./version-check");
Object.defineProperty(exports, "typescriptVersionIsAtLeast", { enumerable: true, get: function () { return version_check_1.typescriptVersionIsAtLeast; } });
var version_1 = require("./version");
Object.defineProperty(exports, "version", { enumerable: true, get: function () { return version_1.version; } });
var withoutProjectParserOptions_1 = require("./withoutProjectParserOptions");
Object.defineProperty(exports, "withoutProjectParserOptions", { enumerable: true, get: function () { return withoutProjectParserOptions_1.withoutProjectParserOptions; } });