WIP: bootstrap and partial real Solana watcher implementation
This commit is contained in:
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"tokenFlags.d.ts","sourceRoot":"","sources":["../../src/enums/tokenFlags.ts"],"names":[],"mappings":"AACA,eAAO,IAAI,UAAU,EAAE,GAAG,CAAC"}
|
||||
@@ -0,0 +1,13 @@
|
||||
import toPropertyKey from "./toPropertyKey.js";
|
||||
function _defineProperties(e, r) {
|
||||
for (var t = 0; t < r.length; t++) {
|
||||
var o = r[t];
|
||||
o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, toPropertyKey(o.key), o);
|
||||
}
|
||||
}
|
||||
function _createClass(e, r, t) {
|
||||
return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
|
||||
writable: !1
|
||||
}), e;
|
||||
}
|
||||
export { _createClass as default };
|
||||
@@ -0,0 +1,13 @@
|
||||
"use strict";
|
||||
// THIS CODE WAS AUTOMATICALLY GENERATED
|
||||
// DO NOT EDIT THIS CODE BY HAND
|
||||
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
|
||||
// npx nx generate-lib repo
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.es2025_intl = void 0;
|
||||
const base_config_1 = require("./base-config");
|
||||
const es2018_intl_1 = require("./es2018.intl");
|
||||
exports.es2025_intl = {
|
||||
libs: [es2018_intl_1.es2018_intl],
|
||||
variables: [['Intl', base_config_1.TYPE_VALUE]],
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
'use strict'
|
||||
|
||||
const { Writable } = require('stream')
|
||||
|
||||
// Nop console.error to avoid printing things out
|
||||
console.error = () => {}
|
||||
|
||||
setImmediate(function () {
|
||||
throw new Error('kaboom')
|
||||
})
|
||||
|
||||
async function run (opts) {
|
||||
const stream = new Writable({
|
||||
write (chunk, enc, cb) {
|
||||
cb()
|
||||
}
|
||||
})
|
||||
return stream
|
||||
}
|
||||
|
||||
module.exports = run
|
||||
@@ -0,0 +1,16 @@
|
||||
export * as core from "../core/index.js";
|
||||
export * from "./schemas.js";
|
||||
export * from "./checks.js";
|
||||
export * from "./errors.js";
|
||||
export * from "./parse.js";
|
||||
export * from "./compat.js";
|
||||
export type { infer, output, input } from "../core/index.js";
|
||||
export type { JSONType } from "../core/util.js";
|
||||
export { globalRegistry, type GlobalMeta, registry, config, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, } from "../core/index.js";
|
||||
export { toJSONSchema } from "../core/json-schema-processors.js";
|
||||
export { fromJSONSchema } from "./from-json-schema.js";
|
||||
export * as locales from "../locales/index.js";
|
||||
export { ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration } from "./iso.js";
|
||||
export * as iso from "./iso.js";
|
||||
export type { ZodCoercedString, ZodCoercedNumber, ZodCoercedBigInt, ZodCoercedBoolean, ZodCoercedDate, } from "./coerce.js";
|
||||
export * as coerce from "./coerce.js";
|
||||
@@ -0,0 +1,12 @@
|
||||
"use strict";
|
||||
// THIS CODE WAS AUTOMATICALLY GENERATED
|
||||
// DO NOT EDIT THIS CODE BY HAND
|
||||
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
|
||||
// npx nx generate-lib repo
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.es2025_regexp = void 0;
|
||||
const base_config_1 = require("./base-config");
|
||||
exports.es2025_regexp = {
|
||||
libs: [],
|
||||
variables: [['RegExpConstructor', base_config_1.TYPE]],
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
declare module "node:inspector/promises" {
|
||||
import { EventEmitter } from "node:events";
|
||||
export { close, console, NetworkResources, open, url, waitForDebugger } from "node:inspector";
|
||||
/**
|
||||
* The `inspector.Session` is used for dispatching messages to the V8 inspector
|
||||
* back-end and receiving message responses and notifications.
|
||||
* @since v19.0.0
|
||||
*/
|
||||
export class Session extends EventEmitter {
|
||||
/**
|
||||
* Create a new instance of the inspector.Session class.
|
||||
* The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend.
|
||||
*/
|
||||
constructor();
|
||||
/**
|
||||
* Connects a session to the inspector back-end.
|
||||
*/
|
||||
connect(): void;
|
||||
/**
|
||||
* Connects a session to the inspector back-end.
|
||||
* An exception will be thrown if this API was not called on a Worker thread.
|
||||
* @since v12.11.0
|
||||
*/
|
||||
connectToMainThread(): void;
|
||||
/**
|
||||
* Immediately close the session. All pending message callbacks will be called with an error.
|
||||
* `session.connect()` will need to be called to be able to send messages again.
|
||||
* Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints.
|
||||
*/
|
||||
disconnect(): void;
|
||||
}
|
||||
}
|
||||
declare module "inspector/promises" {
|
||||
export * from "node:inspector/promises";
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import type { TSESTree } from '@typescript-eslint/types';
|
||||
import type * as ts from 'typescript';
|
||||
/**
|
||||
* Describes specific types or values declared in local files.
|
||||
* See [TypeOrValueSpecifier > FileSpecifier](/packages/type-utils/type-or-value-specifier#filespecifier).
|
||||
*/
|
||||
export interface FileSpecifier {
|
||||
from: 'file';
|
||||
/**
|
||||
* Type or value name(s) to match on.
|
||||
*/
|
||||
name: string | string[];
|
||||
/**
|
||||
* A specific file the types or values must be declared in.
|
||||
*/
|
||||
path?: string;
|
||||
}
|
||||
/**
|
||||
* Describes specific types or values declared in TypeScript's built-in lib definitions.
|
||||
* See [TypeOrValueSpecifier > LibSpecifier](/packages/type-utils/type-or-value-specifier#libspecifier).
|
||||
*/
|
||||
export interface LibSpecifier {
|
||||
from: 'lib';
|
||||
/**
|
||||
* Type or value name(s) to match on.
|
||||
*/
|
||||
name: string | string[];
|
||||
}
|
||||
/**
|
||||
* Describes specific types or values imported from packages.
|
||||
* See [TypeOrValueSpecifier > PackageSpecifier](/packages/type-utils/type-or-value-specifier#packagespecifier).
|
||||
*/
|
||||
export interface PackageSpecifier {
|
||||
from: 'package';
|
||||
/**
|
||||
* Type or value name(s) to match on.
|
||||
*/
|
||||
name: string | string[];
|
||||
/**
|
||||
* Package name the type or value must be declared in.
|
||||
*/
|
||||
package: string;
|
||||
}
|
||||
/**
|
||||
* A centralized format for rule options to describe specific _types_ and/or _values_.
|
||||
* See [TypeOrValueSpecifier](/packages/type-utils/type-or-value-specifier).
|
||||
*/
|
||||
export type TypeOrValueSpecifier = string | FileSpecifier | LibSpecifier | PackageSpecifier;
|
||||
export declare const typeOrValueSpecifiersSchema: {
|
||||
readonly items: {
|
||||
readonly oneOf: [{
|
||||
readonly type: 'string';
|
||||
}, {
|
||||
readonly additionalProperties: false;
|
||||
readonly properties: {
|
||||
readonly from: {
|
||||
readonly enum: ["file"];
|
||||
readonly type: 'string';
|
||||
};
|
||||
readonly name: {
|
||||
readonly oneOf: [{
|
||||
readonly type: 'string';
|
||||
}, {
|
||||
readonly items: {
|
||||
readonly type: 'string';
|
||||
};
|
||||
readonly minItems: 1;
|
||||
readonly type: 'array';
|
||||
readonly uniqueItems: true;
|
||||
}];
|
||||
};
|
||||
readonly path: {
|
||||
readonly type: 'string';
|
||||
};
|
||||
};
|
||||
readonly required: ["from", "name"];
|
||||
readonly type: 'object';
|
||||
}, {
|
||||
readonly additionalProperties: false;
|
||||
readonly properties: {
|
||||
readonly from: {
|
||||
readonly enum: ["lib"];
|
||||
readonly type: 'string';
|
||||
};
|
||||
readonly name: {
|
||||
readonly oneOf: [{
|
||||
readonly type: 'string';
|
||||
}, {
|
||||
readonly items: {
|
||||
readonly type: 'string';
|
||||
};
|
||||
readonly minItems: 1;
|
||||
readonly type: 'array';
|
||||
readonly uniqueItems: true;
|
||||
}];
|
||||
};
|
||||
};
|
||||
readonly required: ["from", "name"];
|
||||
readonly type: 'object';
|
||||
}, {
|
||||
readonly additionalProperties: false;
|
||||
readonly properties: {
|
||||
readonly from: {
|
||||
readonly enum: ["package"];
|
||||
readonly type: 'string';
|
||||
};
|
||||
readonly name: {
|
||||
readonly oneOf: [{
|
||||
readonly type: 'string';
|
||||
}, {
|
||||
readonly items: {
|
||||
readonly type: 'string';
|
||||
};
|
||||
readonly minItems: 1;
|
||||
readonly type: 'array';
|
||||
readonly uniqueItems: true;
|
||||
}];
|
||||
};
|
||||
readonly package: {
|
||||
readonly type: 'string';
|
||||
};
|
||||
};
|
||||
readonly required: ["from", "name", "package"];
|
||||
readonly type: 'object';
|
||||
}];
|
||||
};
|
||||
readonly type: 'array';
|
||||
};
|
||||
export declare function typeMatchesSpecifier(type: ts.Type, specifier: TypeOrValueSpecifier, program: ts.Program): boolean;
|
||||
export declare const typeMatchesSomeSpecifier: (type: ts.Type, specifiers: TypeOrValueSpecifier[] | undefined, program: ts.Program) => boolean;
|
||||
export declare function valueMatchesSpecifier(node: TSESTree.Node, specifier: TypeOrValueSpecifier, program: ts.Program, type: ts.Type): boolean;
|
||||
export declare const valueMatchesSomeSpecifier: (node: TSESTree.Node, specifiers: TypeOrValueSpecifier[] | undefined, program: ts.Program, type: ts.Type) => boolean;
|
||||
@@ -0,0 +1,7 @@
|
||||
Copyright Mateo Collina, David Mark Clements, James Sumners
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,22 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isStartOfExpressionStatement = isStartOfExpressionStatement;
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
// The following is copied from `eslint`'s source code.
|
||||
// https://github.com/eslint/eslint/blob/3a4eaf921543b1cd5d1df4ea9dec02fab396af2a/lib/rules/utils/ast-utils.js#L1026-L1041
|
||||
// Could be export { isStartOfExpressionStatement } from 'eslint/lib/rules/utils/ast-utils'
|
||||
/**
|
||||
* Tests if a node appears at the beginning of an ancestor ExpressionStatement node.
|
||||
* @param node The node to check.
|
||||
* @returns Whether the node appears at the beginning of an ancestor ExpressionStatement node.
|
||||
*/
|
||||
function isStartOfExpressionStatement(node) {
|
||||
const start = node.range[0];
|
||||
let ancestor = node;
|
||||
while ((ancestor = ancestor.parent) && ancestor.range[0] === start) {
|
||||
if (ancestor.type === utils_1.AST_NODE_TYPES.ExpressionStatement) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import MagicString from 'magic-string';
|
||||
|
||||
interface AutomockOptions {
|
||||
/**
|
||||
* @default "__vitest_mocker__"
|
||||
*/
|
||||
globalThisAccessor?: string;
|
||||
id?: string;
|
||||
}
|
||||
declare function automockModule(code: string, mockType: "automock" | "autospy", parse: (code: string) => any, options?: AutomockOptions): MagicString;
|
||||
|
||||
export { automockModule };
|
||||
export type { AutomockOptions };
|
||||
@@ -0,0 +1,23 @@
|
||||
export interface FileSystemEntries {
|
||||
files: string[];
|
||||
directories: string[];
|
||||
}
|
||||
export interface FileSystem {
|
||||
directoryExists?: (directoryName: string) => boolean | undefined;
|
||||
fileExists?: (fileName: string) => boolean | undefined;
|
||||
getAccessibleEntries?: (directoryName: string) => FileSystemEntries | undefined;
|
||||
/**
|
||||
* Read a file's content.
|
||||
* - Return the file content as a `string` (including `""` for empty files).
|
||||
* - Return `null` to indicate the file does not exist (without falling back to the real FS).
|
||||
* - Return `undefined` to fall back to the real filesystem.
|
||||
*/
|
||||
readFile?: (fileName: string) => string | null | undefined;
|
||||
realpath?: (path: string) => string | undefined;
|
||||
writeFile?: (path: string, content: string) => void;
|
||||
removeFile?: (path: string) => void;
|
||||
}
|
||||
/** The callback names supported by the Go server for virtual FS delegation. */
|
||||
export declare const fsCallbackNames: readonly ["readFile", "fileExists", "directoryExists", "getAccessibleEntries", "realpath"];
|
||||
export declare function createVirtualFileSystem(files: Record<string, string>): FileSystem;
|
||||
//# sourceMappingURL=fs.d.ts.map
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"name": "safe-buffer",
|
||||
"description": "Safer Node.js Buffer API",
|
||||
"version": "5.2.1",
|
||||
"author": {
|
||||
"name": "Feross Aboukhadijeh",
|
||||
"email": "feross@feross.org",
|
||||
"url": "https://feross.org"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/feross/safe-buffer/issues"
|
||||
},
|
||||
"devDependencies": {
|
||||
"standard": "*",
|
||||
"tape": "^5.0.0"
|
||||
},
|
||||
"homepage": "https://github.com/feross/safe-buffer",
|
||||
"keywords": [
|
||||
"buffer",
|
||||
"buffer allocate",
|
||||
"node security",
|
||||
"safe",
|
||||
"safe-buffer",
|
||||
"security",
|
||||
"uninitialized"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "index.js",
|
||||
"types": "index.d.ts",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/feross/safe-buffer.git"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "standard && tape test/*.js"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { _ as default } from "../esm/_class_extract_field_descriptor.js";
|
||||
@@ -0,0 +1,4 @@
|
||||
function _instanceof(n, e) {
|
||||
return null != e && "undefined" != typeof Symbol && e[Symbol.hasInstance] ? !!e[Symbol.hasInstance](n) : n instanceof e;
|
||||
}
|
||||
module.exports = _instanceof, module.exports.__esModule = true, module.exports["default"] = module.exports;
|
||||
@@ -0,0 +1,24 @@
|
||||
var bench = require('fastbench')
|
||||
var utilFormat = require('util').format
|
||||
var quickFormat = require('./')
|
||||
|
||||
var run = bench([
|
||||
function util(cb) {
|
||||
utilFormat('%s %j %d', 'a', {a: {x: 1}}, 1)
|
||||
setImmediate(cb)
|
||||
},
|
||||
function quick(cb) {
|
||||
quickFormat('%s %j %d', 'a', [{a: {x: 1}}, 1], null)
|
||||
setImmediate(cb)
|
||||
},
|
||||
function utilWithTailObj(cb) {
|
||||
utilFormat('hello %s %j %d', 'world', {obj: true}, 4, {another: 'obj'})
|
||||
setImmediate(cb)
|
||||
},
|
||||
function quickWithTailObj(cb) {
|
||||
quickFormat('hello %s %j %d', 'world', [{obj: true}, 4, {another: 'obj'}], null)
|
||||
setImmediate(cb)
|
||||
}
|
||||
], 100000)
|
||||
|
||||
run(run)
|
||||
@@ -0,0 +1,5 @@
|
||||
import type { TSESLint } from '@typescript-eslint/utils';
|
||||
declare const _default: TSESLint.RuleModule<"preferForOf", [], import("../../rules").ESLintPluginDocs, TSESLint.RuleListener> & {
|
||||
name: string;
|
||||
};
|
||||
export default _default;
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* @fileoverview Disallow string concatenation when using __dirname and __filename
|
||||
* @author Nicholas C. Zakas
|
||||
* @deprecated in ESLint v7.0.0
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @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-path-concat",
|
||||
url: "https://github.com/eslint-community/eslint-plugin-n/tree/master/docs/rules/no-path-concat.md",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
type: "suggestion",
|
||||
|
||||
docs: {
|
||||
description:
|
||||
"Disallow string concatenation with `__dirname` and `__filename`",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/latest/rules/no-path-concat",
|
||||
},
|
||||
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
usePathFunctions:
|
||||
"Use path.join() or path.resolve() instead of + to create paths.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const MATCHER = /^__(?:dir|file)name$/u;
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Public
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
return {
|
||||
BinaryExpression(node) {
|
||||
const left = node.left,
|
||||
right = node.right;
|
||||
|
||||
if (
|
||||
node.operator === "+" &&
|
||||
((left.type === "Identifier" && MATCHER.test(left.name)) ||
|
||||
(right.type === "Identifier" &&
|
||||
MATCHER.test(right.name)))
|
||||
) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "usePathFunctions",
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,374 @@
|
||||
/**
|
||||
* @fileoverview A class to operate forking.
|
||||
*
|
||||
* This is state of forking.
|
||||
* This has a fork list and manages it.
|
||||
*
|
||||
* @author Toru Nagashima
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const assert = require("../../shared/assert"),
|
||||
CodePathSegment = require("./code-path-segment");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Determines whether or not a given segment is reachable.
|
||||
* @param {CodePathSegment} segment The segment to check.
|
||||
* @returns {boolean} `true` if the segment is reachable.
|
||||
*/
|
||||
function isReachable(segment) {
|
||||
return segment.reachable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new segment for each fork in the given context and appends it
|
||||
* to the end of the specified range of segments. Ultimately, this ends up calling
|
||||
* `new CodePathSegment()` for each of the forks using the `create` argument
|
||||
* as a wrapper around special behavior.
|
||||
*
|
||||
* The `startIndex` and `endIndex` arguments specify a range of segments in
|
||||
* `context` that should become `allPrevSegments` for the newly created
|
||||
* `CodePathSegment` objects.
|
||||
*
|
||||
* When `context.segmentsList` is `[[a, b], [c, d], [e, f]]`, `begin` is `0`, and
|
||||
* `end` is `-1`, this creates two new segments, `[g, h]`. This `g` is appended to
|
||||
* the end of the path from `a`, `c`, and `e`. This `h` is appended to the end of
|
||||
* `b`, `d`, and `f`.
|
||||
* @param {ForkContext} context An instance from which the previous segments
|
||||
* will be obtained.
|
||||
* @param {number} startIndex The index of the first segment in the context
|
||||
* that should be specified as previous segments for the newly created segments.
|
||||
* @param {number} endIndex The index of the last segment in the context
|
||||
* that should be specified as previous segments for the newly created segments.
|
||||
* @param {Function} create A function that creates new `CodePathSegment`
|
||||
* instances in a particular way. See the `CodePathSegment.new*` methods.
|
||||
* @returns {Array<CodePathSegment>} An array of the newly-created segments.
|
||||
*/
|
||||
function createSegments(context, startIndex, endIndex, create) {
|
||||
/** @type {Array<Array<CodePathSegment>>} */
|
||||
const list = context.segmentsList;
|
||||
|
||||
/*
|
||||
* Both `startIndex` and `endIndex` work the same way: if the number is zero
|
||||
* or more, then the number is used as-is. If the number is negative,
|
||||
* then that number is added to the length of the segments list to
|
||||
* determine the index to use. That means -1 for either argument
|
||||
* is the last element, -2 is the second to last, and so on.
|
||||
*
|
||||
* So if `startIndex` is 0, `endIndex` is -1, and `list.length` is 3, the
|
||||
* effective `startIndex` is 0 and the effective `endIndex` is 2, so this function
|
||||
* will include items at indices 0, 1, and 2.
|
||||
*
|
||||
* Therefore, if `startIndex` is -1 and `endIndex` is -1, that means we'll only
|
||||
* be using the last segment in `list`.
|
||||
*/
|
||||
const normalizedBegin =
|
||||
startIndex >= 0 ? startIndex : list.length + startIndex;
|
||||
const normalizedEnd = endIndex >= 0 ? endIndex : list.length + endIndex;
|
||||
|
||||
/** @type {Array<CodePathSegment>} */
|
||||
const segments = [];
|
||||
|
||||
for (let i = 0; i < context.count; ++i) {
|
||||
// this is passed into `new CodePathSegment` to add to code path.
|
||||
const allPrevSegments = [];
|
||||
|
||||
for (let j = normalizedBegin; j <= normalizedEnd; ++j) {
|
||||
allPrevSegments.push(list[j][i]);
|
||||
}
|
||||
|
||||
// note: `create` is just a wrapper that augments `new CodePathSegment`.
|
||||
segments.push(create(context.idGenerator.next(), allPrevSegments));
|
||||
}
|
||||
|
||||
return segments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inside of a `finally` block we end up with two parallel paths. If the code path
|
||||
* exits by a control statement (such as `break` or `continue`) from the `finally`
|
||||
* block, then we need to merge the remaining parallel paths back into one.
|
||||
* @param {ForkContext} context The fork context to work on.
|
||||
* @param {Array<CodePathSegment>} segments Segments to merge.
|
||||
* @returns {Array<CodePathSegment>} The merged segments.
|
||||
*/
|
||||
function mergeExtraSegments(context, segments) {
|
||||
let currentSegments = segments;
|
||||
|
||||
/*
|
||||
* We need to ensure that the array returned from this function contains no more
|
||||
* than the number of segments that the context allows. `context.count` indicates
|
||||
* how many items should be in the returned array to ensure that the new segment
|
||||
* entries will line up with the already existing segment entries.
|
||||
*/
|
||||
while (currentSegments.length > context.count) {
|
||||
const merged = [];
|
||||
|
||||
/*
|
||||
* Because `context.count` is a factor of 2 inside of a `finally` block,
|
||||
* we can divide the segment count by 2 to merge the paths together.
|
||||
* This loops through each segment in the list and creates a new `CodePathSegment`
|
||||
* that has the segment and the segment two slots away as previous segments.
|
||||
*
|
||||
* If `currentSegments` is [a,b,c,d], this will create new segments e and f, such
|
||||
* that:
|
||||
*
|
||||
* When `i` is 0:
|
||||
* a->e
|
||||
* c->e
|
||||
*
|
||||
* When `i` is 1:
|
||||
* b->f
|
||||
* d->f
|
||||
*/
|
||||
for (
|
||||
let i = 0, length = Math.floor(currentSegments.length / 2);
|
||||
i < length;
|
||||
++i
|
||||
) {
|
||||
merged.push(
|
||||
CodePathSegment.newNext(context.idGenerator.next(), [
|
||||
currentSegments[i],
|
||||
currentSegments[i + length],
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
/*
|
||||
* Go through the loop condition one more time to see if we have the
|
||||
* number of segments for the context. If not, we'll keep merging paths
|
||||
* of the merged segments until we get there.
|
||||
*/
|
||||
currentSegments = merged;
|
||||
}
|
||||
|
||||
return currentSegments;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Manages the forking of code paths.
|
||||
*/
|
||||
class ForkContext {
|
||||
/**
|
||||
* Creates a new instance.
|
||||
* @param {IdGenerator} idGenerator An identifier generator for segments.
|
||||
* @param {ForkContext|null} upper The preceding fork context.
|
||||
* @param {number} count The number of parallel segments in each element
|
||||
* of `segmentsList`.
|
||||
*/
|
||||
constructor(idGenerator, upper, count) {
|
||||
/**
|
||||
* The ID generator that will generate segment IDs for any new
|
||||
* segments that are created.
|
||||
* @type {IdGenerator}
|
||||
*/
|
||||
this.idGenerator = idGenerator;
|
||||
|
||||
/**
|
||||
* The preceding fork context.
|
||||
* @type {ForkContext|null}
|
||||
*/
|
||||
this.upper = upper;
|
||||
|
||||
/**
|
||||
* The number of elements in each element of `segmentsList`. In most
|
||||
* cases, this is 1 but can be 2 when there is a `finally` present,
|
||||
* which forks the code path outside of normal flow. In the case of nested
|
||||
* `finally` blocks, this can be a multiple of 2.
|
||||
* @type {number}
|
||||
*/
|
||||
this.count = count;
|
||||
|
||||
/**
|
||||
* The segments within this context. Each element in this array has
|
||||
* `count` elements that represent one step in each fork. For example,
|
||||
* when `segmentsList` is `[[a, b], [c, d], [e, f]]`, there is one path
|
||||
* a->c->e and one path b->d->f, and `count` is 2 because each element
|
||||
* is an array with two elements.
|
||||
* @type {Array<Array<CodePathSegment>>}
|
||||
*/
|
||||
this.segmentsList = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* The segments that begin this fork context.
|
||||
* @type {Array<CodePathSegment>}
|
||||
*/
|
||||
get head() {
|
||||
const list = this.segmentsList;
|
||||
|
||||
return list.length === 0 ? [] : list.at(-1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the context contains no segments.
|
||||
* @type {boolean}
|
||||
*/
|
||||
get empty() {
|
||||
return this.segmentsList.length === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if there are any segments that are reachable.
|
||||
* @type {boolean}
|
||||
*/
|
||||
get reachable() {
|
||||
const segments = this.head;
|
||||
|
||||
return segments.length > 0 && segments.some(isReachable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates new segments in this context and appends them to the end of the
|
||||
* already existing `CodePathSegment`s specified by `startIndex` and
|
||||
* `endIndex`.
|
||||
* @param {number} startIndex The index of the first segment in the context
|
||||
* that should be specified as previous segments for the newly created segments.
|
||||
* @param {number} endIndex The index of the last segment in the context
|
||||
* that should be specified as previous segments for the newly created segments.
|
||||
* @returns {Array<CodePathSegment>} An array of the newly created segments.
|
||||
*/
|
||||
makeNext(startIndex, endIndex) {
|
||||
return createSegments(
|
||||
this,
|
||||
startIndex,
|
||||
endIndex,
|
||||
CodePathSegment.newNext,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates new unreachable segments in this context and appends them to the end of the
|
||||
* already existing `CodePathSegment`s specified by `startIndex` and
|
||||
* `endIndex`.
|
||||
* @param {number} startIndex The index of the first segment in the context
|
||||
* that should be specified as previous segments for the newly created segments.
|
||||
* @param {number} endIndex The index of the last segment in the context
|
||||
* that should be specified as previous segments for the newly created segments.
|
||||
* @returns {Array<CodePathSegment>} An array of the newly created segments.
|
||||
*/
|
||||
makeUnreachable(startIndex, endIndex) {
|
||||
return createSegments(
|
||||
this,
|
||||
startIndex,
|
||||
endIndex,
|
||||
CodePathSegment.newUnreachable,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates new segments in this context and does not append them to the end
|
||||
* of the already existing `CodePathSegment`s specified by `startIndex` and
|
||||
* `endIndex`. The `startIndex` and `endIndex` are only used to determine if
|
||||
* the new segments should be reachable. If any of the segments in this range
|
||||
* are reachable then the new segments are also reachable; otherwise, the new
|
||||
* segments are unreachable.
|
||||
* @param {number} startIndex The index of the first segment in the context
|
||||
* that should be considered for reachability.
|
||||
* @param {number} endIndex The index of the last segment in the context
|
||||
* that should be considered for reachability.
|
||||
* @returns {Array<CodePathSegment>} An array of the newly created segments.
|
||||
*/
|
||||
makeDisconnected(startIndex, endIndex) {
|
||||
return createSegments(
|
||||
this,
|
||||
startIndex,
|
||||
endIndex,
|
||||
CodePathSegment.newDisconnected,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds segments to the head of this context.
|
||||
* @param {Array<CodePathSegment>} segments The segments to add.
|
||||
* @returns {void}
|
||||
*/
|
||||
add(segments) {
|
||||
assert(
|
||||
segments.length >= this.count,
|
||||
`${segments.length} >= ${this.count}`,
|
||||
);
|
||||
this.segmentsList.push(mergeExtraSegments(this, segments));
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the head segments with the given segments.
|
||||
* The current head segments are removed.
|
||||
* @param {Array<CodePathSegment>} replacementHeadSegments The new head segments.
|
||||
* @returns {void}
|
||||
*/
|
||||
replaceHead(replacementHeadSegments) {
|
||||
assert(
|
||||
replacementHeadSegments.length >= this.count,
|
||||
`${replacementHeadSegments.length} >= ${this.count}`,
|
||||
);
|
||||
this.segmentsList.splice(
|
||||
-1,
|
||||
1,
|
||||
mergeExtraSegments(this, replacementHeadSegments),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds all segments of a given fork context into this context.
|
||||
* @param {ForkContext} otherForkContext The fork context to add from.
|
||||
* @returns {void}
|
||||
*/
|
||||
addAll(otherForkContext) {
|
||||
assert(otherForkContext.count === this.count);
|
||||
this.segmentsList.push(...otherForkContext.segmentsList);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all segments in this context.
|
||||
* @returns {void}
|
||||
*/
|
||||
clear() {
|
||||
this.segmentsList = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new root context, meaning that there are no parent
|
||||
* fork contexts.
|
||||
* @param {IdGenerator} idGenerator An identifier generator for segments.
|
||||
* @returns {ForkContext} New fork context.
|
||||
*/
|
||||
static newRoot(idGenerator) {
|
||||
const context = new ForkContext(idGenerator, null, 1);
|
||||
|
||||
context.add([CodePathSegment.newRoot(idGenerator.next())]);
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an empty fork context preceded by a given context.
|
||||
* @param {ForkContext} parentContext The parent fork context.
|
||||
* @param {boolean} shouldForkLeavingPath Indicates that we are inside of
|
||||
* a `finally` block and should therefore fork the path that leaves
|
||||
* `finally`.
|
||||
* @returns {ForkContext} New fork context.
|
||||
*/
|
||||
static newEmpty(parentContext, shouldForkLeavingPath) {
|
||||
return new ForkContext(
|
||||
parentContext.idGenerator,
|
||||
parentContext,
|
||||
(shouldForkLeavingPath ? 2 : 1) * parentContext.count,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ForkContext;
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,MAAM,MAAM,OAAO,GAAG;IACpB,KAAK,EAAE,GAAG,CAAA;IACV,GAAG,EAAE,GAAG,CAAA;IACR,IAAI,EAAE,MAAM,CAAA;IACZ,UAAU,EAAE,MAAM,GAAG,SAAS,CAAA;IAC9B,OAAO,EAAE,MAAM,CAAA;IACf,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,CAAA;IAClB,IAAI,EAAE,KAAK,CAAC,GAAG,CAAC,CAAA;CACjB,CAAA;AAED;;;;;;;GAOG;AAEH,qBAAa,WAAY,SAAQ,SAAS;IACxC,KAAK,EAAE,GAAG,CAAA;IACV,GAAG,EAAG,GAAG,CAAA;IACT,IAAI,EAAG,MAAM,CAAA;IACb,UAAU,EAAG,MAAM,GAAG,SAAS,CAAA;IAC/B,IAAI,EAAG,KAAK,CAAC,GAAG,CAAC,CAAA;IACjB,MAAM,EAAG,KAAK,CAAC,GAAG,CAAC,CAAA;IACnB,QAAQ,EAAE,MAAM,KAAK,CAAC,OAAO,CAAC,CAAC;IAC/B,CAAC,CAAC,EAAE,MAAM,GAAG,GAAG,CAAA;gBAEJ,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC,OAAO,CAAC;CAcjE"}
|
||||
@@ -0,0 +1,68 @@
|
||||
declare module "node:assert/strict" {
|
||||
import {
|
||||
Assert,
|
||||
AssertionError,
|
||||
AssertionErrorOptions,
|
||||
AssertMessageFunction,
|
||||
AssertOptions,
|
||||
AssertPredicate,
|
||||
AssertStrict,
|
||||
deepStrictEqual,
|
||||
doesNotMatch,
|
||||
doesNotReject,
|
||||
doesNotThrow,
|
||||
fail,
|
||||
ifError,
|
||||
match,
|
||||
notDeepStrictEqual,
|
||||
notStrictEqual,
|
||||
ok,
|
||||
partialDeepStrictEqual,
|
||||
rejects,
|
||||
strictEqual,
|
||||
throws,
|
||||
} from "node:assert";
|
||||
function strict(
|
||||
value: unknown,
|
||||
message?: Error | AssertMessageFunction,
|
||||
): asserts value;
|
||||
function strict(
|
||||
value: unknown,
|
||||
message: string,
|
||||
...args: unknown[]
|
||||
): asserts value;
|
||||
namespace strict {
|
||||
export {
|
||||
Assert,
|
||||
AssertionError,
|
||||
AssertionErrorOptions,
|
||||
AssertOptions,
|
||||
AssertPredicate,
|
||||
AssertStrict,
|
||||
deepStrictEqual,
|
||||
deepStrictEqual as deepEqual,
|
||||
doesNotMatch,
|
||||
doesNotReject,
|
||||
doesNotThrow,
|
||||
fail,
|
||||
ifError,
|
||||
match,
|
||||
notDeepStrictEqual,
|
||||
notDeepStrictEqual as notDeepEqual,
|
||||
notStrictEqual,
|
||||
notStrictEqual as notEqual,
|
||||
ok,
|
||||
partialDeepStrictEqual,
|
||||
rejects,
|
||||
strict,
|
||||
strictEqual,
|
||||
strictEqual as equal,
|
||||
throws,
|
||||
};
|
||||
}
|
||||
export = strict;
|
||||
}
|
||||
declare module "assert/strict" {
|
||||
import strict = require("node:assert/strict");
|
||||
export = strict;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
declare module 'string_decoder' {
|
||||
class StringDecoder {
|
||||
constructor(encoding?: string);
|
||||
write(buffer: Buffer): string;
|
||||
end(buffer?: Buffer): string;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
import type { LibDefinition } from '../variable';
|
||||
export declare const es2018_asynciterable: LibDefinition;
|
||||
@@ -0,0 +1,285 @@
|
||||
import { expect, expectTypeOf, test } from "vitest";
|
||||
import * as z from "zod/v4";
|
||||
|
||||
test("enum from string array", () => {
|
||||
const MyEnum = z.enum(["Red", "Green", "Blue"]);
|
||||
expect(MyEnum.enum.Red).toEqual("Red");
|
||||
|
||||
type MyEnum = z.infer<typeof MyEnum>;
|
||||
expectTypeOf<MyEnum>().toEqualTypeOf<"Red" | "Green" | "Blue">();
|
||||
});
|
||||
|
||||
test("enum from const object", () => {
|
||||
const Fruits: { Apple: "apple"; Banana: "banana" } = {
|
||||
Apple: "apple",
|
||||
Banana: "banana",
|
||||
};
|
||||
const fruitEnum = z.nativeEnum(Fruits);
|
||||
type fruitEnum = z.infer<typeof fruitEnum>;
|
||||
fruitEnum.parse("apple");
|
||||
fruitEnum.parse("banana");
|
||||
fruitEnum.parse(Fruits.Apple);
|
||||
fruitEnum.parse(Fruits.Banana);
|
||||
expectTypeOf<fruitEnum>().toEqualTypeOf<"apple" | "banana">();
|
||||
});
|
||||
|
||||
test("enum from native enum", () => {
|
||||
enum Fruits {
|
||||
Apple = "apple",
|
||||
Banana = "banana",
|
||||
Orange = 3,
|
||||
}
|
||||
// @ts-ignore
|
||||
const fruitEnum = z.nativeEnum(Fruits);
|
||||
type fruitEnum = z.infer<typeof fruitEnum>;
|
||||
fruitEnum.parse("apple");
|
||||
fruitEnum.parse("banana");
|
||||
fruitEnum.parse(Fruits.Apple);
|
||||
fruitEnum.parse(Fruits.Banana);
|
||||
|
||||
expect(fruitEnum.safeParse("Apple").success).toEqual(false);
|
||||
expect(fruitEnum.safeParse("Cantaloupe").success).toEqual(false);
|
||||
|
||||
expectTypeOf<fruitEnum>().toMatchTypeOf<Fruits>();
|
||||
expectTypeOf<Fruits>().toMatchTypeOf<fruitEnum>();
|
||||
});
|
||||
|
||||
test("enum from native enum with numeric keys", () => {
|
||||
const FruitValues = {
|
||||
Apple: 10,
|
||||
Banana: 20,
|
||||
// @ts-ignore
|
||||
} as const;
|
||||
const fruitEnum = z.nativeEnum(FruitValues);
|
||||
type fruitEnum = z.infer<typeof fruitEnum>;
|
||||
fruitEnum.parse(10);
|
||||
fruitEnum.parse(20);
|
||||
fruitEnum.parse(FruitValues.Apple);
|
||||
fruitEnum.parse(FruitValues.Banana);
|
||||
expectTypeOf<fruitEnum>().toEqualTypeOf<10 | 20>();
|
||||
});
|
||||
|
||||
test("issue metadata", () => {
|
||||
const schema = z.enum(["Red", "Green", "Blue"]);
|
||||
const result = schema.safeParse("Yellow");
|
||||
expect(result.error!.issues[0]).toMatchInlineSnapshot(`
|
||||
{
|
||||
"code": "invalid_value",
|
||||
"message": "Invalid option: expected one of "Red"|"Green"|"Blue"",
|
||||
"path": [],
|
||||
"values": [
|
||||
"Red",
|
||||
"Green",
|
||||
"Blue",
|
||||
],
|
||||
}
|
||||
`);
|
||||
});
|
||||
|
||||
test("enum from non-const inputs", () => {
|
||||
const foods = ["Pasta", "Pizza", "Tacos", "Burgers", "Salad"];
|
||||
const FoodEnum = z.enum(foods);
|
||||
|
||||
expectTypeOf<z.infer<typeof FoodEnum>>().toEqualTypeOf<string>();
|
||||
expect(FoodEnum.safeParse("Pasta").success).toEqual(true);
|
||||
expect(FoodEnum.safeParse("Cucumbers").success).toEqual(false);
|
||||
});
|
||||
|
||||
test("get options", () => {
|
||||
expect(z.enum(["tuna", "trout"]).options).toEqual(["tuna", "trout"]);
|
||||
});
|
||||
|
||||
test("readonly enum", () => {
|
||||
const HTTP_SUCCESS = ["200", "201"] as const;
|
||||
const arg = z.enum(HTTP_SUCCESS);
|
||||
type arg = z.infer<typeof arg>;
|
||||
expectTypeOf<arg>().toEqualTypeOf<"200" | "201">();
|
||||
|
||||
arg.parse("201");
|
||||
expect(() => arg.parse("202")).toThrow();
|
||||
});
|
||||
|
||||
test("error map", () => {
|
||||
const result = z
|
||||
.enum(["test"], { error: (iss) => (iss.input === undefined ? "REQUIRED" : undefined) })
|
||||
.safeParse(undefined);
|
||||
expect(result.success).toEqual(false);
|
||||
if (!result.success) {
|
||||
expect(result.error.issues[0].message).toEqual("REQUIRED");
|
||||
}
|
||||
});
|
||||
|
||||
test("type signatures", () => {
|
||||
const a = z.enum(["a", "b", "c"]);
|
||||
const b = z.enum(a.options);
|
||||
expectTypeOf(a).toEqualTypeOf(b);
|
||||
|
||||
const c = z.enum({ a: 1, b: 2 } as const);
|
||||
expectTypeOf(c.enum).toEqualTypeOf<{
|
||||
readonly a: 1;
|
||||
readonly b: 2;
|
||||
}>();
|
||||
|
||||
enum Fruit {
|
||||
Apple = "apple",
|
||||
Banana = "banana",
|
||||
Orange = "orange",
|
||||
}
|
||||
const d = z.enum(Fruit);
|
||||
expectTypeOf(d.enum).toEqualTypeOf(Fruit);
|
||||
|
||||
const e = z.enum({ a: 1, b: 2 });
|
||||
expectTypeOf(e.enum).toEqualTypeOf<{
|
||||
readonly a: 1;
|
||||
readonly b: 2;
|
||||
}>();
|
||||
});
|
||||
|
||||
test("extract", () => {
|
||||
const foods = ["Pasta", "Pizza", "Tacos", "Burgers", "Salad"] as const;
|
||||
const FoodEnum = z.enum(foods);
|
||||
const ItalianEnum = FoodEnum.extract(["Pasta", "Pizza"]);
|
||||
|
||||
expect(ItalianEnum.safeParse("Pasta").success).toEqual(true);
|
||||
expect(ItalianEnum.safeParse("Tacos").success).toEqual(false);
|
||||
|
||||
expectTypeOf<z.infer<typeof ItalianEnum>>().toEqualTypeOf<"Pasta" | "Pizza">();
|
||||
});
|
||||
|
||||
test("exclude", () => {
|
||||
const foods = ["Pasta", "Pizza", "Tacos", "Burgers", "Salad"] as const;
|
||||
const FoodEnum = z.enum(foods);
|
||||
const UnhealthyEnum = FoodEnum.exclude(["Salad"]);
|
||||
|
||||
expect(UnhealthyEnum.safeParse("Pasta").success).toEqual(true);
|
||||
expect(UnhealthyEnum.safeParse("Salad").success).toEqual(false);
|
||||
expectTypeOf<z.infer<typeof UnhealthyEnum>>().toEqualTypeOf<"Pasta" | "Pizza" | "Tacos" | "Burgers">();
|
||||
|
||||
const EmptyFoodEnum = FoodEnum.exclude(foods);
|
||||
expectTypeOf<typeof EmptyFoodEnum>().toEqualTypeOf<z.ZodEnum<{}>>();
|
||||
expectTypeOf<z.infer<typeof EmptyFoodEnum>>().toEqualTypeOf<never>();
|
||||
});
|
||||
|
||||
test("error map inheritance", () => {
|
||||
const foods = ["Pasta", "Pizza", "Tacos", "Burgers", "Salad"] as const;
|
||||
const FoodEnum = z.enum(foods, { error: () => "This is not food!" });
|
||||
const ItalianEnum = FoodEnum.extract(["Pasta", "Pizza"]);
|
||||
|
||||
const foodsError = FoodEnum.safeParse("Cucumbers");
|
||||
const italianError = ItalianEnum.safeParse("Tacos");
|
||||
|
||||
expect(foodsError.error!.issues[0].message).toEqual(italianError.error!.issues[0].message);
|
||||
|
||||
const UnhealthyEnum = FoodEnum.exclude(["Salad"], {
|
||||
error: () => ({ message: "This is not healthy food!" }),
|
||||
});
|
||||
const unhealthyError = UnhealthyEnum.safeParse("Salad");
|
||||
if (!unhealthyError.success) {
|
||||
expect(unhealthyError.error.issues[0].message).toEqual("This is not healthy food!");
|
||||
}
|
||||
});
|
||||
|
||||
test("readonly in ZodEnumDef", () => {
|
||||
type _a = z.ZodEnum<{ readonly a: "a"; readonly b: "b" }>;
|
||||
type _b = z.ZodEnum<{ a: "a"; b: "b" }>;
|
||||
});
|
||||
|
||||
test("enum error message, invalid enum elementstring", () => {
|
||||
const result = z.enum(["Tuna", "Trout"]).safeParse("Salmon");
|
||||
expect(result.success).toEqual(false);
|
||||
expect(result.error!.issues.length).toEqual(1);
|
||||
|
||||
expect(result.error).toMatchInlineSnapshot(`
|
||||
[ZodError: [
|
||||
{
|
||||
"code": "invalid_value",
|
||||
"values": [
|
||||
"Tuna",
|
||||
"Trout"
|
||||
],
|
||||
"path": [],
|
||||
"message": "Invalid option: expected one of \\"Tuna\\"|\\"Trout\\""
|
||||
}
|
||||
]]
|
||||
`);
|
||||
});
|
||||
|
||||
test("enum error message, invalid type", () => {
|
||||
const result = z.enum(["Tuna", "Trout"]).safeParse(12);
|
||||
expect(result.success).toEqual(false);
|
||||
expect(result.error!.issues.length).toEqual(1);
|
||||
// expect(result.error!.issues[0].message).toEqual('Invalid input: expected one of "Tuna"|"Trout"');
|
||||
expect(result.error).toMatchInlineSnapshot(`
|
||||
[ZodError: [
|
||||
{
|
||||
"code": "invalid_value",
|
||||
"values": [
|
||||
"Tuna",
|
||||
"Trout"
|
||||
],
|
||||
"path": [],
|
||||
"message": "Invalid option: expected one of \\"Tuna\\"|\\"Trout\\""
|
||||
}
|
||||
]]
|
||||
`);
|
||||
});
|
||||
|
||||
test("nativeEnum default error message", () => {
|
||||
enum Fish {
|
||||
Tuna = "Tuna",
|
||||
Trout = "Trout",
|
||||
}
|
||||
const result = z.nativeEnum(Fish).safeParse("Salmon");
|
||||
expect(result.success).toEqual(false);
|
||||
expect(result.error!.issues.length).toEqual(1);
|
||||
// expect(result.error!.issues[0].message).toEqual('Invalid input: expected one of "Tuna"|"Trout"');
|
||||
expect(result.error).toMatchInlineSnapshot(`
|
||||
[ZodError: [
|
||||
{
|
||||
"code": "invalid_value",
|
||||
"values": [
|
||||
"Tuna",
|
||||
"Trout"
|
||||
],
|
||||
"path": [],
|
||||
"message": "Invalid option: expected one of \\"Tuna\\"|\\"Trout\\""
|
||||
}
|
||||
]]
|
||||
`);
|
||||
});
|
||||
|
||||
test("enum with message returns the custom error message", () => {
|
||||
const schema = z.enum(["apple", "banana"], {
|
||||
message: "the value provided is invalid",
|
||||
});
|
||||
|
||||
const result1 = schema.safeParse("berries");
|
||||
expect(result1.success).toEqual(false);
|
||||
if (!result1.success) {
|
||||
expect(result1.error.issues[0].message).toEqual("the value provided is invalid");
|
||||
}
|
||||
|
||||
const result2 = schema.safeParse(undefined);
|
||||
expect(result2.success).toEqual(false);
|
||||
if (!result2.success) {
|
||||
expect(result2.error.issues[0].message).toEqual("the value provided is invalid");
|
||||
}
|
||||
|
||||
const result3 = schema.safeParse("banana");
|
||||
expect(result3.success).toEqual(true);
|
||||
|
||||
const result4 = schema.safeParse(null);
|
||||
expect(result4.success).toEqual(false);
|
||||
if (!result4.success) {
|
||||
expect(result4.error.issues[0].message).toEqual("the value provided is invalid");
|
||||
}
|
||||
});
|
||||
|
||||
test("enum with diagonal keys", () => {
|
||||
const schema_02 = z.enum({
|
||||
A: 1,
|
||||
B: "A",
|
||||
});
|
||||
|
||||
expect(schema_02.safeParse("A")).toMatchObject({ success: true });
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"poseidon.d.ts","sourceRoot":"","sources":["../../src/abstract/poseidon.ts"],"names":[],"mappings":"AAUA,OAAO,EAAwB,KAAK,MAAM,EAAiB,MAAM,cAAc,CAAC;AAyBhF,MAAM,MAAM,iBAAiB,GAAG;IAC9B,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACnB,CAAC,EAAE,MAAM,CAAC;IACV,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB,CAAC;AA0DF,MAAM,MAAM,iBAAiB,GAAG,iBAAiB,GAAG;IAClD,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,KAAK,iBAAiB,GAAG;IAAE,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC;IAAC,cAAc,EAAE,MAAM,EAAE,EAAE,CAAA;CAAE,CAAC;AAIzE,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,iBAAiB,EAAE,OAAO,GAAE,MAAU,GAAG,iBAAiB,CAuBjG;AAED,MAAM,MAAM,YAAY,GAAG,iBAAiB,GAC1C,iBAAiB,GAAG;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,oBAAoB,CAAC,EAAE,OAAO,CAAC;CAChC,CAAC;AAEJ,wBAAgB,YAAY,CAAC,IAAI,EAAE,YAAY,GAAG,QAAQ,CAAC;IACzD,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAC9B,cAAc,EAAE,MAAM,EAAE,EAAE,CAAC;IAC3B,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC;IAChB,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACnB,CAAC,EAAE,MAAM,CAAC;IACV,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,oBAAoB,CAAC,EAAE,OAAO,CAAC;CAChC,CAAC,CAwCD;AAED,wBAAgB,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,CAalE;AAED,MAAM,MAAM,UAAU,GAAG;IACvB,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC;IAE7B,cAAc,EAAE,MAAM,EAAE,EAAE,CAAC;CAC5B,CAAC;AACF,kCAAkC;AAClC,wBAAgB,QAAQ,CAAC,IAAI,EAAE,YAAY,GAAG,UAAU,CAmCvD;AAED,qBAAa,cAAc;IACzB,OAAO,CAAC,EAAE,CAAiB;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;IAC1B,OAAO,CAAC,KAAK,CAAW;IACxB,OAAO,CAAC,GAAG,CAAK;IAChB,OAAO,CAAC,WAAW,CAAQ;gBAEf,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU;IAQhF,OAAO,CAAC,OAAO;IAGf,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI;IAgB7B,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE;IAahC,KAAK,IAAI,IAAI;IAKb,KAAK,IAAI,cAAc;CAMxB;AAED,MAAM,MAAM,kBAAkB,GAAG,IAAI,CAAC,YAAY,EAAE,GAAG,CAAC,GAAG;IACzD,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,kBAAkB,GAAG,MAAM,cAAc,CAW7E"}
|
||||
@@ -0,0 +1,223 @@
|
||||
const { test } = require('node:test')
|
||||
const { strict: assert } = require('node:assert')
|
||||
const slowRedact = require('../index.js')
|
||||
|
||||
/* eslint-disable no-proto */
|
||||
|
||||
test('prototype pollution: __proto__ path should not pollute Object prototype', () => {
|
||||
const obj = {
|
||||
user: { name: 'john' },
|
||||
__proto__: { isAdmin: true }
|
||||
}
|
||||
|
||||
const redact = slowRedact({
|
||||
paths: ['__proto__.isAdmin'],
|
||||
serialize: false
|
||||
})
|
||||
|
||||
const result = redact(obj)
|
||||
|
||||
// Should not pollute Object.prototype
|
||||
assert.strictEqual(Object.prototype.isAdmin, undefined)
|
||||
assert.strictEqual({}.isAdmin, undefined)
|
||||
|
||||
// Should redact the __proto__ property if it exists as a regular property
|
||||
assert.strictEqual(result.__proto__.isAdmin, '[REDACTED]')
|
||||
})
|
||||
|
||||
test('prototype pollution: constructor.prototype path should not pollute', () => {
|
||||
const obj = {
|
||||
user: { name: 'john' },
|
||||
constructor: {
|
||||
prototype: { isAdmin: true }
|
||||
}
|
||||
}
|
||||
|
||||
const redact = slowRedact({
|
||||
paths: ['constructor.prototype.isAdmin'],
|
||||
serialize: false
|
||||
})
|
||||
|
||||
const result = redact(obj)
|
||||
|
||||
// Should not pollute Object.prototype
|
||||
assert.strictEqual(Object.prototype.isAdmin, undefined)
|
||||
assert.strictEqual({}.isAdmin, undefined)
|
||||
|
||||
// Should redact the constructor.prototype property if it exists as a regular property
|
||||
assert.strictEqual(result.constructor.prototype.isAdmin, '[REDACTED]')
|
||||
})
|
||||
|
||||
test('prototype pollution: nested __proto__ should not pollute', () => {
|
||||
const obj = {
|
||||
user: {
|
||||
settings: {
|
||||
__proto__: { isAdmin: true }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const redact = slowRedact({
|
||||
paths: ['user.settings.__proto__.isAdmin'],
|
||||
serialize: false
|
||||
})
|
||||
|
||||
const result = redact(obj)
|
||||
|
||||
// Should not pollute Object.prototype
|
||||
assert.strictEqual(Object.prototype.isAdmin, undefined)
|
||||
assert.strictEqual({}.isAdmin, undefined)
|
||||
|
||||
// Should redact the nested __proto__ property
|
||||
assert.strictEqual(result.user.settings.__proto__.isAdmin, '[REDACTED]')
|
||||
})
|
||||
|
||||
test('prototype pollution: bracket notation __proto__ should not pollute', () => {
|
||||
const obj = {
|
||||
user: { name: 'john' },
|
||||
__proto__: { isAdmin: true }
|
||||
}
|
||||
|
||||
const redact = slowRedact({
|
||||
paths: ['["__proto__"]["isAdmin"]'],
|
||||
serialize: false
|
||||
})
|
||||
|
||||
const result = redact(obj)
|
||||
|
||||
// Should not pollute Object.prototype
|
||||
assert.strictEqual(Object.prototype.isAdmin, undefined)
|
||||
assert.strictEqual({}.isAdmin, undefined)
|
||||
|
||||
// Should redact the __proto__ property when accessed via bracket notation
|
||||
assert.strictEqual(result.__proto__.isAdmin, '[REDACTED]')
|
||||
})
|
||||
|
||||
test('prototype pollution: wildcard with __proto__ should not pollute', () => {
|
||||
const obj = {
|
||||
users: {
|
||||
__proto__: { isAdmin: true },
|
||||
user1: { name: 'john' },
|
||||
user2: { name: 'jane' }
|
||||
}
|
||||
}
|
||||
|
||||
const redact = slowRedact({
|
||||
paths: ['users.*'],
|
||||
serialize: false
|
||||
})
|
||||
|
||||
const result = redact(obj)
|
||||
|
||||
// Should not pollute Object.prototype
|
||||
assert.strictEqual(Object.prototype.isAdmin, undefined)
|
||||
assert.strictEqual({}.isAdmin, undefined)
|
||||
|
||||
// Should redact only own properties
|
||||
assert.strictEqual(result.users.user1, '[REDACTED]')
|
||||
assert.strictEqual(result.users.user2, '[REDACTED]')
|
||||
|
||||
// __proto__ should only be redacted if it's an own property, not inherited
|
||||
if (Object.prototype.hasOwnProperty.call(obj.users, '__proto__')) {
|
||||
assert.strictEqual(result.users.__proto__, '[REDACTED]')
|
||||
}
|
||||
})
|
||||
|
||||
test('prototype pollution: malicious JSON payload should not pollute', () => {
|
||||
// Simulate a malicious payload that might come from JSON.parse
|
||||
const maliciousObj = JSON.parse('{"user": {"name": "john"}, "__proto__": {"isAdmin": true}}')
|
||||
|
||||
const redact = slowRedact({
|
||||
paths: ['__proto__.isAdmin'],
|
||||
serialize: false
|
||||
})
|
||||
|
||||
const result = redact(maliciousObj)
|
||||
|
||||
// Should not pollute Object.prototype
|
||||
assert.strictEqual(Object.prototype.isAdmin, undefined)
|
||||
assert.strictEqual({}.isAdmin, undefined)
|
||||
|
||||
// The malicious payload should have been redacted
|
||||
assert.strictEqual(result.__proto__.isAdmin, '[REDACTED]')
|
||||
})
|
||||
|
||||
test('prototype pollution: verify prototype chain is preserved', () => {
|
||||
function CustomClass () {
|
||||
this.data = 'test'
|
||||
}
|
||||
CustomClass.prototype.method = function () { return 'original' }
|
||||
|
||||
const obj = new CustomClass()
|
||||
|
||||
const redact = slowRedact({
|
||||
paths: ['data'],
|
||||
serialize: false
|
||||
})
|
||||
|
||||
const result = redact(obj)
|
||||
|
||||
// Should redact the data property
|
||||
assert.strictEqual(result.data, '[REDACTED]')
|
||||
|
||||
// Should preserve the original prototype chain
|
||||
assert.strictEqual(result.method(), 'original')
|
||||
assert.strictEqual(Object.getPrototypeOf(result), CustomClass.prototype)
|
||||
})
|
||||
|
||||
test('prototype pollution: setValue should not create prototype pollution', () => {
|
||||
const obj = { user: { name: 'john' } }
|
||||
|
||||
// Try to pollute via non-existent path that could create __proto__
|
||||
const redact = slowRedact({
|
||||
paths: ['__proto__.isAdmin'],
|
||||
serialize: false
|
||||
})
|
||||
|
||||
const result = redact(obj)
|
||||
|
||||
// Should not pollute Object.prototype
|
||||
assert.strictEqual(Object.prototype.isAdmin, undefined)
|
||||
assert.strictEqual({}.isAdmin, undefined)
|
||||
|
||||
// Should not create the path if it doesn't exist
|
||||
// The __proto__ property may exist due to Object.create, but should not contain our redacted value
|
||||
if (result.__proto__) {
|
||||
assert.strictEqual(result.__proto__.isAdmin, undefined)
|
||||
}
|
||||
})
|
||||
|
||||
test('prototype pollution: deep nested prototype properties should not pollute', () => {
|
||||
const obj = {
|
||||
level1: {
|
||||
level2: {
|
||||
level3: {
|
||||
__proto__: { isAdmin: true },
|
||||
constructor: {
|
||||
prototype: { isEvil: true }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const redact = slowRedact({
|
||||
paths: [
|
||||
'level1.level2.level3.__proto__.isAdmin',
|
||||
'level1.level2.level3.constructor.prototype.isEvil'
|
||||
],
|
||||
serialize: false
|
||||
})
|
||||
|
||||
const result = redact(obj)
|
||||
|
||||
// Should not pollute Object.prototype
|
||||
assert.strictEqual(Object.prototype.isAdmin, undefined)
|
||||
assert.strictEqual(Object.prototype.isEvil, undefined)
|
||||
assert.strictEqual({}.isAdmin, undefined)
|
||||
assert.strictEqual({}.isEvil, undefined)
|
||||
|
||||
// Should redact the deep nested properties
|
||||
assert.strictEqual(result.level1.level2.level3.__proto__.isAdmin, '[REDACTED]')
|
||||
assert.strictEqual(result.level1.level2.level3.constructor.prototype.isEvil, '[REDACTED]')
|
||||
})
|
||||
@@ -0,0 +1,3 @@
|
||||
var stringify = require('../');
|
||||
var obj = { c: 6, b: [4,5], a: 3 };
|
||||
console.log(stringify(obj));
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* @fileoverview Validates newlines before and after dots
|
||||
* @author Greg Cochard
|
||||
* @deprecated in ESLint v8.53.0
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
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: "dot-location",
|
||||
url: "https://eslint.style/rules/dot-location",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
type: "layout",
|
||||
|
||||
docs: {
|
||||
description: "Enforce consistent newlines before and after dots",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/latest/rules/dot-location",
|
||||
},
|
||||
|
||||
schema: [
|
||||
{
|
||||
enum: ["object", "property"],
|
||||
},
|
||||
],
|
||||
|
||||
fixable: "code",
|
||||
|
||||
messages: {
|
||||
expectedDotAfterObject:
|
||||
"Expected dot to be on same line as object.",
|
||||
expectedDotBeforeProperty:
|
||||
"Expected dot to be on same line as property.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const config = context.options[0];
|
||||
|
||||
// default to onObject if no preference is passed
|
||||
const onObject = config === "object" || !config;
|
||||
|
||||
const sourceCode = context.sourceCode;
|
||||
|
||||
/**
|
||||
* Reports if the dot between object and property is on the correct location.
|
||||
* @param {ASTNode} node The `MemberExpression` node.
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkDotLocation(node) {
|
||||
const property = node.property;
|
||||
const dotToken = sourceCode.getTokenBefore(property);
|
||||
|
||||
if (onObject) {
|
||||
// `obj` expression can be parenthesized, but those paren tokens are not a part of the `obj` node.
|
||||
const tokenBeforeDot = sourceCode.getTokenBefore(dotToken);
|
||||
|
||||
if (!astUtils.isTokenOnSameLine(tokenBeforeDot, dotToken)) {
|
||||
context.report({
|
||||
node,
|
||||
loc: dotToken.loc,
|
||||
messageId: "expectedDotAfterObject",
|
||||
*fix(fixer) {
|
||||
if (
|
||||
dotToken.value.startsWith(".") &&
|
||||
astUtils.isDecimalIntegerNumericToken(
|
||||
tokenBeforeDot,
|
||||
)
|
||||
) {
|
||||
yield fixer.insertTextAfter(
|
||||
tokenBeforeDot,
|
||||
` ${dotToken.value}`,
|
||||
);
|
||||
} else {
|
||||
yield fixer.insertTextAfter(
|
||||
tokenBeforeDot,
|
||||
dotToken.value,
|
||||
);
|
||||
}
|
||||
yield fixer.remove(dotToken);
|
||||
},
|
||||
});
|
||||
}
|
||||
} else if (!astUtils.isTokenOnSameLine(dotToken, property)) {
|
||||
context.report({
|
||||
node,
|
||||
loc: dotToken.loc,
|
||||
messageId: "expectedDotBeforeProperty",
|
||||
*fix(fixer) {
|
||||
yield fixer.remove(dotToken);
|
||||
yield fixer.insertTextBefore(property, dotToken.value);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the spacing of the dot within a member expression.
|
||||
* @param {ASTNode} node The node to check.
|
||||
* @returns {void}
|
||||
*/
|
||||
function checkNode(node) {
|
||||
if (!node.computed) {
|
||||
checkDotLocation(node);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
MemberExpression: checkNode,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,138 @@
|
||||
/* eslint-disable @typescript-eslint/unified-signatures */
|
||||
import {Options as LocatePathOptions} from 'locate-path';
|
||||
|
||||
declare const stop: unique symbol;
|
||||
|
||||
declare namespace findUp {
|
||||
interface Options extends LocatePathOptions {}
|
||||
|
||||
type StopSymbol = typeof stop;
|
||||
|
||||
type Match = string | StopSymbol | undefined;
|
||||
}
|
||||
|
||||
declare const findUp: {
|
||||
sync: {
|
||||
/**
|
||||
Synchronously check if a path exists.
|
||||
|
||||
@param path - Path to the file or directory.
|
||||
@returns Whether the path exists.
|
||||
|
||||
@example
|
||||
```
|
||||
import findUp = require('find-up');
|
||||
|
||||
console.log(findUp.sync.exists('/Users/sindresorhus/unicorn.png'));
|
||||
//=> true
|
||||
```
|
||||
*/
|
||||
exists: (path: string) => boolean;
|
||||
|
||||
/**
|
||||
Synchronously find a file or directory by walking up parent directories.
|
||||
|
||||
@param name - Name of the file or directory to find. Can be multiple.
|
||||
@returns The first path found (by respecting the order of `name`s) or `undefined` if none could be found.
|
||||
*/
|
||||
(name: string | readonly string[], options?: findUp.Options): string | undefined;
|
||||
|
||||
/**
|
||||
Synchronously find a file or directory by walking up parent directories.
|
||||
|
||||
@param matcher - Called for each directory in the search. Return a path or `findUp.stop` to stop the search.
|
||||
@returns The first path found or `undefined` if none could be found.
|
||||
|
||||
@example
|
||||
```
|
||||
import path = require('path');
|
||||
import findUp = require('find-up');
|
||||
|
||||
console.log(findUp.sync(directory => {
|
||||
const hasUnicorns = findUp.sync.exists(path.join(directory, 'unicorn.png'));
|
||||
return hasUnicorns && directory;
|
||||
}, {type: 'directory'}));
|
||||
//=> '/Users/sindresorhus'
|
||||
```
|
||||
*/
|
||||
(matcher: (directory: string) => findUp.Match, options?: findUp.Options): string | undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
Check if a path exists.
|
||||
|
||||
@param path - Path to a file or directory.
|
||||
@returns Whether the path exists.
|
||||
|
||||
@example
|
||||
```
|
||||
import findUp = require('find-up');
|
||||
|
||||
(async () => {
|
||||
console.log(await findUp.exists('/Users/sindresorhus/unicorn.png'));
|
||||
//=> true
|
||||
})();
|
||||
```
|
||||
*/
|
||||
exists: (path: string) => Promise<boolean>;
|
||||
|
||||
/**
|
||||
Return this in a `matcher` function to stop the search and force `findUp` to immediately return `undefined`.
|
||||
*/
|
||||
readonly stop: findUp.StopSymbol;
|
||||
|
||||
/**
|
||||
Find a file or directory by walking up parent directories.
|
||||
|
||||
@param name - Name of the file or directory to find. Can be multiple.
|
||||
@returns The first path found (by respecting the order of `name`s) or `undefined` if none could be found.
|
||||
|
||||
@example
|
||||
```
|
||||
// /
|
||||
// └── Users
|
||||
// └── sindresorhus
|
||||
// ├── unicorn.png
|
||||
// └── foo
|
||||
// └── bar
|
||||
// ├── baz
|
||||
// └── example.js
|
||||
|
||||
// example.js
|
||||
import findUp = require('find-up');
|
||||
|
||||
(async () => {
|
||||
console.log(await findUp('unicorn.png'));
|
||||
//=> '/Users/sindresorhus/unicorn.png'
|
||||
|
||||
console.log(await findUp(['rainbow.png', 'unicorn.png']));
|
||||
//=> '/Users/sindresorhus/unicorn.png'
|
||||
})();
|
||||
```
|
||||
*/
|
||||
(name: string | readonly string[], options?: findUp.Options): Promise<string | undefined>;
|
||||
|
||||
/**
|
||||
Find a file or directory by walking up parent directories.
|
||||
|
||||
@param matcher - Called for each directory in the search. Return a path or `findUp.stop` to stop the search.
|
||||
@returns The first path found or `undefined` if none could be found.
|
||||
|
||||
@example
|
||||
```
|
||||
import path = require('path');
|
||||
import findUp = require('find-up');
|
||||
|
||||
(async () => {
|
||||
console.log(await findUp(async directory => {
|
||||
const hasUnicorns = await findUp.exists(path.join(directory, 'unicorn.png'));
|
||||
return hasUnicorns && directory;
|
||||
}, {type: 'directory'}));
|
||||
//=> '/Users/sindresorhus'
|
||||
})();
|
||||
```
|
||||
*/
|
||||
(matcher: (directory: string) => (findUp.Match | Promise<findUp.Match>), options?: findUp.Options): Promise<string | undefined>;
|
||||
};
|
||||
|
||||
export = findUp;
|
||||
Reference in New Issue
Block a user