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,45 @@
'use strict'
module.exports = filterLog
const { createCopier } = require('fast-copy')
const fastCopy = createCopier({})
const deleteLogProperty = require('./delete-log-property')
/**
* @typedef {object} FilterLogParams
* @property {object} log The log object to be modified.
* @property {PrettyContext} context The context object built from parsing
* the options.
*/
/**
* Filter a log object by removing or including keys accordingly.
* When `includeKeys` is passed, `ignoredKeys` will be ignored.
* One of ignoreKeys or includeKeys must be pass in.
*
* @param {FilterLogParams} input
*
* @returns {object} A new `log` object instance that
* either only includes the keys in ignoreKeys
* or does not include those in ignoredKeys.
*/
function filterLog ({ log, context }) {
const { ignoreKeys, includeKeys } = context
const logCopy = fastCopy(log)
if (includeKeys) {
const logIncluded = {}
includeKeys.forEach((key) => {
logIncluded[key] = logCopy[key]
})
return logIncluded
}
ignoreKeys.forEach((ignoreKey) => {
deleteLogProperty(logCopy, ignoreKey)
})
return logCopy
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"blake1.d.ts","sourceRoot":"","sources":["../src/blake1.ts"],"names":[],"mappings":"AA4BA,OAAO,EAGO,IAAI,EAChB,KAAK,MAAM,EAAE,KAAK,KAAK,EACxB,MAAM,YAAY,CAAC;AAEpB,4CAA4C;AAC5C,MAAM,MAAM,SAAS,GAAG;IACtB,IAAI,CAAC,EAAE,UAAU,CAAC;CACnB,CAAC;AAKF,uBAAe,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,CAAC,CAAC,CAAE,SAAQ,IAAI,CAAC,CAAC,CAAC;IACxD,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,MAAM,SAAK;IACrB,SAAS,CAAC,GAAG,SAAK;IAClB,SAAS,CAAC,SAAS,UAAS;IAE5B,SAAS,CAAC,MAAM,EAAE,UAAU,CAAC;IAC7B,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC;I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,22 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABILITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference lib="es2017" />
/// <reference lib="es2018.asynciterable" />
/// <reference lib="es2018.asyncgenerator" />
/// <reference lib="es2018.promise" />
/// <reference lib="es2018.regexp" />
/// <reference lib="es2018.intl" />

View File

@@ -0,0 +1,303 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const scope_manager_1 = require("@typescript-eslint/scope-manager");
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
const referenceContainsTypeQuery_1 = require("../util/referenceContainsTypeQuery");
const SENTINEL_TYPE = /^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration)$/;
/**
* Parses a given value as options.
*/
function parseOptions(options) {
let functions = true;
let classes = true;
let enums = true;
let variables = true;
let typedefs = true;
let ignoreTypeReferences = true;
let allowNamedExports = false;
if (typeof options === 'string') {
functions = options !== 'nofunc';
}
else if (typeof options === 'object' && options != null) {
functions = options.functions !== false;
classes = options.classes !== false;
enums = options.enums !== false;
variables = options.variables !== false;
typedefs = options.typedefs !== false;
ignoreTypeReferences = options.ignoreTypeReferences !== false;
allowNamedExports = options.allowNamedExports !== false;
}
return {
allowNamedExports,
classes,
enums,
functions,
ignoreTypeReferences,
typedefs,
variables,
};
}
/**
* Checks whether or not a given variable is a function declaration.
*/
function isFunction(variable) {
return variable.defs[0].type === scope_manager_1.DefinitionType.FunctionName;
}
/**
* Checks whether or not a given variable is a type declaration.
*/
function isTypedef(variable) {
return variable.defs[0].type === scope_manager_1.DefinitionType.Type;
}
/**
* Checks whether or not a given variable is a enum declaration.
*/
function isOuterEnum(variable, reference) {
return (variable.defs[0].type === scope_manager_1.DefinitionType.TSEnumName &&
variable.scope.variableScope !== reference.from.variableScope);
}
/**
* Checks whether or not a given variable is a class declaration in an upper function scope.
*/
function isOuterClass(variable, reference) {
return (variable.defs[0].type === scope_manager_1.DefinitionType.ClassName &&
variable.scope.variableScope !== reference.from.variableScope);
}
/**
* Checks whether or not a given variable is a variable declaration in an upper function scope.
*/
function isOuterVariable(variable, reference) {
return (variable.defs[0].type === scope_manager_1.DefinitionType.Variable &&
variable.scope.variableScope !== reference.from.variableScope);
}
/**
* Checks whether or not a given reference is a export reference.
*/
function isNamedExports(reference) {
const { identifier } = reference;
return (identifier.parent.type === utils_1.AST_NODE_TYPES.ExportSpecifier &&
identifier.parent.local === identifier);
}
/**
* Checks whether or not a given reference is a type reference.
*/
function isTypeReference(reference) {
return (reference.isTypeReference ||
(0, referenceContainsTypeQuery_1.referenceContainsTypeQuery)(reference.identifier));
}
/**
* Checks whether or not a given location is inside of the range of a given node.
*/
function isInRange(node, location) {
return !!node && node.range[0] <= location && location <= node.range[1];
}
/**
* Decorators are transpiled such that the decorator is placed after the class declaration
* So it is considered safe
*/
function isClassRefInClassDecorator(variable, reference) {
if (variable.defs[0].type !== scope_manager_1.DefinitionType.ClassName ||
variable.defs[0].node.decorators.length === 0) {
return false;
}
for (const deco of variable.defs[0].node.decorators) {
if (reference.identifier.range[0] >= deco.range[0] &&
reference.identifier.range[1] <= deco.range[1]) {
return true;
}
}
return false;
}
/**
* Checks whether or not a given reference is inside of the initializers of a given variable.
*
* @returns `true` in the following cases:
* - var a = a
* - var [a = a] = list
* - var {a = a} = obj
* - for (var a in a) {}
* - for (var a of a) {}
*/
function isInInitializer(variable, reference) {
if (variable.scope !== reference.from) {
return false;
}
let node = variable.identifiers[0].parent;
const location = reference.identifier.range[1];
while (node) {
if (node.type === utils_1.AST_NODE_TYPES.VariableDeclarator) {
if (isInRange(node.init, location)) {
return true;
}
if ((node.parent.parent.type === utils_1.AST_NODE_TYPES.ForInStatement ||
node.parent.parent.type === utils_1.AST_NODE_TYPES.ForOfStatement) &&
isInRange(node.parent.parent.right, location)) {
return true;
}
break;
}
else if (node.type === utils_1.AST_NODE_TYPES.AssignmentPattern) {
if (isInRange(node.right, location)) {
return true;
}
}
else if (SENTINEL_TYPE.test(node.type)) {
break;
}
node = node.parent;
}
return false;
}
exports.default = (0, util_1.createRule)({
name: 'no-use-before-define',
meta: {
type: 'problem',
docs: {
description: 'Disallow the use of variables before they are defined',
extendsBaseRule: true,
},
messages: {
noUseBeforeDefine: "'{{name}}' was used before it was defined.",
},
schema: [
{
oneOf: [
{
type: 'string',
description: 'Broadly set functions and allowNamedExports to false.',
enum: ['nofunc'],
},
{
type: 'object',
additionalProperties: false,
properties: {
allowNamedExports: {
type: 'boolean',
description: 'Whether to ignore named exports.',
},
classes: {
type: 'boolean',
description: 'Whether to ignore references to class declarations.',
},
enums: {
type: 'boolean',
description: 'Whether to check references to enums.',
},
functions: {
type: 'boolean',
description: 'Whether to ignore references to function declarations.',
},
ignoreTypeReferences: {
type: 'boolean',
description: 'Whether to ignore type references, such as in type annotations and assertions.',
},
typedefs: {
type: 'boolean',
description: 'Whether to check references to types.',
},
variables: {
type: 'boolean',
description: 'Whether to ignore references to variables.',
},
},
},
],
},
],
},
defaultOptions: [
{
allowNamedExports: false,
classes: true,
enums: true,
functions: true,
ignoreTypeReferences: true,
typedefs: true,
variables: true,
},
],
create(context, optionsWithDefault) {
const options = parseOptions(optionsWithDefault[0]);
/**
* Determines whether a given use-before-define case should be reported according to the options.
* @param variable The variable that gets used before being defined
* @param reference The reference to the variable
*/
function isForbidden(variable, reference) {
if (options.ignoreTypeReferences && isTypeReference(reference)) {
return false;
}
if (isFunction(variable)) {
return options.functions;
}
if (isOuterClass(variable, reference)) {
return options.classes;
}
if (isOuterVariable(variable, reference)) {
return options.variables;
}
if (isOuterEnum(variable, reference)) {
return options.enums;
}
if (isTypedef(variable)) {
return options.typedefs;
}
return true;
}
function isDefinedBeforeUse(variable, reference) {
return (variable.identifiers[0].range[1] <= reference.identifier.range[1] &&
!(reference.isValueReference && isInInitializer(variable, reference)));
}
/**
* Finds and validates all variables in a given scope.
*/
function findVariablesInScope(scope) {
scope.references.forEach(reference => {
const variable = reference.resolved;
function report() {
context.report({
node: reference.identifier,
messageId: 'noUseBeforeDefine',
data: {
name: reference.identifier.name,
},
});
}
// Skips when the reference is:
// - initializations.
// - referring to an undefined variable.
// - referring to a global environment variable (there're no identifiers).
// - located preceded by the variable (except in initializers).
// - allowed by options.
if (reference.init) {
return;
}
if (!options.allowNamedExports && isNamedExports(reference)) {
if (!variable || !isDefinedBeforeUse(variable, reference)) {
report();
}
return;
}
if (!variable) {
return;
}
if (variable.identifiers.length === 0 ||
isDefinedBeforeUse(variable, reference) ||
!isForbidden(variable, reference) ||
isClassRefInClassDecorator(variable, reference) ||
reference.from.type === utils_1.TSESLint.Scope.ScopeType.functionType) {
return;
}
// Reports.
report();
});
scope.childScopes.forEach(findVariablesInScope);
}
return {
Program(node) {
findVariablesInScope(context.sourceCode.getScope(node));
},
};
},
});

View File

@@ -0,0 +1,115 @@
/**
* @fileoverview Enforces or disallows inline comments.
* @author Greg Cochard
*/
"use strict";
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
defaultOptions: [{}],
docs: {
description: "Disallow inline comments after code",
recommended: false,
frozen: true,
url: "https://eslint.org/docs/latest/rules/no-inline-comments",
},
schema: [
{
type: "object",
properties: {
ignorePattern: {
type: "string",
},
},
additionalProperties: false,
},
],
messages: {
unexpectedInlineComment: "Unexpected comment inline with code.",
},
},
create(context) {
const sourceCode = context.sourceCode;
const [{ ignorePattern }] = context.options;
const customIgnoreRegExp =
ignorePattern && new RegExp(ignorePattern, "u");
/**
* Will check that comments are not on lines starting with or ending with code
* @param {ASTNode} node The comment node to check
* @private
* @returns {void}
*/
function testCodeAroundComment(node) {
const startLine = String(sourceCode.lines[node.loc.start.line - 1]),
endLine = String(sourceCode.lines[node.loc.end.line - 1]),
preamble = startLine.slice(0, node.loc.start.column).trim(),
postamble = endLine.slice(node.loc.end.column).trim(),
isPreambleEmpty = !preamble,
isPostambleEmpty = !postamble;
// Nothing on both sides
if (isPreambleEmpty && isPostambleEmpty) {
return;
}
// Matches the ignore pattern
if (customIgnoreRegExp && customIgnoreRegExp.test(node.value)) {
return;
}
// JSX Exception
if (
(isPreambleEmpty || preamble === "{") &&
(isPostambleEmpty || postamble === "}")
) {
const enclosingNode = sourceCode.getNodeByRangeIndex(
node.range[0],
);
if (
enclosingNode &&
enclosingNode.type === "JSXEmptyExpression"
) {
return;
}
}
// Don't report ESLint directive comments
if (astUtils.isDirectiveComment(node)) {
return;
}
context.report({
node,
messageId: "unexpectedInlineComment",
});
}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
return {
Program() {
sourceCode
.getAllComments()
.filter(token => token.type !== "Shebang")
.forEach(testCodeAroundComment);
},
};
},
};

View File

@@ -0,0 +1,2 @@
export declare var ObjectFlags: any;
//# sourceMappingURL=objectFlags.d.ts.map

View File

@@ -0,0 +1,110 @@
{
"author": {
"email": "tony.quetano@planttheidea.com",
"name": "Tony Quetano",
"url": "https://www.planttheidea.com/"
},
"browser": "./dist/umd/index.js",
"bugs": {
"url": "https://github.com/planttheidea/fast-copy/issues"
},
"contributors": [
"Dariusz Rzepka <rzepkadarek@gmail.com>"
],
"description": "A blazing fast deep object copier",
"devDependencies": {
"@planttheidea/build-tools": "^2.0.2",
"@types/lodash": "^4.17.24",
"@types/node": "^24.13.3",
"@types/ramda": "^0.32.0",
"@types/react": "^19.2.17",
"@vitest/coverage-v8": "^4.1.10",
"cli-table3": "^0.6.5",
"clone": "^2.1.2",
"deepclone": "^1.0.2",
"eslint": "^9.39.4",
"fast-clone": "^1.5.13",
"lodash": "^4.18.1",
"prettier": "^3.9.4",
"ramda": "^0.32.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"release-it": "^20.2.1",
"rollup": "^4.62.2",
"tinybench": "^6.0.2",
"typescript": "^5.9.3",
"vite": "^8.1.3",
"vitest": "^4.1.10"
},
"exports": {
".": {
"import": {
"types": "./dist/es/index.d.mts",
"default": "./dist/es/index.mjs"
},
"require": {
"types": "./dist/cjs/index.d.cts",
"default": "./dist/cjs/index.cjs"
},
"default": {
"types": "./dist/umd/index.d.ts",
"default": "./dist/umd/index.js"
}
}
},
"files": [
"dist",
"LICENSE",
"README.md",
"index.d.ts",
"package.json"
],
"homepage": "https://github.com/planttheidea/fast-copy#readme",
"keywords": [
"clone",
"deep",
"copy",
"fast"
],
"license": "MIT",
"main": "./dist/cjs/index.cjs",
"module": "./dist/es/index.mjs",
"name": "fast-copy",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/planttheidea/fast-copy.git"
},
"scripts": {
"benchmark": "npm run build && node benchmark/index.js",
"build": "npm run clean && npm run build:dist",
"build:dist": "NODE_ENV=production rollup -c config/rollup.config.js",
"build:types": "pti fix-types -l dist",
"clean": "rm -rf dist",
"clean:cjs": "rm -rf dist/cjs",
"clean:es": "rm -rf dist/es",
"clean:esm": "rm -rf dist/esm",
"clean:min": "rm -rf dist/min",
"clean:umd": "rm -rf dist/umd",
"dev": "vite --config=config/vite.config.ts",
"format": "prettier . --log-level=warn --write",
"format:check": "prettier . --log-level=warn --check",
"lint": "eslint --max-warnings=0",
"lint:fix": "npm run lint -- --fix",
"release:alpha": "release-it --config=config/release-it/alpha.json",
"release:beta": "release-it --config=config/release-it/beta.json",
"release:dry": "release-it --dry-run",
"release:rc": "release-it --config=config/release-it/rc.json",
"release:scripts": "npm run format:check && npm run typecheck && npm run lint && npm run test && npm run build",
"release:stable": "release-it --config=config/release-it/stable.json",
"start": "npm run dev",
"test": "vitest run --config=config/vitest.config.ts",
"typecheck": "tsc --noEmit"
},
"sideEffects": false,
"type": "module",
"types": "./index.d.ts",
"version": "4.0.4"
}

View File

@@ -0,0 +1,11 @@
import * as fs from 'node:fs'
import { once } from 'node:events'
async function run (opts: { destination?: fs.PathLike }): Promise<fs.WriteStream> {
if (!opts.destination) throw new Error('kaboom')
const stream = fs.createWriteStream(opts.destination, { encoding: 'utf8' })
await once(stream, 'open')
return stream
}
export default run

View File

@@ -0,0 +1,329 @@
export type VisitTraversalStep = $eslintcore.VisitTraversalStep;
export type CallTraversalStep = $eslintcore.CallTraversalStep;
export type TraversalStep = $eslintcore.TraversalStep;
export type SourceLocation = $eslintcore.SourceLocation;
export type SourceLocationWithOffset = $eslintcore.SourceLocationWithOffset;
export type SourceRange = $eslintcore.SourceRange;
export type IDirective = $eslintcore.Directive;
export type DirectiveType = $eslintcore.DirectiveType;
export type SourceCodeBaseTypeOptions = $eslintcore.SourceCodeBaseTypeOptions;
export type TextSourceCode<Options extends SourceCodeBaseTypeOptions = $eslintcore.SourceCodeBaseTypeOptions> = import("@eslint/core").TextSourceCode<Options>;
export type RuleVisitor = $eslintcore.RuleVisitor;
export type CustomRuleVisitorWithExit<RuleVisitorType extends RuleVisitor> = import("./types.cts").CustomRuleVisitorWithExit<RuleVisitorType>;
export type CustomRuleTypeDefinitions = $typests.CustomRuleTypeDefinitions;
export type CustomRuleDefinitionType<LanguageSpecificOptions extends Omit<import("@eslint/core").RuleDefinitionTypeOptions, keyof CustomRuleTypeDefinitions>, Options extends Partial<CustomRuleTypeDefinitions>> = import("./types.cts").CustomRuleDefinitionType<LanguageSpecificOptions, Options>;
export type RuleConfig = $eslintcore.RuleConfig;
export type RulesConfig = $eslintcore.RulesConfig;
export type StringConfig = $typests.StringConfig;
export type BooleanConfig = $typests.BooleanConfig;
/**
* A class to represent a step in the traversal process where a
* method is called.
* @implements {CallTraversalStep}
*/
export class CallMethodStep implements CallTraversalStep {
/**
* Creates a new instance.
* @param {Object} options The options for the step.
* @param {string} options.target The target of the step.
* @param {Array<any>} options.args The arguments of the step.
*/
constructor({ target, args }: {
target: string;
args: Array<any>;
});
/**
* The type of the step.
* @type {"call"}
* @readonly
*/
readonly type: "call";
/**
* The kind of the step. Represents the same data as the `type` property
* but it's a number for performance.
* @type {2}
* @readonly
*/
readonly kind: 2;
/**
* The name of the method to call.
* @type {string}
*/
target: string;
/**
* The arguments to pass to the method.
* @type {Array<any>}
*/
args: Array<any>;
}
/**
* Object to parse ESLint configuration comments.
*/
export class ConfigCommentParser {
/**
* Parses a list of "name:string_value" or/and "name" options divided by comma or
* whitespace. Used for "global" comments.
* @param {string} string The string to parse.
* @returns {StringConfig} Result map object of names and string values, or null values if no value was provided.
*/
parseStringConfig(string: string): StringConfig;
/**
* Parses a JSON-like config.
* @param {string} string The string to parse.
* @returns {({ok: true, config: RulesConfig}|{ok: false, error: {message: string}})} Result map object
*/
parseJSONLikeConfig(string: string): ({
ok: true;
config: RulesConfig;
} | {
ok: false;
error: {
message: string;
};
});
/**
* Parses a config of values separated by comma.
* @param {string} string The string to parse.
* @returns {BooleanConfig} Result map of values and true values
*/
parseListConfig(string: string): BooleanConfig;
/**
* Parses a directive comment into directive text and value.
* @param {string} string The string with the directive to be parsed.
* @returns {DirectiveComment|undefined} The parsed directive or `undefined` if the directive is invalid.
*/
parseDirective(string: string): DirectiveComment | undefined;
#private;
}
/**
* A class to represent a directive comment.
* @implements {IDirective}
*/
export class Directive implements IDirective {
/**
* Creates a new instance.
* @param {Object} options The options for the directive.
* @param {"disable"|"enable"|"disable-next-line"|"disable-line"} options.type The type of directive.
* @param {unknown} options.node The node representing the directive.
* @param {string} options.value The value of the directive.
* @param {string} options.justification The justification for the directive.
*/
constructor({ type, node, value, justification }: {
type: "disable" | "enable" | "disable-next-line" | "disable-line";
node: unknown;
value: string;
justification: string;
});
/**
* The type of directive.
* @type {DirectiveType}
* @readonly
*/
readonly type: DirectiveType;
/**
* The node representing the directive.
* @type {unknown}
* @readonly
*/
readonly node: unknown;
/**
* Everything after the "eslint-disable" portion of the directive,
* but before the "--" that indicates the justification.
* @type {string}
* @readonly
*/
readonly value: string;
/**
* The justification for the directive.
* @type {string}
* @readonly
*/
readonly justification: string;
}
/**
* Source Code Base Object
* @template {SourceCodeBaseTypeOptions & {RootNode: object, SyntaxElementWithLoc: object}} [Options=SourceCodeBaseTypeOptions & {RootNode: object, SyntaxElementWithLoc: object}]
* @implements {TextSourceCode<Options>}
*/
export class TextSourceCodeBase<Options extends SourceCodeBaseTypeOptions & {
RootNode: object;
SyntaxElementWithLoc: object;
} = $eslintcore.SourceCodeBaseTypeOptions & {
RootNode: object;
SyntaxElementWithLoc: object;
}> implements TextSourceCode<Options> {
/**
* Creates a new instance.
* @param {Object} options The options for the instance.
* @param {string} options.text The source code text.
* @param {Options['RootNode']} options.ast The root AST node.
* @param {RegExp} [options.lineEndingPattern] The pattern to match lineEndings in the source code. Defaults to `/\r?\n/u`.
*/
constructor({ text, ast, lineEndingPattern }: {
text: string;
ast: Options["RootNode"];
lineEndingPattern?: RegExp;
});
/**
* The AST of the source code.
* @type {Options['RootNode']}
*/
ast: Options["RootNode"];
/**
* The text of the source code.
* @type {string}
*/
text: string;
/**
* Returns the loc information for the given node or token.
* @param {Options['SyntaxElementWithLoc']} nodeOrToken The node or token to get the loc information for.
* @returns {SourceLocation} The loc information for the node or token.
* @throws {Error} If the node or token does not have loc information.
*/
getLoc(nodeOrToken: Options["SyntaxElementWithLoc"]): SourceLocation;
/**
* Converts a source text index into a `{ line: number, column: number }` pair.
* @param {number} index The index of a character in a file.
* @throws {TypeError|RangeError} If non-numeric index or index out of range.
* @returns {{line: number, column: number}} A `{ line: number, column: number }` location object with 0 or 1-indexed line and 0 or 1-indexed column based on language.
* @public
*/
public getLocFromIndex(index: number): {
line: number;
column: number;
};
/**
* Converts a `{ line: number, column: number }` pair into a source text index.
* @param {Object} loc A line/column location.
* @param {number} loc.line The line number of the location. (0 or 1-indexed based on language.)
* @param {number} loc.column The column number of the location. (0 or 1-indexed based on language.)
* @throws {TypeError|RangeError} If `loc` is not an object with a numeric
* `line` and `column`, if the `line` is less than or equal to zero or
* the `line` or `column` is out of the expected range.
* @returns {number} The index of the line/column location in a file.
* @public
*/
public getIndexFromLoc(loc: {
line: number;
column: number;
}): number;
/**
* Returns the range information for the given node or token.
* @param {Options['SyntaxElementWithLoc']} nodeOrToken The node or token to get the range information for.
* @returns {SourceRange} The range information for the node or token.
* @throws {Error} If the node or token does not have range information.
*/
getRange(nodeOrToken: Options["SyntaxElementWithLoc"]): SourceRange;
/**
* Returns the parent of the given node.
* @param {Options['SyntaxElementWithLoc']} node The node to get the parent of.
* @returns {Options['SyntaxElementWithLoc']|undefined} The parent of the node.
* @throws {Error} If the method is not implemented in the subclass.
*/
getParent(node: Options["SyntaxElementWithLoc"]): Options["SyntaxElementWithLoc"] | undefined;
/**
* Gets all the ancestors of a given node
* @param {Options['SyntaxElementWithLoc']} node The node
* @returns {Array<Options['SyntaxElementWithLoc']>} All the ancestor nodes in the AST, not including the provided node, starting
* from the root node at index 0 and going inwards to the parent node.
* @throws {TypeError} When `node` is missing.
*/
getAncestors(node: Options["SyntaxElementWithLoc"]): Array<Options["SyntaxElementWithLoc"]>;
/**
* Gets the source code for the given node.
* @param {Options['SyntaxElementWithLoc']} [node] The AST node to get the text for.
* @param {number} [beforeCount] The number of characters before the node to retrieve.
* @param {number} [afterCount] The number of characters after the node to retrieve.
* @returns {string} The text representing the AST node.
* @public
*/
public getText(node?: Options["SyntaxElementWithLoc"], beforeCount?: number, afterCount?: number): string;
/**
* Gets the entire source text split into an array of lines.
* @returns {Array<string>} The source text as an array of lines.
* @public
*/
public get lines(): Array<string>;
/**
* Traverse the source code and return the steps that were taken.
* @returns {Iterable<TraversalStep>} The steps that were taken while traversing the source code.
*/
traverse(): Iterable<TraversalStep>;
#private;
}
/**
* A class to represent a step in the traversal process where a node is visited.
* @implements {VisitTraversalStep}
*/
export class VisitNodeStep implements VisitTraversalStep {
/**
* Creates a new instance.
* @param {Object} options The options for the step.
* @param {object} options.target The target of the step.
* @param {1|2} options.phase The phase of the step.
* @param {Array<any>} options.args The arguments of the step.
*/
constructor({ target, phase, args }: {
target: object;
phase: 1 | 2;
args: Array<any>;
});
/**
* The type of the step.
* @type {"visit"}
* @readonly
*/
readonly type: "visit";
/**
* The kind of the step. Represents the same data as the `type` property
* but it's a number for performance.
* @type {1}
* @readonly
*/
readonly kind: 1;
/**
* The target of the step.
* @type {object}
*/
target: object;
/**
* The phase of the step.
* @type {1|2}
*/
phase: 1 | 2;
/**
* The arguments of the step.
* @type {Array<any>}
*/
args: Array<any>;
}
import type * as $eslintcore from "@eslint/core";
import type * as $typests from "./types.cts";
/**
* Represents a directive comment.
*/
declare class DirectiveComment {
/**
* Creates a new directive comment.
* @param {string} label The label of the directive.
* @param {string} value The value of the directive.
* @param {string} justification The justification of the directive.
*/
constructor(label: string, value: string, justification: string);
/**
* The label of the directive, such as "eslint", "eslint-disable", etc.
* @type {string}
*/
label: string;
/**
* The value of the directive (the string after the label).
* @type {string}
*/
value: string;
/**
* The justification of the directive (the string after the --).
* @type {string}
*/
justification: string;
}
export {};

View File

@@ -0,0 +1,54 @@
import { BLAKE2 } from './blake2.ts';
import { type CHashXO, type HashXOF, type Input } from './utils.ts';
/**
* Ensure to use EITHER `key` OR `context`, not both.
*
* * `key`: 32-byte MAC key.
* * `context`: string for KDF. Should be hardcoded, globally unique, and application - specific.
* A good default format for the context string is "[application] [commit timestamp] [purpose]".
*/
export type Blake3Opts = {
dkLen?: number;
key?: Input;
context?: Input;
};
/** Blake3 hash. Can be used as MAC and KDF. */
export declare class BLAKE3 extends BLAKE2<BLAKE3> implements HashXOF<BLAKE3> {
private chunkPos;
private chunksDone;
private flags;
private IV;
private state;
private stack;
private posOut;
private bufferOut32;
private bufferOut;
private chunkOut;
private enableXOF;
constructor(opts?: Blake3Opts, flags?: number);
protected get(): [];
protected set(): void;
private b2Compress;
protected compress(buf: Uint32Array, bufPos?: number, isLast?: boolean): void;
_cloneInto(to?: BLAKE3): BLAKE3;
destroy(): void;
private b2CompressOut;
protected finish(): void;
private writeInto;
xofInto(out: Uint8Array): Uint8Array;
xof(bytes: number): Uint8Array;
digestInto(out: Uint8Array): Uint8Array;
digest(): Uint8Array;
}
/**
* BLAKE3 hash function. Can be used as MAC and KDF.
* @param msg - message that would be hashed
* @param opts - `dkLen` for output length, `key` for MAC mode, `context` for KDF mode
* @example
* const data = new Uint8Array(32);
* const hash = blake3(data);
* const mac = blake3(data, { key: new Uint8Array(32) });
* const kdf = blake3(data, { context: 'application name' });
*/
export declare const blake3: CHashXO;
//# sourceMappingURL=blake3.d.ts.map

View File

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

View File

@@ -0,0 +1,49 @@
const SAFE_TIMERS_SYMBOL = Symbol("vitest:SAFE_TIMERS");
function getSafeTimers() {
const { setTimeout: safeSetTimeout, setInterval: safeSetInterval, clearInterval: safeClearInterval, clearTimeout: safeClearTimeout, setImmediate: safeSetImmediate, clearImmediate: safeClearImmediate, queueMicrotask: safeQueueMicrotask } = globalThis[SAFE_TIMERS_SYMBOL] || globalThis;
const { nextTick: safeNextTick } = globalThis[SAFE_TIMERS_SYMBOL] || globalThis.process || {};
return {
nextTick: safeNextTick,
setTimeout: safeSetTimeout,
setInterval: safeSetInterval,
clearInterval: safeClearInterval,
clearTimeout: safeClearTimeout,
setImmediate: safeSetImmediate,
clearImmediate: safeClearImmediate,
queueMicrotask: safeQueueMicrotask
};
}
function setSafeTimers() {
const { setTimeout: safeSetTimeout, setInterval: safeSetInterval, clearInterval: safeClearInterval, clearTimeout: safeClearTimeout, setImmediate: safeSetImmediate, clearImmediate: safeClearImmediate, queueMicrotask: safeQueueMicrotask } = globalThis;
const { nextTick: safeNextTick } = globalThis.process || {};
const timers = {
nextTick: safeNextTick,
setTimeout: safeSetTimeout,
setInterval: safeSetInterval,
clearInterval: safeClearInterval,
clearTimeout: safeClearTimeout,
setImmediate: safeSetImmediate,
clearImmediate: safeClearImmediate,
queueMicrotask: safeQueueMicrotask
};
globalThis[SAFE_TIMERS_SYMBOL] = timers;
}
/**
* Returns a promise that resolves after the specified duration.
*
* @param timeout - Delay in milliseconds
* @param scheduler - Timer function to use, defaults to `setTimeout`. Useful for mocked timers.
*
* @example
* await delay(100)
*
* @example
* // With mocked timers
* const { setTimeout } = getSafeTimers()
* await delay(100, setTimeout)
*/
function delay(timeout, scheduler = setTimeout) {
return new Promise((resolve) => scheduler(resolve, timeout));
}
export { delay, getSafeTimers, setSafeTimers };

View File

@@ -0,0 +1,82 @@
{
"name": "@typescript-eslint/project-service",
"version": "8.67.0",
"description": "Standalone TypeScript project service wrapper for linting.",
"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/project-service"
},
"bugs": {
"url": "https://github.com/typescript-eslint/typescript-eslint/issues"
},
"homepage": "https://typescript-eslint.io",
"license": "MIT",
"keywords": [
"eslint",
"typescript",
"estree"
],
"peerDependencies": {
"typescript": ">=4.8.4 <6.1.0"
},
"dependencies": {
"debug": "^4.4.3",
"@typescript-eslint/types": "^8.67.0",
"@typescript-eslint/tsconfig-utils": "^8.67.0"
},
"devDependencies": {
"@typescript/native": "npm:typescript@^7.0.2",
"@vitest/coverage-v8": "^4.0.18",
"rimraf": "^5.0.10",
"typescript": ">=4.8.4 <6.1.0",
"vitest": "^4.0.18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"publishConfig": {
"access": "public"
},
"nx": {
"name": "project-service",
"includedScripts": [
"clean"
],
"targets": {
"lint": {
"command": "eslint"
},
"typecheck:tsgo": {},
"attw-check": {}
}
},
"scripts": {
"//": "These package scripts are mostly here for convenience. Task running is handled by Nx at the root level.",
"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,453 @@
/**
* @fileoverview A rule to suggest using arrow functions as callbacks.
* @author Toru Nagashima
*/
"use strict";
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Types
//------------------------------------------------------------------------------
/** @typedef {import("eslint-scope").Scope} Scope */
/** @typedef {import("eslint-scope").Variable} Variable */
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Checks whether or not a given variable is a function name.
* @param {Variable} variable A variable to check.
* @returns {boolean} `true` if the variable is a function name.
*/
function isFunctionName(variable) {
return variable && variable.defs[0].type === "FunctionName";
}
/**
* Checks whether or not a given MetaProperty node equals to a given value.
* @param {ASTNode} node A MetaProperty node to check.
* @param {string} metaName The name of `MetaProperty.meta`.
* @param {string} propertyName The name of `MetaProperty.property`.
* @returns {boolean} `true` if the node is the specific value.
*/
function checkMetaProperty(node, metaName, propertyName) {
return node.meta.name === metaName && node.property.name === propertyName;
}
/**
* Gets the variable object of `arguments` which is defined implicitly.
* @param {Scope} scope A scope to get.
* @returns {Variable} The found variable object.
*/
function getVariableOfArguments(scope) {
const variables = scope.variables;
for (let i = 0; i < variables.length; ++i) {
const variable = variables[i];
if (variable.name === "arguments") {
/*
* If there was a parameter which is named "arguments", the
* implicit "arguments" is not defined.
* So does fast return with null.
*/
return variable.identifiers.length === 0 ? variable : null;
}
}
/* c8 ignore next */
return null;
}
/**
* Checks whether or not a given node is a callback.
* @param {ASTNode} node A node to check.
* @throws {Error} (Unreachable.)
* @returns {Object}
* {boolean} retv.isCallback - `true` if the node is a callback.
* {boolean} retv.isLexicalThis - `true` if the node is with `.bind(this)`.
*/
function getCallbackInfo(node) {
const retv = { isCallback: false, isLexicalThis: false };
let currentNode = node;
let parent = node.parent;
let bound = false;
while (currentNode) {
switch (parent.type) {
// Checks parents recursively.
case "LogicalExpression":
case "ChainExpression":
case "ConditionalExpression":
break;
// Checks whether the parent node is `.bind(this)` call.
case "MemberExpression":
if (
parent.object === currentNode &&
!parent.property.computed &&
parent.property.type === "Identifier" &&
parent.property.name === "bind"
) {
const maybeCallee =
parent.parent.type === "ChainExpression"
? parent.parent
: parent;
if (astUtils.isCallee(maybeCallee)) {
if (!bound) {
bound = true; // Use only the first `.bind()` to make `isLexicalThis` value.
retv.isLexicalThis =
maybeCallee.parent.arguments.length === 1 &&
maybeCallee.parent.arguments[0].type ===
"ThisExpression";
}
parent = maybeCallee.parent;
} else {
return retv;
}
} else {
return retv;
}
break;
// Checks whether the node is a callback.
case "CallExpression":
case "NewExpression":
if (parent.callee !== currentNode) {
retv.isCallback = true;
}
return retv;
default:
return retv;
}
currentNode = parent;
parent = parent.parent;
}
/* c8 ignore next */
throw new Error("unreachable");
}
/**
* Checks whether a simple list of parameters contains any duplicates. This does not handle complex
* parameter lists (e.g. with destructuring), since complex parameter lists are a SyntaxError with duplicate
* parameter names anyway. Instead, it always returns `false` for complex parameter lists.
* @param {ASTNode[]} paramsList The list of parameters for a function
* @returns {boolean} `true` if the list of parameters contains any duplicates
*/
function hasDuplicateParams(paramsList) {
return (
paramsList.every(param => param.type === "Identifier") &&
paramsList.length !== new Set(paramsList.map(param => param.name)).size
);
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
defaultOptions: [
{ allowNamedFunctions: false, allowUnboundThis: true },
],
docs: {
description: "Require using arrow functions for callbacks",
dialects: ["JavaScript", "TypeScript"],
recommended: false,
frozen: true,
url: "https://eslint.org/docs/latest/rules/prefer-arrow-callback",
},
schema: [
{
type: "object",
properties: {
allowNamedFunctions: {
type: "boolean",
},
allowUnboundThis: {
type: "boolean",
},
},
additionalProperties: false,
},
],
fixable: "code",
messages: {
preferArrowCallback: "Unexpected function expression.",
},
},
create(context) {
const [{ allowNamedFunctions, allowUnboundThis }] = context.options;
const sourceCode = context.sourceCode;
/*
* {Array<{this: boolean, super: boolean, meta: boolean}>}
* - this - A flag which shows there are one or more ThisExpression.
* - super - A flag which shows there are one or more Super.
* - meta - A flag which shows there are one or more MethProperty.
*/
let stack = [];
/**
* Pushes new function scope with all `false` flags.
* @returns {void}
*/
function enterScope() {
stack.push({ this: false, super: false, meta: false });
}
/**
* Pops a function scope from the stack.
* @returns {{this: boolean, super: boolean, meta: boolean}} The information of the last scope.
*/
function exitScope() {
return stack.pop();
}
return {
// Reset internal state.
Program() {
stack = [];
},
// If there are below, it cannot replace with arrow functions merely.
ThisExpression() {
const info = stack.at(-1);
if (info) {
info.this = true;
}
},
Super() {
const info = stack.at(-1);
if (info) {
info.super = true;
}
},
MetaProperty(node) {
const info = stack.at(-1);
if (info && checkMetaProperty(node, "new", "target")) {
info.meta = true;
}
},
// To skip nested scopes.
FunctionDeclaration: enterScope,
"FunctionDeclaration:exit": exitScope,
// Main.
FunctionExpression: enterScope,
"FunctionExpression:exit"(node) {
const scopeInfo = exitScope();
// Skip named function expressions
if (allowNamedFunctions && node.id && node.id.name) {
return;
}
// Skip generators.
if (node.generator) {
return;
}
// Skip recursive functions.
const nameVar = sourceCode.getDeclaredVariables(node)[0];
if (isFunctionName(nameVar) && nameVar.references.length > 0) {
return;
}
// Skip if it's using arguments.
const variable = getVariableOfArguments(
sourceCode.getScope(node),
);
if (variable && variable.references.length > 0) {
return;
}
// Reports if it's a callback which can replace with arrows.
const callbackInfo = getCallbackInfo(node);
if (
callbackInfo.isCallback &&
(!allowUnboundThis ||
!scopeInfo.this ||
callbackInfo.isLexicalThis) &&
!scopeInfo.super &&
!scopeInfo.meta
) {
context.report({
node,
messageId: "preferArrowCallback",
*fix(fixer) {
if (
(!callbackInfo.isLexicalThis &&
scopeInfo.this) ||
hasDuplicateParams(node.params)
) {
/*
* If the callback function does not have .bind(this) and contains a reference to `this`, there
* is no way to determine what `this` should be, so don't perform any fixes.
* If the callback function has duplicates in its list of parameters (possible in sloppy mode),
* don't replace it with an arrow function, because this is a SyntaxError with arrow functions.
*/
return;
}
if (
node.params.length &&
node.params[0].name === "this"
) {
return;
}
const functionToken = sourceCode.getFirstToken(
node,
node.async ? 1 : 0,
);
const leftParenToken = sourceCode.getTokenAfter(
functionToken,
astUtils.isOpeningParenToken,
);
if (node.async) {
if (
functionToken.loc.end.line <
leftParenToken.loc.start.line
) {
return;
}
}
// Remove `.bind(this)` if exists.
if (callbackInfo.isLexicalThis) {
const memberNode = node.parent;
/*
* If `.bind(this)` exists but the parent is not `.bind(this)`, don't remove it automatically.
* E.g. `(foo || function(){}).bind(this)`
*/
if (memberNode.type !== "MemberExpression") {
return;
}
const callNode = memberNode.parent;
const firstTokenToRemove =
sourceCode.getTokenAfter(
memberNode.object,
astUtils.isNotClosingParenToken,
);
const lastTokenToRemove =
sourceCode.getLastToken(callNode);
/*
* If the member expression is parenthesized, don't remove the right paren.
* E.g. `(function(){}.bind)(this)`
* ^^^^^^^^^^^^
*/
if (
astUtils.isParenthesised(
sourceCode,
memberNode,
)
) {
return;
}
// If comments exist in the `.bind(this)`, don't remove those.
if (
sourceCode.commentsExistBetween(
firstTokenToRemove,
lastTokenToRemove,
)
) {
return;
}
yield fixer.removeRange([
firstTokenToRemove.range[0],
lastTokenToRemove.range[1],
]);
}
// Convert the function expression to an arrow function.
const tokenBeforeBody = sourceCode.getTokenBefore(
node.body,
);
if (
sourceCode.commentsExistBetween(
functionToken,
leftParenToken,
)
) {
// Remove only extra tokens to keep comments.
yield fixer.remove(functionToken);
if (node.id) {
yield fixer.remove(node.id);
}
} else {
// Remove extra tokens and spaces.
yield fixer.removeRange([
functionToken.range[0],
leftParenToken.range[0],
]);
}
yield fixer.insertTextAfter(tokenBeforeBody, " =>");
// Get the node that will become the new arrow function.
let replacedNode = callbackInfo.isLexicalThis
? node.parent.parent
: node;
if (replacedNode.type === "ChainExpression") {
replacedNode = replacedNode.parent;
}
/*
* If the replaced node is part of a BinaryExpression, LogicalExpression, or MemberExpression, then
* the arrow function needs to be parenthesized, because `foo || () => {}` is invalid syntax even
* though `foo || function() {}` is valid.
*/
if (
replacedNode.parent.type !== "CallExpression" &&
replacedNode.parent.type !==
"ConditionalExpression" &&
!astUtils.isParenthesised(
sourceCode,
replacedNode,
) &&
!astUtils.isParenthesised(sourceCode, node)
) {
yield fixer.insertTextBefore(replacedNode, "(");
yield fixer.insertTextAfter(replacedNode, ")");
}
},
});
}
},
};
},
};

View File

@@ -0,0 +1,55 @@
'use strict'
/**
* A set of property names that indicate the value represents an error object.
*
* @typedef {string[]} K_ERROR_LIKE_KEYS
*/
module.exports = {
DATE_FORMAT: 'yyyy-mm-dd HH:MM:ss.l o',
DATE_FORMAT_SIMPLE: 'HH:MM:ss.l',
/**
* @type {K_ERROR_LIKE_KEYS}
*/
ERROR_LIKE_KEYS: ['err', 'error'],
MESSAGE_KEY: 'msg',
LEVEL_KEY: 'level',
LEVEL_LABEL: 'levelLabel',
TIMESTAMP_KEY: 'time',
LEVELS: {
default: 'USERLVL',
60: 'FATAL',
50: 'ERROR',
40: 'WARN',
30: 'INFO',
20: 'DEBUG',
10: 'TRACE'
},
LEVEL_NAMES: {
fatal: 60,
error: 50,
warn: 40,
info: 30,
debug: 20,
trace: 10
},
// Object keys that probably came from a logger like Pino or Bunyan.
LOGGER_KEYS: [
'pid',
'hostname',
'name',
'level',
'time',
'timestamp',
'caller'
]
}

View File

@@ -0,0 +1,4 @@
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"useLiteral", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
name: string;
};
export default _default;

View File

@@ -0,0 +1,137 @@
const Benchmark = require('benchmark')
const suite = new Benchmark.Suite()
const { inspect } = require('util')
const jsonStringifySafe = require('json-stringify-safe')
const fastSafeStringify = require('./')
const array = new Array(10).fill(0).map((_, i) => i)
const obj = { foo: array }
const circ = JSON.parse(JSON.stringify(obj))
circ.o = { obj: circ, array }
const circGetters = JSON.parse(JSON.stringify(obj))
Object.assign(circGetters, { get o () { return { obj: circGetters, array } } })
const deep = require('./package.json')
deep.deep = JSON.parse(JSON.stringify(deep))
deep.deep.deep = JSON.parse(JSON.stringify(deep))
deep.deep.deep.deep = JSON.parse(JSON.stringify(deep))
deep.array = array
const deepCirc = JSON.parse(JSON.stringify(deep))
deepCirc.deep.deep.deep.circ = deepCirc
deepCirc.deep.deep.circ = deepCirc
deepCirc.deep.circ = deepCirc
deepCirc.array = array
const deepCircGetters = JSON.parse(JSON.stringify(deep))
for (let i = 0; i < 10; i++) {
deepCircGetters[i.toString()] = {
deep: {
deep: {
get circ () { return deep.deep },
deep: { get circ () { return deep.deep.deep } }
},
get circ () { return deep }
},
get array () { return array }
}
}
const deepCircNonCongifurableGetters = JSON.parse(JSON.stringify(deep))
Object.defineProperty(deepCircNonCongifurableGetters.deep.deep.deep, 'circ', {
get: () => deepCircNonCongifurableGetters,
enumerable: true,
configurable: false
})
Object.defineProperty(deepCircNonCongifurableGetters.deep.deep, 'circ', {
get: () => deepCircNonCongifurableGetters,
enumerable: true,
configurable: false
})
Object.defineProperty(deepCircNonCongifurableGetters.deep, 'circ', {
get: () => deepCircNonCongifurableGetters,
enumerable: true,
configurable: false
})
Object.defineProperty(deepCircNonCongifurableGetters, 'array', {
get: () => array,
enumerable: true,
configurable: false
})
suite.add('util.inspect: simple object ', function () {
inspect(obj, { showHidden: false, depth: null })
})
suite.add('util.inspect: circular ', function () {
inspect(circ, { showHidden: false, depth: null })
})
suite.add('util.inspect: circular getters ', function () {
inspect(circGetters, { showHidden: false, depth: null })
})
suite.add('util.inspect: deep ', function () {
inspect(deep, { showHidden: false, depth: null })
})
suite.add('util.inspect: deep circular ', function () {
inspect(deepCirc, { showHidden: false, depth: null })
})
suite.add('util.inspect: large deep circular getters ', function () {
inspect(deepCircGetters, { showHidden: false, depth: null })
})
suite.add('util.inspect: deep non-conf circular getters', function () {
inspect(deepCircNonCongifurableGetters, { showHidden: false, depth: null })
})
suite.add('\njson-stringify-safe: simple object ', function () {
jsonStringifySafe(obj)
})
suite.add('json-stringify-safe: circular ', function () {
jsonStringifySafe(circ)
})
suite.add('json-stringify-safe: circular getters ', function () {
jsonStringifySafe(circGetters)
})
suite.add('json-stringify-safe: deep ', function () {
jsonStringifySafe(deep)
})
suite.add('json-stringify-safe: deep circular ', function () {
jsonStringifySafe(deepCirc)
})
suite.add('json-stringify-safe: large deep circular getters ', function () {
jsonStringifySafe(deepCircGetters)
})
suite.add('json-stringify-safe: deep non-conf circular getters', function () {
jsonStringifySafe(deepCircNonCongifurableGetters)
})
suite.add('\nfast-safe-stringify: simple object ', function () {
fastSafeStringify(obj)
})
suite.add('fast-safe-stringify: circular ', function () {
fastSafeStringify(circ)
})
suite.add('fast-safe-stringify: circular getters ', function () {
fastSafeStringify(circGetters)
})
suite.add('fast-safe-stringify: deep ', function () {
fastSafeStringify(deep)
})
suite.add('fast-safe-stringify: deep circular ', function () {
fastSafeStringify(deepCirc)
})
suite.add('fast-safe-stringify: large deep circular getters ', function () {
fastSafeStringify(deepCircGetters)
})
suite.add('fast-safe-stringify: deep non-conf circular getters', function () {
fastSafeStringify(deepCircNonCongifurableGetters)
})
// add listeners
suite.on('cycle', function (event) {
console.log(String(event.target))
})
suite.on('complete', function () {
console.log('\nFastest is ' + this.filter('fastest').map('name'))
})
suite.run({ delay: 1, minSamples: 150 })

View File

@@ -0,0 +1,179 @@
// TypeScript Version: 3.0
/// <reference types="node" />
import type { URL } from 'url';
export interface DotenvParseOutput {
[name: string]: string;
}
export interface DotenvPopulateOutput {
[name: string]: string;
}
/**
* Parses a string or buffer in the .env file format into an object.
*
* See https://dotenvx.com/docs
*
* @param src - contents to be parsed. example: `'DB_HOST=localhost'`
* @returns an object with keys and values based on `src`. example: `{ DB_HOST : 'localhost' }`
*/
export function parse<T extends DotenvParseOutput = DotenvParseOutput>(
src: string | Buffer
): T;
export interface DotenvConfigOptions {
/**
* Default: `path.resolve(process.cwd(), '.env')`
*
* Specify a custom path if your file containing environment variables is located elsewhere.
* Can also be an array of strings, specifying multiple paths.
*
* example: `require('dotenv').config({ path: '/custom/path/to/.env' })`
* example: `require('dotenv').config({ path: ['/path/to/first.env', '/path/to/second.env'] })`
*/
path?: string | string[] | URL;
/**
* Default: `utf8`
*
* Specify the encoding of your file containing environment variables.
*
* example: `require('dotenv').config({ encoding: 'latin1' })`
*/
encoding?: string;
/**
* Default: `false`
*
* Suppress all output (except errors).
*
* example: `require('dotenv').config({ quiet: true })`
*/
quiet?: boolean;
/**
* Default: `false`
*
* Turn on logging to help debug why certain keys or values are not being set as you expect.
*
* example: `require('dotenv').config({ debug: process.env.DEBUG })`
*/
debug?: boolean;
/**
* Default: `false`
*
* Override any environment variables that have already been set on your machine with values from your .env file.
*
* example: `require('dotenv').config({ override: true })`
*/
override?: boolean;
/**
* Default: `process.env`
*
* Specify an object to write your secrets to. Defaults to process.env environment variables.
*
* example: `const processEnv = {}; require('dotenv').config({ processEnv: processEnv })`
*/
processEnv?: DotenvPopulateInput;
/**
* Default: `undefined`
*
* Pass the DOTENV_KEY directly to config options. Defaults to looking for process.env.DOTENV_KEY environment variable. Note this only applies to decrypting .env.vault files. If passed as null or undefined, or not passed at all, dotenv falls back to its traditional job of parsing a .env file.
*
* example: `require('dotenv').config({ DOTENV_KEY: 'dotenv://:key_1234…@dotenvx.com/vault/.env.vault?environment=production' })`
*/
DOTENV_KEY?: string;
}
export interface DotenvConfigOutput {
error?: DotenvError;
parsed?: DotenvParseOutput;
}
type DotenvError = Error & {
code:
| 'MISSING_DATA'
| 'INVALID_DOTENV_KEY'
| 'NOT_FOUND_DOTENV_ENVIRONMENT'
| 'DECRYPTION_FAILED'
| 'OBJECT_REQUIRED';
}
export interface DotenvPopulateOptions {
/**
* Default: `false`
*
* Turn on logging to help debug why certain keys or values are not being set as you expect.
*
* example: `require('dotenv').populate(processEnv, parsed, { debug: true })`
*/
debug?: boolean;
/**
* Default: `false`
*
* Override any environment variables that have already been set on your machine with values from your .env file.
*
* example: `require('dotenv').populate(processEnv, parsed, { override: true })`
*/
override?: boolean;
}
export interface DotenvPopulateInput {
[name: string]: string | undefined;
}
/**
* Loads `.env` file contents into process.env by default. If `DOTENV_KEY` is present, it smartly attempts to load encrypted `.env.vault` file contents into process.env.
*
* See https://dotenvx.com/docs
*
* @param options - additional options. example: `{ path: './custom/path', encoding: 'latin1', quiet: false, debug: true, override: false }`
* @returns an object with a `parsed` key if successful or `error` key if an error occurred. example: { parsed: { KEY: 'value' } }
*
*/
export function config(options?: DotenvConfigOptions): DotenvConfigOutput;
/**
* Loads `.env` file contents into process.env.
*
* See https://dotenvx.com/docs
*
* @param options - additional options. example: `{ path: './custom/path', encoding: 'latin1', quiet: false, debug: true, override: false }`
* @returns an object with a `parsed` key if successful or `error` key if an error occurred. example: { parsed: { KEY: 'value' } }
*
*/
export function configDotenv(options?: DotenvConfigOptions): DotenvConfigOutput;
/**
* Loads `source` json contents into `target` like process.env.
*
* See https://dotenvx.com/docs
*
* @param processEnv - the target JSON object. in most cases use process.env but you can also pass your own JSON object
* @param parsed - the source JSON object
* @param options - additional options. example: `{ debug: true, override: false }`
* @returns an object with the keys and values that were actually set
*
*/
export function populate(
processEnv: DotenvPopulateInput,
parsed: DotenvPopulateInput,
options?: DotenvPopulateOptions
): DotenvPopulateOutput;
/**
* Decrypt ciphertext
*
* See https://dotenvx.com/docs
*
* @param encrypted - the encrypted ciphertext string
* @param keyStr - the decryption key string
* @returns {string}
*
*/
export function decrypt(encrypted: string, keyStr: string): string;

View File

@@ -0,0 +1,160 @@
import { expect, expectTypeOf, test } from "vitest";
import * as z from "zod/v4";
test("string coercion", () => {
const schema = z.coerce.string();
expect(schema.parse("sup")).toEqual("sup");
expect(schema.parse("")).toEqual("");
expect(schema.parse(12)).toEqual("12");
expect(schema.parse(0)).toEqual("0");
expect(schema.parse(-12)).toEqual("-12");
expect(schema.parse(3.14)).toEqual("3.14");
expect(schema.parse(BigInt(15))).toEqual("15");
expect(schema.parse(Number.NaN)).toEqual("NaN");
expect(schema.parse(Number.POSITIVE_INFINITY)).toEqual("Infinity");
expect(schema.parse(Number.NEGATIVE_INFINITY)).toEqual("-Infinity");
expect(schema.parse(true)).toEqual("true");
expect(schema.parse(false)).toEqual("false");
expect(schema.parse(null)).toEqual("null");
expect(schema.parse(undefined)).toEqual("undefined");
expect(schema.parse({ hello: "world!" })).toEqual("[object Object]");
expect(schema.parse(["item", "another_item"])).toEqual("item,another_item");
expect(schema.parse([])).toEqual("");
expect(schema.parse(new Date("2022-01-01T00:00:00.000Z"))).toEqual(new Date("2022-01-01T00:00:00.000Z").toString());
});
test("number coercion", () => {
const schema = z.coerce.number();
expect(schema.parse("12")).toEqual(12);
expect(schema.parse("0")).toEqual(0);
expect(schema.parse("-12")).toEqual(-12);
expect(schema.parse("3.14")).toEqual(3.14);
expect(schema.parse("")).toEqual(0);
expect(() => schema.parse("NOT_A_NUMBER")).toThrow(); // z.ZodError
expect(schema.parse(12)).toEqual(12);
expect(schema.parse(0)).toEqual(0);
expect(schema.parse(-12)).toEqual(-12);
expect(schema.parse(3.14)).toEqual(3.14);
expect(schema.parse(BigInt(15))).toEqual(15);
expect(() => schema.parse(Number.NaN)).toThrow(); // z.ZodError
// expect(schema.parse(Number.POSITIVE_INFINITY)).toEqual(Number.POSITIVE_INFINITY);
// expect(schema.parse(Number.NEGATIVE_INFINITY)).toEqual(Number.NEGATIVE_INFINITY);
expect(schema.parse(true)).toEqual(1);
expect(schema.parse(false)).toEqual(0);
expect(schema.parse(null)).toEqual(0);
expect(() => schema.parse(undefined)).toThrow(); // z.ZodError
expect(() => schema.parse({ hello: "world!" })).toThrow(); // z.ZodError
expect(() => schema.parse(["item", "another_item"])).toThrow(); // z.ZodError
expect(schema.parse([])).toEqual(0);
expect(schema.parse(new Date(1670139203496))).toEqual(1670139203496);
});
test("boolean coercion", () => {
const schema = z.coerce.boolean();
expect(schema.parse("true")).toEqual(true);
expect(schema.parse("false")).toEqual(true);
expect(schema.parse("0")).toEqual(true);
expect(schema.parse("1")).toEqual(true);
expect(schema.parse("")).toEqual(false);
expect(schema.parse(1)).toEqual(true);
expect(schema.parse(0)).toEqual(false);
expect(schema.parse(-1)).toEqual(true);
expect(schema.parse(3.14)).toEqual(true);
expect(schema.parse(BigInt(15))).toEqual(true);
expect(schema.parse(Number.NaN)).toEqual(false);
expect(schema.parse(Number.POSITIVE_INFINITY)).toEqual(true);
expect(schema.parse(Number.NEGATIVE_INFINITY)).toEqual(true);
expect(schema.parse(true)).toEqual(true);
expect(schema.parse(false)).toEqual(false);
expect(schema.parse(null)).toEqual(false);
expect(schema.parse(undefined)).toEqual(false);
expect(schema.parse({ hello: "world!" })).toEqual(true);
expect(schema.parse(["item", "another_item"])).toEqual(true);
expect(schema.parse([])).toEqual(true);
expect(schema.parse(new Date(1670139203496))).toEqual(true);
});
test("bigint coercion", () => {
const schema = z.coerce.bigint();
expect(schema.parse("5")).toEqual(BigInt(5));
expect(schema.parse("0")).toEqual(BigInt(0));
expect(schema.parse("-5")).toEqual(BigInt(-5));
expect(() => schema.parse("3.14")).toThrow(); // not a z.ZodError!
expect(schema.parse("")).toEqual(BigInt(0));
expect(() => schema.parse("NOT_A_NUMBER")).toThrow(); // not a z.ZodError!
expect(schema.parse(5)).toEqual(BigInt(5));
expect(schema.parse(0)).toEqual(BigInt(0));
expect(schema.parse(-5)).toEqual(BigInt(-5));
expect(() => schema.parse(3.14)).toThrow(); // not a z.ZodError!
expect(schema.parse(BigInt(5))).toEqual(BigInt(5));
expect(() => schema.parse(Number.NaN)).toThrow(); // not a z.ZodError!
expect(() => schema.parse(Number.POSITIVE_INFINITY)).toThrow(); // not a z.ZodError!
expect(() => schema.parse(Number.NEGATIVE_INFINITY)).toThrow(); // not a z.ZodError!
expect(schema.parse(true)).toEqual(BigInt(1));
expect(schema.parse(false)).toEqual(BigInt(0));
expect(() => schema.parse(null)).toThrow(); // not a z.ZodError!
expect(() => schema.parse(undefined)).toThrow(); // not a z.ZodError!
expect(() => schema.parse({ hello: "world!" })).toThrow(); // not a z.ZodError!
expect(() => schema.parse(["item", "another_item"])).toThrow(); // not a z.ZodError!
expect(schema.parse([])).toEqual(BigInt(0));
expect(schema.parse(new Date(1670139203496))).toEqual(BigInt(1670139203496));
});
test("date coercion", () => {
const schema = z.coerce.date();
expect(schema.parse(new Date().toDateString())).toBeInstanceOf(Date);
expect(schema.parse(new Date().toISOString())).toBeInstanceOf(Date);
expect(schema.parse(new Date().toUTCString())).toBeInstanceOf(Date);
expect(schema.parse("5")).toBeInstanceOf(Date);
expect(schema.parse("2000-01-01")).toBeInstanceOf(Date);
// expect(schema.parse("0")).toBeInstanceOf(Date);
// expect(schema.parse("-5")).toBeInstanceOf(Date);
// expect(schema.parse("3.14")).toBeInstanceOf(Date);
expect(() => schema.parse("")).toThrow(); // z.ZodError
expect(() => schema.parse("NOT_A_DATE")).toThrow(); // z.ZodError
expect(schema.parse(5)).toBeInstanceOf(Date);
expect(schema.parse(0)).toBeInstanceOf(Date);
expect(schema.parse(-5)).toBeInstanceOf(Date);
expect(schema.parse(3.14)).toBeInstanceOf(Date);
expect(() => schema.parse(BigInt(5))).toThrow(); // not a z.ZodError!
expect(() => schema.parse(Number.NaN)).toThrow(); // z.ZodError
expect(() => schema.parse(Number.POSITIVE_INFINITY)).toThrow(); // z.ZodError
expect(() => schema.parse(Number.NEGATIVE_INFINITY)).toThrow(); // z.ZodError
expect(schema.parse(true)).toBeInstanceOf(Date);
expect(schema.parse(false)).toBeInstanceOf(Date);
expect(schema.parse(null)).toBeInstanceOf(Date);
expect(() => schema.parse(undefined)).toThrow(); // z.ZodError
expect(() => schema.parse({ hello: "world!" })).toThrow(); // z.ZodError
expect(() => schema.parse(["item", "another_item"])).toThrow(); // z.ZodError
expect(() => schema.parse([])).toThrow(); // z.ZodError
expect(schema.parse(new Date())).toBeInstanceOf(Date);
});
// test("template literal coercion", () => {
// const schema = z.coerce
// .templateLiteral()
// .interpolated(z.number().finite())
// .interpolated(
// z.enum(["px", "em", "rem", "vh", "vw", "vmin", "vmax"]).optional()
// );
// expect(schema.parse(300)).toEqual("300");
// expect(schema.parse(BigInt(300))).toEqual("300");
// expect(schema.parse("300")).toEqual("300");
// expect(schema.parse("300px")).toEqual("300px");
// expect(schema.parse("300em")).toEqual("300em");
// expect(schema.parse("300rem")).toEqual("300rem");
// expect(schema.parse("300vh")).toEqual("300vh");
// expect(schema.parse("300vw")).toEqual("300vw");
// expect(schema.parse("300vmin")).toEqual("300vmin");
// expect(schema.parse("300vmax")).toEqual("300vmax");
// expect(schema.parse(["300px"])).toEqual("300px");
// });
test("override input type", () => {
const a = z.coerce.string<any>();
type input = z.input<typeof a>;
expectTypeOf<input>().toEqualTypeOf<any>();
type output = z.infer<typeof a>;
expectTypeOf<output>().toEqualTypeOf<string>();
});