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,15 @@
{
"permissions": {
"allow": [
"Bash(npx tap:*)",
"Bash(node:*)",
"Bash(for i in 1 2 3 4 5)",
"Bash(do)",
"Bash(echo:*)",
"Bash(done)",
"Bash(npm test:*)"
],
"deny": [],
"ask": []
}
}

View File

@@ -0,0 +1,8 @@
"use strict";
var _array_like_to_array = require("./_array_like_to_array.cjs");
function _array_without_holes(arr) {
if (Array.isArray(arr)) return _array_like_to_array._(arr);
}
exports._ = _array_without_holes;

View File

@@ -0,0 +1,817 @@
/*
Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import estraverse from "estraverse";
import esrecurse from "esrecurse";
import Reference from "./reference.js";
import Variable from "./variable.js";
import PatternVisitor from "./pattern-visitor.js";
import { Definition, ParameterDefinition } from "./definition.js";
import { assert } from "./assert.js";
/** @import * as types from "eslint-scope" */
/** @import ESTree from "estree" */
const { Syntax } = estraverse;
/**
* Traverse identifier in pattern
* @param {Object} options options
* @param {ESTree.Pattern} rootPattern root pattern
* @param {?Referencer} referencer referencer
* @param {types.PatternVisitorCallback} callback callback
* @returns {void}
*/
function traverseIdentifierInPattern(
options,
rootPattern,
referencer,
callback,
) {
// Call the callback at left hand identifier nodes, and Collect right hand nodes.
const visitor = new PatternVisitor(options, rootPattern, callback);
visitor.visit(rootPattern);
// Process the right hand nodes recursively.
if (referencer !== null && referencer !== void 0) {
visitor.rightHandNodes.forEach(referencer.visit, referencer);
}
}
// Importing ImportDeclaration.
// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation
// https://github.com/estree/estree/blob/master/es6.md#importdeclaration
// FIXME: Now, we don't create module environment, because the context is
// implementation dependent.
/**
* Visitor for import specifiers.
*/
class Importer extends esrecurse.Visitor {
constructor(declaration, referencer) {
super(null, referencer.options);
this.declaration = declaration;
this.referencer = referencer;
}
visitImport(id, specifier) {
this.referencer.visitPattern(id, pattern => {
this.referencer
.currentScope()
.__define(
pattern,
new Definition(
Variable.ImportBinding,
pattern,
specifier,
this.declaration,
null,
null,
),
);
});
}
ImportNamespaceSpecifier(node) {
const local = node.local || node.id;
if (local) {
this.visitImport(local, node);
}
}
ImportDefaultSpecifier(node) {
const local = node.local || node.id;
this.visitImport(local, node);
}
ImportSpecifier(node) {
const local = node.local || node.id;
if (node.name) {
this.visitImport(node.name, node);
} else {
this.visitImport(local, node);
}
}
}
/**
* Referencing variables and creating bindings.
* @implements {types.Referencer}
*/
class Referencer extends esrecurse.Visitor {
constructor(options, scopeManager) {
super(null, options);
this.options = options;
this.scopeManager = scopeManager;
this.parent = null;
this.isInnerMethodDefinition = false;
}
currentScope() {
return this.scopeManager.__currentScope;
}
close(node) {
while (this.currentScope() && node === this.currentScope().block) {
this.scopeManager.__currentScope = this.currentScope().__close(
this.scopeManager,
);
}
}
pushInnerMethodDefinition(isInnerMethodDefinition) {
const previous = this.isInnerMethodDefinition;
this.isInnerMethodDefinition = isInnerMethodDefinition;
return previous;
}
popInnerMethodDefinition(isInnerMethodDefinition) {
this.isInnerMethodDefinition = isInnerMethodDefinition;
}
referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) {
const scope = this.currentScope();
assignments.forEach(assignment => {
scope.__referencing(
pattern,
Reference.WRITE,
assignment.right,
maybeImplicitGlobal,
pattern !== assignment.left,
init,
);
});
}
visitPattern(node, options, callback) {
let visitPatternOptions = options;
let visitPatternCallback = callback;
if (typeof options === "function") {
visitPatternCallback = options;
visitPatternOptions = { processRightHandNodes: false };
}
traverseIdentifierInPattern(
this.options,
node,
visitPatternOptions.processRightHandNodes ? this : null,
visitPatternCallback,
);
}
visitFunction(node) {
let i, iz;
// FunctionDeclaration name is defined in upper scope
// NOTE: Not referring variableScope. It is intended.
// Since
// in ES5, FunctionDeclaration should be in FunctionBody.
// in ES6, FunctionDeclaration should be block scoped.
if (node.type === Syntax.FunctionDeclaration) {
// id is defined in upper scope
this.currentScope().__define(
node.id,
new Definition(
Variable.FunctionName,
node.id,
node,
null,
null,
null,
),
);
}
// FunctionExpression with name creates its special scope;
// FunctionExpressionNameScope.
if (node.type === Syntax.FunctionExpression && node.id) {
this.scopeManager.__nestFunctionExpressionNameScope(node);
}
// Consider this function is in the MethodDefinition.
this.scopeManager.__nestFunctionScope(
node,
this.isInnerMethodDefinition,
);
const that = this;
/**
* Visit pattern callback
* @param {ESTree.Pattern} pattern pattern
* @param {Object} info info
* @returns {void}
*/
function visitPatternCallback(pattern, info) {
that.currentScope().__define(
pattern,
new ParameterDefinition(pattern, node, i, info.rest),
);
that.referencingDefaultValue(pattern, info.assignments, null, true);
}
// Process parameter declarations.
for (i = 0, iz = node.params.length; i < iz; ++i) {
this.visitPattern(
node.params[i],
{ processRightHandNodes: true },
visitPatternCallback,
);
}
// if there's a rest argument, add that
if (node.rest) {
this.visitPattern(
{
type: "RestElement",
argument: node.rest,
},
pattern => {
this.currentScope().__define(
pattern,
new ParameterDefinition(
pattern,
node,
node.params.length,
true,
),
);
},
);
}
// In TypeScript there are a number of function-like constructs which have no body,
// so check it exists before traversing
if (node.body) {
// Skip BlockStatement to prevent creating BlockStatement scope.
if (node.body.type === Syntax.BlockStatement) {
this.visitChildren(node.body);
} else {
this.visit(node.body);
}
}
this.close(node);
}
visitClass(node) {
if (node.type === Syntax.ClassDeclaration) {
this.currentScope().__define(
node.id,
new Definition(
Variable.ClassName,
node.id,
node,
null,
null,
null,
),
);
}
this.scopeManager.__nestClassScope(node);
if (node.id) {
this.currentScope().__define(
node.id,
new Definition(Variable.ClassName, node.id, node),
);
}
this.visit(node.superClass);
this.visit(node.body);
this.close(node);
}
visitProperty(node) {
let previous;
if (node.computed) {
this.visit(node.key);
}
const isMethodDefinition = node.type === Syntax.MethodDefinition;
if (isMethodDefinition) {
previous = this.pushInnerMethodDefinition(true);
}
this.visit(node.value);
if (isMethodDefinition) {
this.popInnerMethodDefinition(previous);
}
}
visitForIn(node) {
if (
node.left.type === Syntax.VariableDeclaration &&
node.left.kind !== "var"
) {
this.scopeManager.__nestForScope(node);
}
if (node.left.type === Syntax.VariableDeclaration) {
this.visit(node.left);
this.visitPattern(node.left.declarations[0].id, pattern => {
this.currentScope().__referencing(
pattern,
Reference.WRITE,
node.right,
null,
true,
true,
);
});
} else {
this.visitPattern(
node.left,
{ processRightHandNodes: true },
(pattern, info) => {
let maybeImplicitGlobal = null;
if (!this.currentScope().isStrict) {
maybeImplicitGlobal = {
pattern,
node,
};
}
this.referencingDefaultValue(
pattern,
info.assignments,
maybeImplicitGlobal,
false,
);
this.currentScope().__referencing(
pattern,
Reference.WRITE,
node.right,
maybeImplicitGlobal,
true,
false,
);
},
);
}
this.visit(node.right);
this.visit(node.body);
this.close(node);
}
visitVariableDeclaration(variableTargetScope, type, node, index) {
const decl = node.declarations[index];
const init = decl.init;
this.visitPattern(
decl.id,
{ processRightHandNodes: true },
(pattern, info) => {
variableTargetScope.__define(
pattern,
new Definition(type, pattern, decl, node, index, node.kind),
);
this.referencingDefaultValue(
pattern,
info.assignments,
null,
true,
);
if (init) {
this.currentScope().__referencing(
pattern,
Reference.WRITE,
init,
null,
!info.topLevel,
true,
);
}
},
);
}
AssignmentExpression(node) {
if (PatternVisitor.isPattern(node.left)) {
if (node.operator === "=") {
this.visitPattern(
node.left,
{ processRightHandNodes: true },
(pattern, info) => {
let maybeImplicitGlobal = null;
if (!this.currentScope().isStrict) {
maybeImplicitGlobal = {
pattern,
node,
};
}
this.referencingDefaultValue(
pattern,
info.assignments,
maybeImplicitGlobal,
false,
);
this.currentScope().__referencing(
pattern,
Reference.WRITE,
node.right,
maybeImplicitGlobal,
!info.topLevel,
false,
);
},
);
} else {
this.currentScope().__referencing(
node.left,
Reference.RW,
node.right,
);
}
} else {
this.visit(node.left);
}
this.visit(node.right);
}
CatchClause(node) {
this.scopeManager.__nestCatchScope(node);
this.visitPattern(
node.param,
{ processRightHandNodes: true },
(pattern, info) => {
this.currentScope().__define(
pattern,
new Definition(
Variable.CatchClause,
pattern,
node,
null,
null,
null,
),
);
this.referencingDefaultValue(
pattern,
info.assignments,
null,
true,
);
},
);
this.visit(node.body);
this.close(node);
}
Program(node) {
this.scopeManager.__nestGlobalScope(node);
if (this.scopeManager.isGlobalReturn()) {
// Force strictness of GlobalScope to false when using node.js scope.
this.currentScope().isStrict = false;
this.scopeManager.__nestFunctionScope(node, false);
}
if (this.scopeManager.__isES6() && this.scopeManager.isModule()) {
this.scopeManager.__nestModuleScope(node);
}
if (
this.scopeManager.isStrictModeSupported() &&
this.scopeManager.isImpliedStrict()
) {
this.currentScope().isStrict = true;
}
this.visitChildren(node);
this.close(node);
}
Identifier(node) {
this.currentScope().__referencing(node);
}
// eslint-disable-next-line class-methods-use-this -- Desired as instance method
PrivateIdentifier() {
// Do nothing.
}
UpdateExpression(node) {
if (PatternVisitor.isPattern(node.argument)) {
this.currentScope().__referencing(
node.argument,
Reference.RW,
null,
);
} else {
this.visitChildren(node);
}
}
MemberExpression(node) {
this.visit(node.object);
if (node.computed) {
this.visit(node.property);
}
}
Property(node) {
this.visitProperty(node);
}
PropertyDefinition(node) {
const { computed, key, value } = node;
if (computed) {
this.visit(key);
}
if (value) {
this.scopeManager.__nestClassFieldInitializerScope(value);
this.visit(value);
this.close(value);
}
}
StaticBlock(node) {
this.scopeManager.__nestClassStaticBlockScope(node);
this.visitChildren(node);
this.close(node);
}
MethodDefinition(node) {
this.visitProperty(node);
}
BreakStatement() {} // eslint-disable-line class-methods-use-this -- Desired as instance method
ContinueStatement() {} // eslint-disable-line class-methods-use-this -- Desired as instance method
LabeledStatement(node) {
this.visit(node.body);
}
ForStatement(node) {
// Create ForStatement declaration.
// NOTE: In ES6, ForStatement dynamically generates
// per iteration environment. However, escope is
// a static analyzer, we only generate one scope for ForStatement.
if (
node.init &&
node.init.type === Syntax.VariableDeclaration &&
node.init.kind !== "var"
) {
this.scopeManager.__nestForScope(node);
}
this.visitChildren(node);
this.close(node);
}
ClassExpression(node) {
this.visitClass(node);
}
ClassDeclaration(node) {
this.visitClass(node);
}
CallExpression(node) {
// Check this is direct call to eval
if (
!this.scopeManager.__ignoreEval() &&
node.callee.type === Syntax.Identifier &&
node.callee.name === "eval"
) {
// NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and
// let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment.
this.currentScope().variableScope.__detectEval();
}
this.visitChildren(node);
}
BlockStatement(node) {
if (this.scopeManager.__isES6()) {
this.scopeManager.__nestBlockScope(node);
}
this.visitChildren(node);
this.close(node);
}
ThisExpression() {
this.currentScope().variableScope.__detectThis();
}
WithStatement(node) {
this.visit(node.object);
// Then nest scope for WithStatement.
this.scopeManager.__nestWithScope(node);
this.visit(node.body);
this.close(node);
}
VariableDeclaration(node) {
const variableTargetScope =
node.kind === "var"
? this.currentScope().variableScope
: this.currentScope();
for (let i = 0, iz = node.declarations.length; i < iz; ++i) {
const decl = node.declarations[i];
this.visitVariableDeclaration(
variableTargetScope,
Variable.Variable,
node,
i,
);
if (decl.init) {
this.visit(decl.init);
}
}
}
// sec 13.11.8
SwitchStatement(node) {
this.visit(node.discriminant);
if (this.scopeManager.__isES6()) {
this.scopeManager.__nestSwitchScope(node);
}
for (let i = 0, iz = node.cases.length; i < iz; ++i) {
this.visit(node.cases[i]);
}
this.close(node);
}
FunctionDeclaration(node) {
this.visitFunction(node);
}
FunctionExpression(node) {
this.visitFunction(node);
}
ForOfStatement(node) {
this.visitForIn(node);
}
ForInStatement(node) {
this.visitForIn(node);
}
ArrowFunctionExpression(node) {
this.visitFunction(node);
}
ImportDeclaration(node) {
assert(
this.scopeManager.__isES6() && this.scopeManager.isModule(),
"ImportDeclaration should appear when the mode is ES6 and in the module context.",
);
const importer = new Importer(node, this);
importer.visit(node);
}
visitExportDeclaration(node) {
if (node.source) {
return;
}
if (node.declaration) {
this.visit(node.declaration);
return;
}
this.visitChildren(node);
}
// TODO: ExportDeclaration doesn't exist. for bc?
ExportDeclaration(node) {
this.visitExportDeclaration(node);
}
ExportAllDeclaration(node) {
this.visitExportDeclaration(node);
}
ExportDefaultDeclaration(node) {
this.visitExportDeclaration(node);
}
ExportNamedDeclaration(node) {
this.visitExportDeclaration(node);
}
ExportSpecifier(node) {
// TODO: `node.id` doesn't exist. for bc?
const local = node.id || node.local;
this.visit(local);
}
// eslint-disable-next-line class-methods-use-this -- Desired as instance method
MetaProperty() {
// do nothing.
}
JSXIdentifier(node) {
// Special case: "this" should not count as a reference
if (this.scopeManager.__isJSXEnabled() && node.name !== "this") {
this.currentScope().__referencing(node);
}
}
JSXMemberExpression(node) {
this.visit(node.object);
}
JSXElement(node) {
if (this.scopeManager.__isJSXEnabled()) {
this.visit(node.openingElement);
node.children.forEach(this.visit, this);
} else {
this.visitChildren(node);
}
}
JSXOpeningElement(node) {
if (this.scopeManager.__isJSXEnabled()) {
const nameNode = node.name;
const isComponentName =
nameNode.type === "JSXIdentifier" &&
nameNode.name[0].toUpperCase() === nameNode.name[0];
const isComponent =
isComponentName || nameNode.type === "JSXMemberExpression";
// we only want to visit JSXIdentifier nodes if they are capitalized
if (isComponent) {
this.visit(nameNode);
}
}
node.attributes.forEach(this.visit, this);
}
JSXAttribute(node) {
if (node.value) {
this.visit(node.value);
}
}
JSXExpressionContainer(node) {
this.visit(node.expression);
}
JSXNamespacedName(node) {
this.visit(node.namespace);
this.visit(node.name);
}
}
export default Referencer;
/* vim: set sw=4 ts=4 et tw=80 : */

View File

@@ -0,0 +1,7 @@
import type { UUIDTypes } from './types.js';
export declare function stringToBytes(str: string): Uint8Array;
export declare const DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
export declare const URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
type HashFunction = (bytes: Uint8Array) => Uint8Array;
export default function v35<TBuf extends Uint8Array = Uint8Array>(version: 0x30 | 0x50, hash: HashFunction, value: string | Uint8Array, namespace: UUIDTypes, buf?: TBuf, offset?: number): UUIDTypes<TBuf>;
export {};

View File

@@ -0,0 +1,223 @@
#!/usr/bin/env node
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// lib/npm/node-platform.ts
var fs = require("fs");
var os = require("os");
var path = require("path");
var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
var packageDarwin_arm64 = "@esbuild/darwin-arm64";
var packageDarwin_x64 = "@esbuild/darwin-x64";
var knownWindowsPackages = {
"win32 arm64 LE": "@esbuild/win32-arm64",
"win32 ia32 LE": "@esbuild/win32-ia32",
"win32 x64 LE": "@esbuild/win32-x64"
};
var knownUnixlikePackages = {
"aix ppc64 BE": "@esbuild/aix-ppc64",
"android arm64 LE": "@esbuild/android-arm64",
"darwin arm64 LE": "@esbuild/darwin-arm64",
"darwin x64 LE": "@esbuild/darwin-x64",
"freebsd arm64 LE": "@esbuild/freebsd-arm64",
"freebsd x64 LE": "@esbuild/freebsd-x64",
"linux arm LE": "@esbuild/linux-arm",
"linux arm64 LE": "@esbuild/linux-arm64",
"linux ia32 LE": "@esbuild/linux-ia32",
"linux mips64el LE": "@esbuild/linux-mips64el",
"linux ppc64 LE": "@esbuild/linux-ppc64",
"linux riscv64 LE": "@esbuild/linux-riscv64",
"linux s390x BE": "@esbuild/linux-s390x",
"linux x64 LE": "@esbuild/linux-x64",
"linux loong64 LE": "@esbuild/linux-loong64",
"netbsd arm64 LE": "@esbuild/netbsd-arm64",
"netbsd x64 LE": "@esbuild/netbsd-x64",
"openbsd arm64 LE": "@esbuild/openbsd-arm64",
"openbsd x64 LE": "@esbuild/openbsd-x64",
"sunos x64 LE": "@esbuild/sunos-x64"
};
var knownWebAssemblyFallbackPackages = {
"android arm LE": "@esbuild/android-arm",
"android x64 LE": "@esbuild/android-x64",
"openharmony arm64 LE": "@esbuild/openharmony-arm64"
};
function pkgAndSubpathForCurrentPlatform() {
let pkg;
let subpath;
let isWASM2 = false;
let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
if (platformKey in knownWindowsPackages) {
pkg = knownWindowsPackages[platformKey];
subpath = "esbuild.exe";
} else if (platformKey in knownUnixlikePackages) {
pkg = knownUnixlikePackages[platformKey];
subpath = "bin/esbuild";
} else if (platformKey in knownWebAssemblyFallbackPackages) {
pkg = knownWebAssemblyFallbackPackages[platformKey];
subpath = "bin/esbuild";
isWASM2 = true;
} else {
throw new Error(`Unsupported platform: ${platformKey}`);
}
return { pkg, subpath, isWASM: isWASM2 };
}
function pkgForSomeOtherPlatform() {
const libMainJS = require.resolve("esbuild");
const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS)));
if (path.basename(nodeModulesDirectory) === "node_modules") {
for (const unixKey in knownUnixlikePackages) {
try {
const pkg = knownUnixlikePackages[unixKey];
if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
} catch {
}
}
for (const windowsKey in knownWindowsPackages) {
try {
const pkg = knownWindowsPackages[windowsKey];
if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
} catch {
}
}
}
return null;
}
function downloadedBinPath(pkg, subpath) {
const esbuildLibDir = path.dirname(require.resolve("esbuild"));
return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
}
function generateBinPath() {
if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
if (!fs.existsSync(ESBUILD_BINARY_PATH)) {
console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
} else {
return { binPath: ESBUILD_BINARY_PATH, isWASM: false };
}
}
const { pkg, subpath, isWASM: isWASM2 } = pkgAndSubpathForCurrentPlatform();
let binPath2;
try {
binPath2 = require.resolve(`${pkg}/${subpath}`);
} catch (e) {
binPath2 = downloadedBinPath(pkg, subpath);
if (!fs.existsSync(binPath2)) {
try {
require.resolve(pkg);
} catch {
const otherPkg = pkgForSomeOtherPlatform();
if (otherPkg) {
let suggestions = `
Specifically the "${otherPkg}" package is present but this platform
needs the "${pkg}" package instead. People often get into this
situation by installing esbuild on Windows or macOS and copying "node_modules"
into a Docker image that runs Linux, or by copying "node_modules" between
Windows and WSL environments.
If you are installing with npm, you can try not copying the "node_modules"
directory when you copy the files over, and running "npm ci" or "npm install"
on the destination platform after the copy. Or you could consider using yarn
instead of npm which has built-in support for installing a package on multiple
platforms simultaneously.
If you are installing with yarn, you can try listing both this platform and the
other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
Keep in mind that this means multiple copies of esbuild will be present.
`;
if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) {
suggestions = `
Specifically the "${otherPkg}" package is present but this platform
needs the "${pkg}" package instead. People often get into this
situation by installing esbuild with npm running inside of Rosetta 2 and then
trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
2 is Apple's on-the-fly x86_64-to-arm64 translation service).
If you are installing with npm, you can try ensuring that both npm and node are
not running under Rosetta 2 and then reinstalling esbuild. This likely involves
changing how you installed npm and/or node. For example, installing node with
the universal installer here should work: https://nodejs.org/en/download/. Or
you could consider using yarn instead of npm which has built-in support for
installing a package on multiple platforms simultaneously.
If you are installing with yarn, you can try listing both "arm64" and "x64"
in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
Keep in mind that this means multiple copies of esbuild will be present.
`;
}
throw new Error(`
You installed esbuild for another platform than the one you're currently using.
This won't work because esbuild is written with native code and needs to
install a platform-specific binary executable.
${suggestions}
Another alternative is to use the "esbuild-wasm" package instead, which works
the same way on all platforms. But it comes with a heavy performance cost and
can sometimes be 10x slower than the "esbuild" package, so you may also not
want to do that.
`);
}
throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
If you are installing esbuild with npm, make sure that you don't specify the
"--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
of "package.json" is used by esbuild to install the correct binary executable
for your current platform.`);
}
throw e;
}
}
if (/\.zip\//.test(binPath2)) {
let pnpapi;
try {
pnpapi = require("pnpapi");
} catch (e) {
}
if (pnpapi) {
const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
const binTargetPath = path.join(
root,
"node_modules",
".cache",
"esbuild",
`pnpapi-${pkg.replace("/", "-")}-${"0.28.2"}-${path.basename(subpath)}`
);
if (!fs.existsSync(binTargetPath)) {
fs.mkdirSync(path.dirname(binTargetPath), { recursive: true });
fs.copyFileSync(binPath2, binTargetPath);
fs.chmodSync(binTargetPath, 493);
}
return { binPath: binTargetPath, isWASM: isWASM2 };
}
}
return { binPath: binPath2, isWASM: isWASM2 };
}
// lib/npm/node-shim.ts
var { binPath, isWASM } = generateBinPath();
if (isWASM) {
require("child_process").execFileSync("node", [binPath].concat(process.argv.slice(2)), { stdio: "inherit" });
} else {
require("child_process").execFileSync(binPath, process.argv.slice(2), { stdio: "inherit" });
}

View File

@@ -0,0 +1,17 @@
/**
* Internal assertion helpers.
* @module
* @deprecated
*/
import { abytes as ab, aexists as ae, anumber as an, aoutput as ao, type IHash as H } from './utils.ts';
/** @deprecated Use import from `noble/hashes/utils` module */
export declare const abytes: typeof ab;
/** @deprecated Use import from `noble/hashes/utils` module */
export declare const aexists: typeof ae;
/** @deprecated Use import from `noble/hashes/utils` module */
export declare const anumber: typeof an;
/** @deprecated Use import from `noble/hashes/utils` module */
export declare const aoutput: typeof ao;
/** @deprecated Use import from `noble/hashes/utils` module */
export type Hash = H;
//# sourceMappingURL=_assert.d.ts.map

View File

@@ -0,0 +1,42 @@
{
"name": "@humanfs/types",
"version": "0.15.0",
"description": "The TypeScript types for the hfs project.",
"type": "module",
"types": "src/hfs-types.ts",
"exports": {
".": {
"types": "./src/hfs-types.ts"
},
"./package.json": "./package.json"
},
"scripts": {
"build": "tsc",
"prepare": "npm run build"
},
"repository": {
"type": "git",
"url": "git+https://github.com/humanwhocodes/humanfs.git"
},
"publishConfig": {
"access": "public"
},
"keywords": [
"filesystem",
"fs",
"hfs",
"files"
],
"author": "Nicholas C. Zakas",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/humanwhocodes/humanfs/issues"
},
"homepage": "https://github.com/humanwhocodes/humanfs#readme",
"engines": {
"node": ">=18.18.0"
},
"devDependencies": {
"typescript": "^5.2.2"
}
}

View File

@@ -0,0 +1,120 @@
import * as util from "../core/util.js";
const error = () => {
const Sizable = {
string: { unit: "символа", verb: "да съдържа" },
file: { unit: "байта", verb: "да съдържа" },
array: { unit: "елемента", verb: "да съдържа" },
set: { unit: "елемента", verb: "да съдържа" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "вход",
email: "имейл адрес",
url: "URL",
emoji: "емоджи",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "ISO време",
date: "ISO дата",
time: "ISO време",
duration: "ISO продължителност",
ipv4: "IPv4 адрес",
ipv6: "IPv6 адрес",
cidrv4: "IPv4 диапазон",
cidrv6: "IPv6 диапазон",
base64: "base64-кодиран низ",
base64url: "base64url-кодиран низ",
json_string: "JSON низ",
e164: "E.164 номер",
jwt: "JWT",
template_literal: "вход",
};
const TypeDictionary = {
nan: "NaN",
number: "число",
array: "масив",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
if (/^[A-Z]/.test(issue.expected)) {
return `Невалиден вход: очакван instanceof ${issue.expected}, получен ${received}`;
}
return `Невалиден вход: очакван ${expected}, получен ${received}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Невалиден вход: очакван ${util.stringifyPrimitive(issue.values[0])}`;
return `Невалидна опция: очаквано едно от ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Твърде голямо: очаква се ${issue.origin ?? "стойност"} да съдържа ${adj}${issue.maximum.toString()} ${sizing.unit ?? "елемента"}`;
return `Твърде голямо: очаква се ${issue.origin ?? "стойност"} да бъде ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Твърде малко: очаква се ${issue.origin} да съдържа ${adj}${issue.minimum.toString()} ${sizing.unit}`;
}
return `Твърде малко: очаква се ${issue.origin} да бъде ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with") {
return `Невалиден низ: трябва да започва с "${_issue.prefix}"`;
}
if (_issue.format === "ends_with")
return `Невалиден низ: трябва да завършва с "${_issue.suffix}"`;
if (_issue.format === "includes")
return `Невалиден низ: трябва да включва "${_issue.includes}"`;
if (_issue.format === "regex")
return `Невалиден низ: трябва да съвпада с ${_issue.pattern}`;
let invalid_adj = "Невалиден";
if (_issue.format === "emoji")
invalid_adj = "Невалидно";
if (_issue.format === "datetime")
invalid_adj = "Невалидно";
if (_issue.format === "date")
invalid_adj = "Невалидна";
if (_issue.format === "time")
invalid_adj = "Невалидно";
if (_issue.format === "duration")
invalid_adj = "Невалидна";
return `${invalid_adj} ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Невалидно число: трябва да бъде кратно на ${issue.divisor}`;
case "unrecognized_keys":
return `Неразпознат${issue.keys.length > 1 ? "и" : ""} ключ${issue.keys.length > 1 ? "ове" : ""}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Невалиден ключ в ${issue.origin}`;
case "invalid_union":
return "Невалиден вход";
case "invalid_element":
return `Невалидна стойност в ${issue.origin}`;
default:
return `Невалиден вход`;
}
};
};
export default function () {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1,21 @@
declare const KNOWN_ASSET_TYPES: string[];
declare const KNOWN_ASSET_RE: RegExp;
declare const CSS_LANGS_RE: RegExp;
/**
* Prefix for resolved Ids that are not valid browser import specifiers
*/
declare const VALID_ID_PREFIX = "/@id/";
/**
* Plugins that use 'virtual modules' (e.g. for helper functions), prefix the
* module ID with `\0`, a convention from the rollup ecosystem.
* This prevents other plugins from trying to process the id (like node resolution),
* and core features like sourcemaps can use this info to differentiate between
* virtual modules and regular files.
* `\0` is not a permitted char in import URLs so we have to replace them during
* import analysis. The id will be decoded back before entering the plugins pipeline.
* These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual
* modules in the browser end up encoded as `/@id/__x00__{id}`
*/
declare const NULL_BYTE_PLACEHOLDER = "__x00__";
export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES, NULL_BYTE_PLACEHOLDER, VALID_ID_PREFIX };

View File

@@ -0,0 +1,674 @@
import { globalConfig } from "./core.js";
// functions
export function assertEqual(val) {
return val;
}
export function assertNotEqual(val) {
return val;
}
export function assertIs(_arg) { }
export function assertNever(_x) {
throw new Error("Unexpected value in exhaustive check");
}
export function assert(_) { }
export function getEnumValues(entries) {
const numericValues = Object.values(entries).filter((v) => typeof v === "number");
const values = Object.entries(entries)
.filter(([k, _]) => numericValues.indexOf(+k) === -1)
.map(([_, v]) => v);
return values;
}
export function joinValues(array, separator = "|") {
return array.map((val) => stringifyPrimitive(val)).join(separator);
}
export function jsonStringifyReplacer(_, value) {
if (typeof value === "bigint")
return value.toString();
return value;
}
export function cached(getter) {
const set = false;
return {
get value() {
if (!set) {
const value = getter();
Object.defineProperty(this, "value", { value });
return value;
}
throw new Error("cached value already set");
},
};
}
export function nullish(input) {
return input === null || input === undefined;
}
export function cleanRegex(source) {
const start = source.startsWith("^") ? 1 : 0;
const end = source.endsWith("$") ? source.length - 1 : source.length;
return source.slice(start, end);
}
export function floatSafeRemainder(val, step) {
const ratio = val / step;
const roundedRatio = Math.round(ratio);
// Use a relative epsilon scaled to the magnitude of the result
const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);
if (Math.abs(ratio - roundedRatio) < tolerance)
return 0;
return ratio - roundedRatio;
}
const EVALUATING = /* @__PURE__*/ Symbol("evaluating");
export function defineLazy(object, key, getter) {
let value = undefined;
Object.defineProperty(object, key, {
get() {
if (value === EVALUATING) {
// Circular reference detected, return undefined to break the cycle
return undefined;
}
if (value === undefined) {
value = EVALUATING;
value = getter();
}
return value;
},
set(v) {
Object.defineProperty(object, key, {
value: v,
// configurable: true,
});
// object[key] = v;
},
configurable: true,
});
}
export function objectClone(obj) {
return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
}
export function assignProp(target, prop, value) {
Object.defineProperty(target, prop, {
value,
writable: true,
enumerable: true,
configurable: true,
});
}
export function mergeDefs(...defs) {
const mergedDescriptors = {};
for (const def of defs) {
const descriptors = Object.getOwnPropertyDescriptors(def);
Object.assign(mergedDescriptors, descriptors);
}
return Object.defineProperties({}, mergedDescriptors);
}
export function cloneDef(schema) {
return mergeDefs(schema._zod.def);
}
export function getElementAtPath(obj, path) {
if (!path)
return obj;
return path.reduce((acc, key) => acc?.[key], obj);
}
export function promiseAllObject(promisesObj) {
const keys = Object.keys(promisesObj);
const promises = keys.map((key) => promisesObj[key]);
return Promise.all(promises).then((results) => {
const resolvedObj = {};
for (let i = 0; i < keys.length; i++) {
resolvedObj[keys[i]] = results[i];
}
return resolvedObj;
});
}
export function randomString(length = 10) {
const chars = "abcdefghijklmnopqrstuvwxyz";
let str = "";
for (let i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
export function esc(str) {
return JSON.stringify(str);
}
export function slugify(input) {
return input
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, "")
.replace(/[\s_-]+/g, "-")
.replace(/^-+|-+$/g, "");
}
export const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { });
export function isObject(data) {
return typeof data === "object" && data !== null && !Array.isArray(data);
}
export const allowsEval = /* @__PURE__*/ cached(() => {
// Skip the probe under `jitless`: strict CSPs report the caught `new Function`
// as a `securitypolicyviolation` even though the throw is swallowed.
if (globalConfig.jitless) {
return false;
}
// @ts-ignore
if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
return false;
}
try {
const F = Function;
new F("");
return true;
}
catch (_) {
return false;
}
});
export function isPlainObject(o) {
if (isObject(o) === false)
return false;
// modified constructor
const ctor = o.constructor;
if (ctor === undefined)
return true;
if (typeof ctor !== "function")
return true;
// modified prototype
const prot = ctor.prototype;
if (isObject(prot) === false)
return false;
// ctor doesn't have static `isPrototypeOf`
if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
return false;
}
return true;
}
export function shallowClone(o) {
if (isPlainObject(o))
return { ...o };
if (Array.isArray(o))
return [...o];
if (o instanceof Map)
return new Map(o);
if (o instanceof Set)
return new Set(o);
return o;
}
export function numKeys(data) {
let keyCount = 0;
for (const key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
keyCount++;
}
}
return keyCount;
}
export const getParsedType = (data) => {
const t = typeof data;
switch (t) {
case "undefined":
return "undefined";
case "string":
return "string";
case "number":
return Number.isNaN(data) ? "nan" : "number";
case "boolean":
return "boolean";
case "function":
return "function";
case "bigint":
return "bigint";
case "symbol":
return "symbol";
case "object":
if (Array.isArray(data)) {
return "array";
}
if (data === null) {
return "null";
}
if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
return "promise";
}
if (typeof Map !== "undefined" && data instanceof Map) {
return "map";
}
if (typeof Set !== "undefined" && data instanceof Set) {
return "set";
}
if (typeof Date !== "undefined" && data instanceof Date) {
return "date";
}
// @ts-ignore
if (typeof File !== "undefined" && data instanceof File) {
return "file";
}
return "object";
default:
throw new Error(`Unknown data type: ${t}`);
}
};
export const propertyKeyTypes = /* @__PURE__*/ new Set(["string", "number", "symbol"]);
export const primitiveTypes = /* @__PURE__*/ new Set([
"string",
"number",
"bigint",
"boolean",
"symbol",
"undefined",
]);
export function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
// zod-specific utils
export function clone(inst, def, params) {
const cl = new inst._zod.constr(def ?? inst._zod.def);
if (!def || params?.parent)
cl._zod.parent = inst;
return cl;
}
export function normalizeParams(_params) {
const params = _params;
if (!params)
return {};
if (typeof params === "string")
return { error: () => params };
if (params?.message !== undefined) {
if (params?.error !== undefined)
throw new Error("Cannot specify both `message` and `error` params");
params.error = params.message;
}
delete params.message;
if (typeof params.error === "string")
return { ...params, error: () => params.error };
return params;
}
export function createTransparentProxy(getter) {
let target;
return new Proxy({}, {
get(_, prop, receiver) {
target ?? (target = getter());
return Reflect.get(target, prop, receiver);
},
set(_, prop, value, receiver) {
target ?? (target = getter());
return Reflect.set(target, prop, value, receiver);
},
has(_, prop) {
target ?? (target = getter());
return Reflect.has(target, prop);
},
deleteProperty(_, prop) {
target ?? (target = getter());
return Reflect.deleteProperty(target, prop);
},
ownKeys(_) {
target ?? (target = getter());
return Reflect.ownKeys(target);
},
getOwnPropertyDescriptor(_, prop) {
target ?? (target = getter());
return Reflect.getOwnPropertyDescriptor(target, prop);
},
defineProperty(_, prop, descriptor) {
target ?? (target = getter());
return Reflect.defineProperty(target, prop, descriptor);
},
});
}
export function stringifyPrimitive(value) {
if (typeof value === "bigint")
return value.toString() + "n";
if (typeof value === "string")
return `"${value}"`;
return `${value}`;
}
export function optionalKeys(shape) {
return Object.keys(shape).filter((k) => {
return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
});
}
export const NUMBER_FORMAT_RANGES = {
safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
int32: [-2147483648, 2147483647],
uint32: [0, 4294967295],
float32: [-3.4028234663852886e38, 3.4028234663852886e38],
float64: [-Number.MAX_VALUE, Number.MAX_VALUE],
};
export const BIGINT_FORMAT_RANGES = {
int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")],
uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")],
};
export function pick(schema, mask) {
const currDef = schema._zod.def;
const checks = currDef.checks;
const hasChecks = checks && checks.length > 0;
if (hasChecks) {
throw new Error(".pick() cannot be used on object schemas containing refinements");
}
const def = mergeDefs(schema._zod.def, {
get shape() {
const newShape = {};
for (const key in mask) {
if (!(key in currDef.shape)) {
throw new Error(`Unrecognized key: "${key}"`);
}
if (!mask[key])
continue;
newShape[key] = currDef.shape[key];
}
assignProp(this, "shape", newShape); // self-caching
return newShape;
},
checks: [],
});
return clone(schema, def);
}
export function omit(schema, mask) {
const currDef = schema._zod.def;
const checks = currDef.checks;
const hasChecks = checks && checks.length > 0;
if (hasChecks) {
throw new Error(".omit() cannot be used on object schemas containing refinements");
}
const def = mergeDefs(schema._zod.def, {
get shape() {
const newShape = { ...schema._zod.def.shape };
for (const key in mask) {
if (!(key in currDef.shape)) {
throw new Error(`Unrecognized key: "${key}"`);
}
if (!mask[key])
continue;
delete newShape[key];
}
assignProp(this, "shape", newShape); // self-caching
return newShape;
},
checks: [],
});
return clone(schema, def);
}
export function extend(schema, shape) {
if (!isPlainObject(shape)) {
throw new Error("Invalid input to extend: expected a plain object");
}
const checks = schema._zod.def.checks;
const hasChecks = checks && checks.length > 0;
if (hasChecks) {
// Only throw if new shape overlaps with existing shape
// Use getOwnPropertyDescriptor to check key existence without accessing values
const existingShape = schema._zod.def.shape;
for (const key in shape) {
if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {
throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
}
}
}
const def = mergeDefs(schema._zod.def, {
get shape() {
const _shape = { ...schema._zod.def.shape, ...shape };
assignProp(this, "shape", _shape); // self-caching
return _shape;
},
});
return clone(schema, def);
}
export function safeExtend(schema, shape) {
if (!isPlainObject(shape)) {
throw new Error("Invalid input to safeExtend: expected a plain object");
}
const def = mergeDefs(schema._zod.def, {
get shape() {
const _shape = { ...schema._zod.def.shape, ...shape };
assignProp(this, "shape", _shape); // self-caching
return _shape;
},
});
return clone(schema, def);
}
export function merge(a, b) {
if (a._zod.def.checks?.length) {
throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
}
const def = mergeDefs(a._zod.def, {
get shape() {
const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
assignProp(this, "shape", _shape); // self-caching
return _shape;
},
get catchall() {
return b._zod.def.catchall;
},
checks: b._zod.def.checks ?? [],
});
return clone(a, def);
}
export function partial(Class, schema, mask) {
const currDef = schema._zod.def;
const checks = currDef.checks;
const hasChecks = checks && checks.length > 0;
if (hasChecks) {
throw new Error(".partial() cannot be used on object schemas containing refinements");
}
const def = mergeDefs(schema._zod.def, {
get shape() {
const oldShape = schema._zod.def.shape;
const shape = { ...oldShape };
if (mask) {
for (const key in mask) {
if (!(key in oldShape)) {
throw new Error(`Unrecognized key: "${key}"`);
}
if (!mask[key])
continue;
// if (oldShape[key]!._zod.optin === "optional") continue;
shape[key] = Class
? new Class({
type: "optional",
innerType: oldShape[key],
})
: oldShape[key];
}
}
else {
for (const key in oldShape) {
// if (oldShape[key]!._zod.optin === "optional") continue;
shape[key] = Class
? new Class({
type: "optional",
innerType: oldShape[key],
})
: oldShape[key];
}
}
assignProp(this, "shape", shape); // self-caching
return shape;
},
checks: [],
});
return clone(schema, def);
}
export function required(Class, schema, mask) {
const def = mergeDefs(schema._zod.def, {
get shape() {
const oldShape = schema._zod.def.shape;
const shape = { ...oldShape };
if (mask) {
for (const key in mask) {
if (!(key in shape)) {
throw new Error(`Unrecognized key: "${key}"`);
}
if (!mask[key])
continue;
// overwrite with non-optional
shape[key] = new Class({
type: "nonoptional",
innerType: oldShape[key],
});
}
}
else {
for (const key in oldShape) {
// overwrite with non-optional
shape[key] = new Class({
type: "nonoptional",
innerType: oldShape[key],
});
}
}
assignProp(this, "shape", shape); // self-caching
return shape;
},
});
return clone(schema, def);
}
// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom
export function aborted(x, startIndex = 0) {
if (x.aborted === true)
return true;
for (let i = startIndex; i < x.issues.length; i++) {
if (x.issues[i]?.continue !== true) {
return true;
}
}
return false;
}
// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined).
// Used to respect `abort: true` in .refine() even for checks that have a `when` function.
export function explicitlyAborted(x, startIndex = 0) {
if (x.aborted === true)
return true;
for (let i = startIndex; i < x.issues.length; i++) {
if (x.issues[i]?.continue === false) {
return true;
}
}
return false;
}
export function prefixIssues(path, issues) {
return issues.map((iss) => {
var _a;
(_a = iss).path ?? (_a.path = []);
iss.path.unshift(path);
return iss;
});
}
export function unwrapMessage(message) {
return typeof message === "string" ? message : message?.message;
}
export function finalizeIssue(iss, ctx, config) {
const message = iss.message
? iss.message
: (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??
unwrapMessage(ctx?.error?.(iss)) ??
unwrapMessage(config.customError?.(iss)) ??
unwrapMessage(config.localeError?.(iss)) ??
"Invalid input");
const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;
rest.path ?? (rest.path = []);
rest.message = message;
if (ctx?.reportInput) {
rest.input = _input;
}
return rest;
}
export function getSizableOrigin(input) {
if (input instanceof Set)
return "set";
if (input instanceof Map)
return "map";
// @ts-ignore
if (input instanceof File)
return "file";
return "unknown";
}
export function getLengthableOrigin(input) {
if (Array.isArray(input))
return "array";
if (typeof input === "string")
return "string";
return "unknown";
}
export function parsedType(data) {
const t = typeof data;
switch (t) {
case "number": {
return Number.isNaN(data) ? "nan" : "number";
}
case "object": {
if (data === null) {
return "null";
}
if (Array.isArray(data)) {
return "array";
}
const obj = data;
if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) {
return obj.constructor.name;
}
}
}
return t;
}
export function issue(...args) {
const [iss, input, inst] = args;
if (typeof iss === "string") {
return {
message: iss,
code: "custom",
input,
inst,
};
}
return { ...iss };
}
export function cleanEnum(obj) {
return Object.entries(obj)
.filter(([k, _]) => {
// return true if NaN, meaning it's not a number, thus a string key
return Number.isNaN(Number.parseInt(k, 10));
})
.map((el) => el[1]);
}
// Codec utility functions
export function base64ToUint8Array(base64) {
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes;
}
export function uint8ArrayToBase64(bytes) {
let binaryString = "";
for (let i = 0; i < bytes.length; i++) {
binaryString += String.fromCharCode(bytes[i]);
}
return btoa(binaryString);
}
export function base64urlToUint8Array(base64url) {
const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/");
const padding = "=".repeat((4 - (base64.length % 4)) % 4);
return base64ToUint8Array(base64 + padding);
}
export function uint8ArrayToBase64url(bytes) {
return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
export function hexToUint8Array(hex) {
const cleanHex = hex.replace(/^0x/, "");
if (cleanHex.length % 2 !== 0) {
throw new Error("Invalid hex string length");
}
const bytes = new Uint8Array(cleanHex.length / 2);
for (let i = 0; i < cleanHex.length; i += 2) {
bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);
}
return bytes;
}
export function uint8ArrayToHex(bytes) {
return Array.from(bytes)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
// instanceof
export class Class {
constructor(..._args) { }
}

View File

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

View File

@@ -0,0 +1,617 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const tsutils = __importStar(require("ts-api-utils"));
const ts = __importStar(require("typescript"));
const util_1 = require("../util");
const getWrappedCode_1 = require("../util/getWrappedCode");
const isMemberAccessLike = (0, util_1.isNodeOfTypes)([
utils_1.AST_NODE_TYPES.ChainExpression,
utils_1.AST_NODE_TYPES.Identifier,
utils_1.AST_NODE_TYPES.MemberExpression,
]);
const isNullLiteralOrUndefinedIdentifier = (node) => (0, util_1.isNullLiteral)(node) || (0, util_1.isUndefinedIdentifier)(node);
const isNodeNullishComparison = (node) => isNullLiteralOrUndefinedIdentifier(node.left) &&
isNullLiteralOrUndefinedIdentifier(node.right);
exports.default = (0, util_1.createRule)({
name: 'prefer-nullish-coalescing',
meta: {
type: 'suggestion',
docs: {
description: 'Enforce using the nullish coalescing operator instead of logical assignments or chaining',
recommended: 'stylistic',
requiresTypeChecking: true,
},
hasSuggestions: true,
messages: {
noStrictNullCheck: 'This rule requires the `strictNullChecks` compiler option to be turned on to function correctly.',
preferNullishOverAssignment: 'Prefer using nullish coalescing operator (`??{{ equals }}`) instead of an assignment expression, as it is simpler to read.',
preferNullishOverOr: 'Prefer using nullish coalescing operator (`??{{ equals }}`) instead of a logical {{ description }} (`||{{ equals }}`), as it is a safer operator.',
preferNullishOverTernary: 'Prefer using nullish coalescing operator (`??{{ equals }}`) instead of a ternary expression, as it is simpler to read.',
suggestNullish: 'Fix to nullish coalescing operator (`??{{ equals }}`).',
},
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: {
type: 'boolean',
description: 'Unless this is set to `true`, the rule will error on every file whose `tsconfig.json` does _not_ have the `strictNullChecks` compiler option (or `strict`) set to `true`.',
},
ignoreBooleanCoercion: {
type: 'boolean',
description: 'Whether to ignore arguments to the `Boolean` constructor',
},
ignoreConditionalTests: {
type: 'boolean',
description: 'Whether to ignore cases that are located within a conditional test.',
},
ignoreIfStatements: {
type: 'boolean',
description: 'Whether to ignore any if statements that could be simplified by using the nullish coalescing operator.',
},
ignoreMixedLogicalExpressions: {
type: 'boolean',
description: 'Whether to ignore any logical or expressions that are part of a mixed logical expression (with `&&`).',
},
ignorePrimitives: {
description: 'Whether to ignore all (`true`) or some (an object with properties) primitive types.',
oneOf: [
{
type: 'object',
additionalProperties: false,
description: 'Which primitives types may be ignored.',
properties: {
bigint: {
type: 'boolean',
description: 'Ignore bigint primitive types.',
},
boolean: {
type: 'boolean',
description: 'Ignore boolean primitive types.',
},
number: {
type: 'boolean',
description: 'Ignore number primitive types.',
},
string: {
type: 'boolean',
description: 'Ignore string primitive types.',
},
},
},
{
type: 'boolean',
description: 'Ignore all primitive types.',
enum: [true],
},
],
},
ignoreTernaryTests: {
type: 'boolean',
description: 'Whether to ignore any ternary expressions that could be simplified by using the nullish coalescing operator.',
},
},
},
],
},
defaultOptions: [
{
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: false,
ignoreBooleanCoercion: false,
ignoreConditionalTests: true,
ignoreIfStatements: false,
ignoreMixedLogicalExpressions: false,
ignorePrimitives: {
bigint: false,
boolean: false,
number: false,
string: false,
},
ignoreTernaryTests: false,
},
],
create(context, [{ allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing, ignoreBooleanCoercion, ignoreConditionalTests, ignoreIfStatements, ignoreMixedLogicalExpressions, ignorePrimitives, ignoreTernaryTests, },]) {
const parserServices = (0, util_1.getParserServices)(context);
const compilerOptions = parserServices.program.getCompilerOptions();
const isStrictNullChecks = tsutils.isStrictCompilerOptionEnabled(compilerOptions, 'strictNullChecks');
if (!isStrictNullChecks &&
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing !== true) {
context.report({
loc: {
start: { column: 0, line: 0 },
end: { column: 0, line: 0 },
},
messageId: 'noStrictNullCheck',
});
}
/**
* Checks whether a type tested for truthiness is eligible for conversion to
* a nullishness check, taking into account the rule's configuration.
*/
function isTypeEligibleForPreferNullish(type) {
if (!(0, util_1.isNullableType)(type)) {
return false;
}
const ignorableFlags = [
/* eslint-disable @typescript-eslint/no-non-null-assertion */
(ignorePrimitives === true || ignorePrimitives.bigint) &&
ts.TypeFlags.BigIntLike,
(ignorePrimitives === true || ignorePrimitives.boolean) &&
ts.TypeFlags.BooleanLike,
(ignorePrimitives === true || ignorePrimitives.number) &&
ts.TypeFlags.NumberLike,
(ignorePrimitives === true || ignorePrimitives.string) &&
ts.TypeFlags.StringLike,
/* eslint-enable @typescript-eslint/no-non-null-assertion */
]
.filter((flag) => typeof flag === 'number')
.reduce((previous, flag) => previous | flag, 0);
if (ignorableFlags === 0) {
// any types are eligible for conversion.
return true;
}
// if the type is `any` or `unknown` we can't make any assumptions
// about the value, so it could be any primitive, even though the flags
// won't be set.
//
// technically, this is true of `void` as well, however, it's a TS error
// to test `void` for truthiness, so we don't need to bother checking for
// it in valid code.
if (tsutils.isTypeFlagSet(type, ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
return false;
}
if (tsutils
.typeConstituents(type)
.some(t => tsutils
.intersectionConstituents(t)
.some(t => tsutils.isTypeFlagSet(t, ignorableFlags)))) {
return false;
}
return true;
}
/**
* Determines whether a control flow construct that uses the truthiness of
* a test expression is eligible for conversion to the nullish coalescing
* operator, taking into account (both dependent on the rule's configuration):
* 1. Whether the construct is in a permitted syntactic context
* 2. Whether the type of the test expression is deemed eligible for
* conversion
*
* @param node The overall node to be converted (e.g. `a || b` or `a ? a : b`)
* @param testNode The node being tested (i.e. `a`)
*/
function isTruthinessCheckEligibleForPreferNullish({ node, testNode, }) {
if (ignoreConditionalTests === true && (0, util_1.isConditionalTest)(node)) {
return false;
}
if (ignoreBooleanCoercion === true &&
isBooleanConstructorContext(node, context) &&
!(node.type === utils_1.AST_NODE_TYPES.ConditionalExpression &&
node.parent.type === utils_1.AST_NODE_TYPES.CallExpression)) {
return false;
}
const testType = parserServices.getTypeAtLocation(testNode);
if (!isTypeEligibleForPreferNullish(testType)) {
return false;
}
return true;
}
function checkAndFixWithPreferNullishOverOr(node, description, equals) {
if (!isTruthinessCheckEligibleForPreferNullish({
node,
testNode: node.left,
})) {
return;
}
if (ignoreMixedLogicalExpressions === true &&
isMixedLogicalExpression(node)) {
return;
}
const barBarOperator = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(node.left, token => token.type === utils_1.AST_TOKEN_TYPES.Punctuator &&
token.value === node.operator), util_1.NullThrowsReasons.MissingToken('operator', node.type));
function* fix(fixer) {
if ((0, util_1.isLogicalOrOperator)(node.parent)) {
// '&&' and '??' operations cannot be mixed without parentheses (e.g. a && b ?? c)
if (node.left.type === utils_1.AST_NODE_TYPES.LogicalExpression &&
!(0, util_1.isLogicalOrOperator)(node.left.left)) {
yield fixer.insertTextBefore(node.left.right, '(');
}
else {
yield fixer.insertTextBefore(node.left, '(');
}
yield fixer.insertTextAfter(node.right, ')');
}
yield fixer.replaceText(barBarOperator, node.operator.replace('||', '??'));
}
context.report({
node: barBarOperator,
messageId: 'preferNullishOverOr',
data: { description, equals },
suggest: [
{
messageId: 'suggestNullish',
data: { equals },
fix,
},
],
});
}
function getNullishCoalescingParams(node, nonNullishNode, nodesInsideTestExpression, operator) {
let nullishCoalescingLeftNode;
let hasTruthinessCheck = false;
let hasNullCheckWithoutTruthinessCheck = false;
let hasUndefinedCheckWithoutTruthinessCheck = false;
if (!nodesInsideTestExpression.length) {
hasTruthinessCheck = true;
nullishCoalescingLeftNode =
node.test.type === utils_1.AST_NODE_TYPES.UnaryExpression
? node.test.argument
: node.test;
if (!areNodesSimilarMemberAccess(nullishCoalescingLeftNode, nonNullishNode)) {
return { isFixable: false };
}
}
else {
// we check that the test only contains null, undefined and the identifier
for (const testNode of nodesInsideTestExpression) {
if ((0, util_1.isNullLiteral)(testNode)) {
hasNullCheckWithoutTruthinessCheck = true;
}
else if ((0, util_1.isUndefinedIdentifier)(testNode)) {
hasUndefinedCheckWithoutTruthinessCheck = true;
}
else if (areNodesSimilarMemberAccess(testNode, nonNullishNode)) {
// Only consider the first expression in a multi-part nullish check,
// as subsequent expressions might not require all the optional chaining operators.
// For example: a?.b?.c !== undefined && a.b.c !== null ? a.b.c : 'foo';
// This works because `node.test` is always evaluated first in the loop
// and has the same or more necessary optional chaining operators
// than `node.alternate` or `node.consequent`.
nullishCoalescingLeftNode ??= testNode;
}
else {
return { isFixable: false };
}
}
}
if (!nullishCoalescingLeftNode) {
return { isFixable: false };
}
const isFixable = (() => {
if (hasTruthinessCheck) {
return isTruthinessCheckEligibleForPreferNullish({
node,
testNode: nullishCoalescingLeftNode,
});
}
// it is fixable if we check for both null and undefined, or not if neither
if (hasUndefinedCheckWithoutTruthinessCheck ===
hasNullCheckWithoutTruthinessCheck) {
return hasUndefinedCheckWithoutTruthinessCheck;
}
// it is fixable if we loosely check for either null or undefined
if (['==', '!='].includes(operator)) {
return true;
}
const type = parserServices.getTypeAtLocation(nullishCoalescingLeftNode);
const flags = (0, util_1.getTypeFlags)(type);
if (flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
return false;
}
const hasNullType = (flags & ts.TypeFlags.Null) !== 0;
// it is fixable if we check for undefined and the type is not nullable
if (hasUndefinedCheckWithoutTruthinessCheck && !hasNullType) {
return true;
}
const hasUndefinedType = (flags & ts.TypeFlags.Undefined) !== 0;
// it is fixable if we check for null and the type can't be undefined
return hasNullCheckWithoutTruthinessCheck && !hasUndefinedType;
})();
return isFixable
? { isFixable: true, nullishCoalescingLeftNode }
: { isFixable: false };
}
return {
'AssignmentExpression[operator = "||="]'(node) {
checkAndFixWithPreferNullishOverOr(node, 'assignment', '=');
},
ConditionalExpression(node) {
if (ignoreTernaryTests) {
return;
}
const { nodesInsideTestExpression, operator } = getOperatorAndNodesInsideTestExpression(node);
if (operator == null) {
return;
}
const { nonNullishBranch, nullishBranch } = getBranchNodes(node, operator);
const nullishCoalescingParams = getNullishCoalescingParams(node, nonNullishBranch, nodesInsideTestExpression, operator);
if (nullishCoalescingParams.isFixable) {
context.report({
node,
messageId: 'preferNullishOverTernary',
// TODO: also account for = in the ternary clause
data: { equals: '' },
suggest: [
{
messageId: 'suggestNullish',
data: { equals: '' },
fix(fixer) {
const nullishBranchText = (0, util_1.getTextWithParentheses)(context.sourceCode, nullishBranch);
const rightOperandReplacement = (0, util_1.isParenthesized)(nullishBranch, context.sourceCode)
? nullishBranchText
: (0, getWrappedCode_1.getWrappedCode)(nullishBranchText, (0, util_1.getOperatorPrecedenceForNode)(nullishBranch), util_1.OperatorPrecedence.Coalesce);
return fixer.replaceText(node, `${(0, util_1.getTextWithParentheses)(context.sourceCode, nullishCoalescingParams.nullishCoalescingLeftNode)} ?? ${rightOperandReplacement}`);
},
},
],
});
}
},
IfStatement(node) {
if (ignoreIfStatements || node.alternate != null) {
return;
}
let assignmentExpression;
if (node.consequent.type === utils_1.AST_NODE_TYPES.BlockStatement &&
node.consequent.body.length === 1 &&
node.consequent.body[0].type === utils_1.AST_NODE_TYPES.ExpressionStatement) {
assignmentExpression = node.consequent.body[0].expression;
}
else if (node.consequent.type === utils_1.AST_NODE_TYPES.ExpressionStatement) {
assignmentExpression = node.consequent.expression;
}
if (assignmentExpression?.type !== utils_1.AST_NODE_TYPES.AssignmentExpression ||
!isMemberAccessLike(assignmentExpression.left)) {
return;
}
const nullishCoalescingLeftNode = assignmentExpression.left;
const nullishCoalescingRightNode = assignmentExpression.right;
const { nodesInsideTestExpression, operator } = getOperatorAndNodesInsideTestExpression(node);
if (operator == null || !['!', '==', '==='].includes(operator)) {
return;
}
const nullishCoalescingParams = getNullishCoalescingParams(node, nullishCoalescingLeftNode, nodesInsideTestExpression, operator);
if (nullishCoalescingParams.isFixable) {
// Handle comments
const isConsequentNodeBlockStatement = node.consequent.type === utils_1.AST_NODE_TYPES.BlockStatement;
const commentsBefore = formatComments(context.sourceCode.getCommentsBefore(assignmentExpression), isConsequentNodeBlockStatement ? '\n' : ' ');
const commentsAfter = isConsequentNodeBlockStatement
? formatComments(context.sourceCode.getCommentsAfter(assignmentExpression.parent), '\n')
: '';
context.report({
node,
messageId: 'preferNullishOverAssignment',
data: { equals: '=' },
suggest: [
{
messageId: 'suggestNullish',
data: { equals: '=' },
fix(fixer) {
const fixes = [];
if (commentsBefore) {
fixes.push(fixer.insertTextBefore(node, commentsBefore));
}
fixes.push(fixer.replaceText(node, `${(0, util_1.getTextWithParentheses)(context.sourceCode, nullishCoalescingLeftNode)} ??= ${(0, util_1.getTextWithParentheses)(context.sourceCode, nullishCoalescingRightNode)};`));
if (commentsAfter) {
fixes.push(fixer.insertTextAfter(node, ` ${commentsAfter.slice(0, -1)}`));
}
return fixes;
},
},
],
});
}
},
'LogicalExpression[operator = "||"]'(node) {
checkAndFixWithPreferNullishOverOr(node, 'or', '');
},
};
},
});
function isBooleanConstructorContext(node, context) {
const parent = node.parent;
if (parent == null) {
return false;
}
if (parent.type === utils_1.AST_NODE_TYPES.LogicalExpression) {
return isBooleanConstructorContext(parent, context);
}
if (parent.type === utils_1.AST_NODE_TYPES.ConditionalExpression &&
(parent.consequent === node || parent.alternate === node)) {
return isBooleanConstructorContext(parent, context);
}
if (parent.type === utils_1.AST_NODE_TYPES.SequenceExpression &&
parent.expressions.at(-1) === node) {
return isBooleanConstructorContext(parent, context);
}
return isBuiltInBooleanCall(parent, context);
}
function isBuiltInBooleanCall(node, context) {
if (node.type === utils_1.AST_NODE_TYPES.CallExpression &&
node.callee.type === utils_1.AST_NODE_TYPES.Identifier &&
// eslint-disable-next-line @typescript-eslint/internal/prefer-ast-types-enum
node.callee.name === 'Boolean' &&
node.arguments[0]) {
const scope = context.sourceCode.getScope(node);
const variable = utils_1.ASTUtils.findVariable(scope, node.callee);
return variable == null || variable.defs.length === 0;
}
return false;
}
function isMixedLogicalExpression(node) {
const seen = new Set();
const queue = [node.parent, node.left, node.right];
for (const current of queue) {
if (seen.has(current)) {
continue;
}
seen.add(current);
if (current.type === utils_1.AST_NODE_TYPES.LogicalExpression) {
if (current.operator === '&&') {
return true;
}
if (['||', '||='].includes(current.operator)) {
// check the pieces of the node to catch cases like `a || b || c && d`
queue.push(current.parent, current.left, current.right);
}
}
}
return false;
}
/**
* Checks if two TSESTree nodes have the same member access sequence,
* regardless of optional chaining differences.
*
* Note: This does not imply that the nodes are runtime-equivalent.
*
* Example: `a.b.c`, `a?.b.c`, `a.b?.c`, `(a?.b).c`, `(a.b)?.c` are considered similar.
*
* @param a First TSESTree node.
* @param b Second TSESTree node.
* @returns `true` if the nodes access members in the same order; otherwise, `false`.
*/
function areNodesSimilarMemberAccess(a, b) {
if (a.type === utils_1.AST_NODE_TYPES.MemberExpression &&
b.type === utils_1.AST_NODE_TYPES.MemberExpression) {
if (!areNodesSimilarMemberAccess(a.object, b.object)) {
return false;
}
if (a.computed === b.computed) {
return (0, util_1.isNodeEqual)(a.property, b.property);
}
if (a.property.type === utils_1.AST_NODE_TYPES.Literal &&
b.property.type === utils_1.AST_NODE_TYPES.Identifier) {
return a.property.value === b.property.name;
}
if (a.property.type === utils_1.AST_NODE_TYPES.Identifier &&
b.property.type === utils_1.AST_NODE_TYPES.Literal) {
return a.property.name === b.property.value;
}
return false;
}
if (a.type === utils_1.AST_NODE_TYPES.ChainExpression ||
b.type === utils_1.AST_NODE_TYPES.ChainExpression) {
return areNodesSimilarMemberAccess((0, util_1.skipChainExpression)(a), (0, util_1.skipChainExpression)(b));
}
return (0, util_1.isNodeEqual)(a, b);
}
/**
* Returns the branch nodes of a conditional expression:
* - the "nonNullish branch" is the branch when test node is not nullish
* - the "nullish branch" is the branch when test node is nullish
*/
function getBranchNodes(node, operator) {
if (['', '!=', '!=='].includes(operator)) {
return { nonNullishBranch: node.consequent, nullishBranch: node.alternate };
}
return { nonNullishBranch: node.alternate, nullishBranch: node.consequent };
}
function getOperatorAndNodesInsideTestExpression(node) {
let operator = null;
let nodesInsideTestExpression = [];
if (isMemberAccessLike(node.test) ||
node.test.type === utils_1.AST_NODE_TYPES.UnaryExpression) {
operator = getNonBinaryNodeOperator(node.test);
}
else if (node.test.type === utils_1.AST_NODE_TYPES.BinaryExpression) {
nodesInsideTestExpression = [node.test.left, node.test.right];
if (node.test.operator === '==' ||
node.test.operator === '!=' ||
node.test.operator === '===' ||
node.test.operator === '!==') {
operator = node.test.operator;
}
}
else if (node.test.type === utils_1.AST_NODE_TYPES.LogicalExpression &&
node.test.left.type === utils_1.AST_NODE_TYPES.BinaryExpression &&
node.test.right.type === utils_1.AST_NODE_TYPES.BinaryExpression) {
if (isNodeNullishComparison(node.test.left) ||
isNodeNullishComparison(node.test.right)) {
return { nodesInsideTestExpression, operator };
}
nodesInsideTestExpression = [
node.test.left.left,
node.test.left.right,
node.test.right.left,
node.test.right.right,
];
if (['||', '||='].includes(node.test.operator)) {
if (node.test.left.operator === '===' &&
node.test.right.operator === '===') {
operator = '===';
}
else if (((node.test.left.operator === '===' ||
node.test.right.operator === '===') &&
(node.test.left.operator === '==' ||
node.test.right.operator === '==')) ||
(node.test.left.operator === '==' && node.test.right.operator === '==')) {
operator = '==';
}
}
else if (node.test.operator === '&&') {
if (node.test.left.operator === '!==' &&
node.test.right.operator === '!==') {
operator = '!==';
}
else if (((node.test.left.operator === '!==' ||
node.test.right.operator === '!==') &&
(node.test.left.operator === '!=' ||
node.test.right.operator === '!=')) ||
(node.test.left.operator === '!=' && node.test.right.operator === '!=')) {
operator = '!=';
}
}
}
return { nodesInsideTestExpression, operator };
}
function getNonBinaryNodeOperator(node) {
if (node.type !== utils_1.AST_NODE_TYPES.UnaryExpression) {
return '';
}
if (isMemberAccessLike(node.argument) && node.operator === '!') {
return '!';
}
return null;
}
function formatComments(comments, separator) {
return comments
.map(({ type, value }) => type === utils_1.AST_TOKEN_TYPES.Line
? `//${value}${separator}`
: `/*${value}*/${separator}`)
.join('');
}

View File

@@ -0,0 +1,27 @@
import type { TSESTree } from '@typescript-eslint/types';
import type { Referencer } from './Referencer';
import { Visitor } from './Visitor';
export declare class ClassVisitor extends Visitor {
#private;
constructor(referencer: Referencer);
static visit(referencer: Referencer, node: TSESTree.ClassDeclaration | TSESTree.ClassExpression): void;
visit(node: TSESTree.Node | null | undefined): void;
protected visitClass(node: TSESTree.ClassDeclaration | TSESTree.ClassExpression): void;
protected visitFunctionParameterTypeAnnotation(node: TSESTree.Parameter): void;
protected visitMethod(node: TSESTree.MethodDefinition): void;
protected visitMethodFunction(node: TSESTree.FunctionExpression): void;
protected visitPropertyBase(node: TSESTree.AccessorProperty | TSESTree.PropertyDefinition | TSESTree.TSAbstractAccessorProperty | TSESTree.TSAbstractMethodDefinition | TSESTree.TSAbstractPropertyDefinition): void;
protected visitPropertyDefinition(node: TSESTree.AccessorProperty | TSESTree.PropertyDefinition | TSESTree.TSAbstractAccessorProperty | TSESTree.TSAbstractPropertyDefinition): void;
protected visitType(node: TSESTree.Node | null | undefined): void;
protected AccessorProperty(node: TSESTree.AccessorProperty): void;
protected ClassBody(node: TSESTree.ClassBody): void;
protected Identifier(node: TSESTree.Identifier): void;
protected MethodDefinition(node: TSESTree.MethodDefinition): void;
protected PrivateIdentifier(): void;
protected PropertyDefinition(node: TSESTree.PropertyDefinition): void;
protected StaticBlock(node: TSESTree.StaticBlock): void;
protected TSAbstractAccessorProperty(node: TSESTree.TSAbstractAccessorProperty): void;
protected TSAbstractMethodDefinition(node: TSESTree.TSAbstractMethodDefinition): void;
protected TSAbstractPropertyDefinition(node: TSESTree.TSAbstractPropertyDefinition): void;
protected TSIndexSignature(node: TSESTree.TSIndexSignature): void;
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"argon2.d.ts","sourceRoot":"","sources":["../src/argon2.ts"],"names":[],"mappings":"AAYA,OAAO,EAAqD,KAAK,QAAQ,EAAE,MAAM,YAAY,CAAC;AAkK9F;;;;;GAKG;AACH,MAAM,MAAM,SAAS,GAAG;IACtB,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,GAAG,CAAC,EAAE,QAAQ,CAAC;IACf,eAAe,CAAC,EAAE,QAAQ,CAAC;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;CACzC,CAAC;AAuNF,qCAAqC;AACrC,eAAO,MAAM,OAAO,GAAI,UAAU,QAAQ,EAAE,MAAM,QAAQ,EAAE,MAAM,SAAS,KAAG,UACnC,CAAC;AAC5C,8CAA8C;AAC9C,eAAO,MAAM,OAAO,GAAI,UAAU,QAAQ,EAAE,MAAM,QAAQ,EAAE,MAAM,SAAS,KAAG,UACpC,CAAC;AAC3C,sEAAsE;AACtE,eAAO,MAAM,QAAQ,GAAI,UAAU,QAAQ,EAAE,MAAM,QAAQ,EAAE,MAAM,SAAS,KAAG,UACpC,CAAC;AAiE5C,2CAA2C;AAC3C,eAAO,MAAM,YAAY,GACvB,UAAU,QAAQ,EAClB,MAAM,QAAQ,EACd,MAAM,SAAS,KACd,OAAO,CAAC,UAAU,CAAmD,CAAC;AACzE,oDAAoD;AACpD,eAAO,MAAM,YAAY,GACvB,UAAU,QAAQ,EAClB,MAAM,QAAQ,EACd,MAAM,SAAS,KACd,OAAO,CAAC,UAAU,CAAkD,CAAC;AACxE,4EAA4E;AAC5E,eAAO,MAAM,aAAa,GACxB,UAAU,QAAQ,EAClB,MAAM,QAAQ,EACd,MAAM,SAAS,KACd,OAAO,CAAC,UAAU,CAAmD,CAAC"}

View File

@@ -0,0 +1,18 @@
import type { AST_NODE_TYPES, AST_TOKEN_TYPES, TSESTree } from '../ts-estree';
export declare const isNodeOfType: <NodeType extends AST_NODE_TYPES>(nodeType: NodeType) => (node: TSESTree.Node | null | undefined) => node is Extract<TSESTree.Node, {
type: NodeType;
}>;
export declare const isNodeOfTypes: <NodeTypes extends readonly AST_NODE_TYPES[]>(nodeTypes: NodeTypes) => (node: TSESTree.Node | null | undefined) => node is Extract<TSESTree.Node, {
type: NodeTypes[number];
}>;
export declare const isNodeOfTypeWithConditions: <NodeType extends AST_NODE_TYPES, ExtractedNode extends Extract<TSESTree.Node, {
type: NodeType;
}>, Conditions extends Partial<ExtractedNode>>(nodeType: NodeType, conditions: Conditions) => ((node: TSESTree.Node | null | undefined) => node is Conditions & ExtractedNode);
export declare const isTokenOfTypeWithConditions: <TokenType extends AST_TOKEN_TYPES, ExtractedToken extends Extract<TSESTree.Token, {
type: TokenType;
}>, Conditions extends Partial<{
type: TokenType;
} & TSESTree.Token>>(tokenType: TokenType, conditions: Conditions) => ((token: TSESTree.Token | null | undefined) => token is Conditions & ExtractedToken);
export declare const isNotTokenOfTypeWithConditions: <TokenType extends AST_TOKEN_TYPES, ExtractedToken extends Extract<TSESTree.Token, {
type: TokenType;
}>, Conditions extends Partial<ExtractedToken>>(tokenType: TokenType, conditions: Conditions) => ((token: TSESTree.Token | null | undefined) => token is Exclude<TSESTree.Token, Conditions & ExtractedToken>);

View File

@@ -0,0 +1,37 @@
import * as ts from 'typescript';
/**
* Checks if the given type is (or accepts) nullable
*/
export declare function isNullableType(type: ts.Type): boolean;
/**
* Checks if the given type is either an array type,
* or a union made up solely of array types.
*/
export declare function isTypeArrayTypeOrUnionOfArrayTypes(type: ts.Type, checker: ts.TypeChecker): boolean;
/**
* @returns true if the type is `never`
*/
export declare function isTypeNeverType(type: ts.Type): boolean;
/**
* @returns true if the type is `unknown`
*/
export declare function isTypeUnknownType(type: ts.Type): boolean;
export declare function isTypeReferenceType(type: ts.Type): type is ts.TypeReference;
/**
* @returns true if the type is `any`
*/
export declare function isTypeAnyType(type: ts.Type): boolean;
/**
* @returns true if the type is `any[]`
*/
export declare function isTypeAnyArrayType(type: ts.Type, checker: ts.TypeChecker): boolean;
/**
* @returns true if the type is `unknown[]`
*/
export declare function isTypeUnknownArrayType(type: ts.Type, checker: ts.TypeChecker): boolean;
/**
* @returns Whether a type is an instance of the parent type, including for the parent's base types.
*/
export declare function typeIsOrHasBaseType(type: ts.Type, parentType: ts.Type): boolean;
export declare function isTypeBigIntLiteralType(type: ts.Type): type is ts.BigIntLiteralType;
export declare function isTypeTemplateLiteralType(type: ts.Type): type is ts.TemplateLiteralType;

View File

@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ESLintScopeVariable = void 0;
const VariableBase_1 = require("./VariableBase");
/**
* ESLint defines global variables using the eslint-scope Variable class
* This is declared here for consumers to use
*/
class ESLintScopeVariable extends VariableBase_1.VariableBase {
/**
* Written to by ESLint.
* If this key exists, this variable is a global variable added by ESLint.
* If this is `true`, this variable can be assigned arbitrary values.
* If this is `false`, this variable is readonly.
*/
writeable; // note that this isn't a typo - ESlint uses this spelling here
/**
* Written to by ESLint.
* This property is undefined if there are no globals comment directives.
* The array of globals comment directives which defined this global variable in the source code file.
*/
eslintExplicitGlobal;
/**
* Written to by ESLint.
* The configured value in config files. This can be different from `variable.writeable` if there are globals comment directives.
*/
eslintImplicitGlobalSetting;
/**
* Written to by ESLint.
* If this key exists, it is a global variable added by ESLint.
* If `true`, this global variable was defined by a globals comment directive in the source code file.
*/
eslintExplicitGlobalComments;
}
exports.ESLintScopeVariable = ESLintScopeVariable;

View File

@@ -0,0 +1,5 @@
throw new Error(
'Vitest cannot be imported in a CommonJS module using require(). Please use "import" instead.'
+ '\n\nIf you are using "import" in your source code, then it\'s possible it was bundled into require() automatically by your bundler. '
+ 'In that case, do not bundle CommonJS output since it will never work with Vitest, or use dynamic import() which is available in all CommonJS modules.',
)

View File

@@ -0,0 +1,767 @@
import * as core from "../core/index.cjs";
import { util } from "../core/index.cjs";
import type { StandardSchemaWithJSONProps } from "../core/standard-schema.cjs";
import * as parse from "./parse.cjs";
export type ZodStandardSchemaWithJSON<T> = StandardSchemaWithJSONProps<core.input<T>, core.output<T>>;
export interface ZodType<out Output = unknown, out Input = unknown, out Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> extends core.$ZodType<Output, Input, Internals> {
def: Internals["def"];
type: Internals["def"]["type"];
/** @deprecated Use `.def` instead. */
_def: Internals["def"];
/** @deprecated Use `z.output<typeof schema>` instead. */
_output: Internals["output"];
/** @deprecated Use `z.input<typeof schema>` instead. */
_input: Internals["input"];
"~standard": ZodStandardSchemaWithJSON<this>;
/** Converts this schema to a JSON Schema representation. */
toJSONSchema(params?: core.ToJSONSchemaParams): core.ZodStandardJSONSchemaPayload<this>;
check(...checks: (core.CheckFn<core.output<this>> | core.$ZodCheck<core.output<this>>)[]): this;
with(...checks: (core.CheckFn<core.output<this>> | core.$ZodCheck<core.output<this>>)[]): this;
clone(def?: Internals["def"], params?: {
parent: boolean;
}): this;
register<R extends core.$ZodRegistry>(registry: R, ...meta: this extends R["_schema"] ? undefined extends R["_meta"] ? [core.$replace<R["_meta"], this>?] : [core.$replace<R["_meta"], this>] : ["Incompatible schema"]): this;
brand<T extends PropertyKey = PropertyKey, Dir extends "in" | "out" | "inout" = "out">(value?: T): PropertyKey extends T ? this : core.$ZodBranded<this, T, Dir>;
parse(data: unknown, params?: core.ParseContext<core.$ZodIssue>): core.output<this>;
safeParse(data: unknown, params?: core.ParseContext<core.$ZodIssue>): parse.ZodSafeParseResult<core.output<this>>;
parseAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<core.output<this>>;
safeParseAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.output<this>>>;
spa: (data: unknown, params?: core.ParseContext<core.$ZodIssue>) => Promise<parse.ZodSafeParseResult<core.output<this>>>;
encode(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): core.input<this>;
decode(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): core.output<this>;
encodeAsync(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<core.input<this>>;
decodeAsync(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<core.output<this>>;
safeEncode(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): parse.ZodSafeParseResult<core.input<this>>;
safeDecode(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): parse.ZodSafeParseResult<core.output<this>>;
safeEncodeAsync(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.input<this>>>;
safeDecodeAsync(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.output<this>>>;
refine<Ch extends (arg: core.output<this>) => unknown | Promise<unknown>>(check: Ch, params?: string | core.$ZodCustomParams): Ch extends (arg: any) => arg is infer R ? this & ZodType<R, core.input<this>> : this;
superRefine(refinement: (arg: core.output<this>, ctx: core.$RefinementCtx<core.output<this>>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): this;
overwrite(fn: (x: core.output<this>) => core.output<this>): this;
optional(): ZodOptional<this>;
exactOptional(): ZodExactOptional<this>;
nonoptional(params?: string | core.$ZodNonOptionalParams): ZodNonOptional<this>;
nullable(): ZodNullable<this>;
nullish(): ZodOptional<ZodNullable<this>>;
default(def: util.NoUndefined<core.output<this>>): ZodDefault<this>;
default(def: () => util.NoUndefined<core.output<this>>): ZodDefault<this>;
prefault(def: () => core.input<this>): ZodPrefault<this>;
prefault(def: core.input<this>): ZodPrefault<this>;
array(): ZodArray<this>;
or<T extends core.SomeType>(option: T): ZodUnion<[this, T]>;
and<T extends core.SomeType>(incoming: T): ZodIntersection<this, T>;
transform<NewOut>(transform: (arg: core.output<this>, ctx: core.$RefinementCtx<core.output<this>>) => NewOut | Promise<NewOut>): ZodPipe<this, ZodTransform<Awaited<NewOut>, core.output<this>>>;
catch(def: core.output<this>): ZodCatch<this>;
catch(def: (ctx: core.$ZodCatchCtx) => core.output<this>): ZodCatch<this>;
pipe<T extends core.$ZodType<any, core.output<this>>>(target: T | core.$ZodType<any, core.output<this>>): ZodPipe<this, T>;
readonly(): ZodReadonly<this>;
/** Returns a new instance that has been registered in `z.globalRegistry` with the specified description */
describe(description: string): this;
description?: string;
/** Returns the metadata associated with this instance in `z.globalRegistry` */
meta(): core.$replace<core.GlobalMeta, this> | undefined;
/** Returns a new instance that has been registered in `z.globalRegistry` with the specified metadata */
meta(data: core.$replace<core.GlobalMeta, this>): this;
/** @deprecated Try safe-parsing `undefined` (this is what `isOptional` does internally):
*
* ```ts
* const schema = z.string().optional();
* const isOptional = schema.safeParse(undefined).success; // true
* ```
*/
isOptional(): boolean;
/**
* @deprecated Try safe-parsing `null` (this is what `isNullable` does internally):
*
* ```ts
* const schema = z.string().nullable();
* const isNullable = schema.safeParse(null).success; // true
* ```
*/
isNullable(): boolean;
apply<T>(fn: (schema: this) => T): T;
}
export interface _ZodType<out Internals extends core.$ZodTypeInternals = core.$ZodTypeInternals> extends ZodType<any, any, Internals> {
}
export declare const ZodType: core.$constructor<ZodType>;
export interface _ZodString<T extends core.$ZodStringInternals<unknown> = core.$ZodStringInternals<unknown>> extends _ZodType<T> {
format: string | null;
minLength: number | null;
maxLength: number | null;
regex(regex: RegExp, params?: string | core.$ZodCheckRegexParams): this;
includes(value: string, params?: string | core.$ZodCheckIncludesParams): this;
startsWith(value: string, params?: string | core.$ZodCheckStartsWithParams): this;
endsWith(value: string, params?: string | core.$ZodCheckEndsWithParams): this;
min(minLength: number, params?: string | core.$ZodCheckMinLengthParams): this;
max(maxLength: number, params?: string | core.$ZodCheckMaxLengthParams): this;
length(len: number, params?: string | core.$ZodCheckLengthEqualsParams): this;
nonempty(params?: string | core.$ZodCheckMinLengthParams): this;
lowercase(params?: string | core.$ZodCheckLowerCaseParams): this;
uppercase(params?: string | core.$ZodCheckUpperCaseParams): this;
trim(): this;
normalize(form?: "NFC" | "NFD" | "NFKC" | "NFKD" | (string & {})): this;
toLowerCase(): this;
toUpperCase(): this;
slugify(): this;
}
/** @internal */
export declare const _ZodString: core.$constructor<_ZodString>;
export interface ZodString extends _ZodString<core.$ZodStringInternals<string>> {
/** @deprecated Use `z.email()` instead. */
email(params?: string | core.$ZodCheckEmailParams): this;
/** @deprecated Use `z.url()` instead. */
url(params?: string | core.$ZodCheckURLParams): this;
/** @deprecated Use `z.jwt()` instead. */
jwt(params?: string | core.$ZodCheckJWTParams): this;
/** @deprecated Use `z.emoji()` instead. */
emoji(params?: string | core.$ZodCheckEmojiParams): this;
/** @deprecated Use `z.guid()` instead. */
guid(params?: string | core.$ZodCheckGUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuid(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuidv4(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuidv6(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuidv7(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.nanoid()` instead. */
nanoid(params?: string | core.$ZodCheckNanoIDParams): this;
/** @deprecated Use `z.guid()` instead. */
guid(params?: string | core.$ZodCheckGUIDParams): this;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use `z.cuid2()` instead.
* See https://github.com/paralleldrive/cuid.
*/
cuid(params?: string | core.$ZodCheckCUIDParams): this;
/** @deprecated Use `z.cuid2()` instead. */
cuid2(params?: string | core.$ZodCheckCUID2Params): this;
/** @deprecated Use `z.ulid()` instead. */
ulid(params?: string | core.$ZodCheckULIDParams): this;
/** @deprecated Use `z.base64()` instead. */
base64(params?: string | core.$ZodCheckBase64Params): this;
/** @deprecated Use `z.base64url()` instead. */
base64url(params?: string | core.$ZodCheckBase64URLParams): this;
/** @deprecated Use `z.xid()` instead. */
xid(params?: string | core.$ZodCheckXIDParams): this;
/** @deprecated Use `z.ksuid()` instead. */
ksuid(params?: string | core.$ZodCheckKSUIDParams): this;
/** @deprecated Use `z.ipv4()` instead. */
ipv4(params?: string | core.$ZodCheckIPv4Params): this;
/** @deprecated Use `z.ipv6()` instead. */
ipv6(params?: string | core.$ZodCheckIPv6Params): this;
/** @deprecated Use `z.cidrv4()` instead. */
cidrv4(params?: string | core.$ZodCheckCIDRv4Params): this;
/** @deprecated Use `z.cidrv6()` instead. */
cidrv6(params?: string | core.$ZodCheckCIDRv6Params): this;
/** @deprecated Use `z.e164()` instead. */
e164(params?: string | core.$ZodCheckE164Params): this;
/** @deprecated Use `z.iso.datetime()` instead. */
datetime(params?: string | core.$ZodCheckISODateTimeParams): this;
/** @deprecated Use `z.iso.date()` instead. */
date(params?: string | core.$ZodCheckISODateParams): this;
/** @deprecated Use `z.iso.time()` instead. */
time(params?: string | core.$ZodCheckISOTimeParams): this;
/** @deprecated Use `z.iso.duration()` instead. */
duration(params?: string | core.$ZodCheckISODurationParams): this;
}
export declare const ZodString: core.$constructor<ZodString>;
export declare function string(params?: string | core.$ZodStringParams): ZodString;
export declare function string<T extends string>(params?: string | core.$ZodStringParams): core.$ZodType<T, T>;
export interface ZodStringFormat<Format extends string = string> extends _ZodString<core.$ZodStringFormatInternals<Format>> {
}
export declare const ZodStringFormat: core.$constructor<ZodStringFormat>;
export interface ZodEmail extends ZodStringFormat<"email"> {
_zod: core.$ZodEmailInternals;
}
export declare const ZodEmail: core.$constructor<ZodEmail>;
export declare function email(params?: string | core.$ZodEmailParams): ZodEmail;
export interface ZodGUID extends ZodStringFormat<"guid"> {
_zod: core.$ZodGUIDInternals;
}
export declare const ZodGUID: core.$constructor<ZodGUID>;
export declare function guid(params?: string | core.$ZodGUIDParams): ZodGUID;
export interface ZodUUID extends ZodStringFormat<"uuid"> {
_zod: core.$ZodUUIDInternals;
}
export declare const ZodUUID: core.$constructor<ZodUUID>;
export declare function uuid(params?: string | core.$ZodUUIDParams): ZodUUID;
export declare function uuidv4(params?: string | core.$ZodUUIDv4Params): ZodUUID;
export declare function uuidv6(params?: string | core.$ZodUUIDv6Params): ZodUUID;
export declare function uuidv7(params?: string | core.$ZodUUIDv7Params): ZodUUID;
export interface ZodURL extends ZodStringFormat<"url"> {
_zod: core.$ZodURLInternals;
}
export declare const ZodURL: core.$constructor<ZodURL>;
export declare function url(params?: string | core.$ZodURLParams): ZodURL;
export declare function httpUrl(params?: string | Omit<core.$ZodURLParams, "protocol" | "hostname">): ZodURL;
export interface ZodEmoji extends ZodStringFormat<"emoji"> {
_zod: core.$ZodEmojiInternals;
}
export declare const ZodEmoji: core.$constructor<ZodEmoji>;
export declare function emoji(params?: string | core.$ZodEmojiParams): ZodEmoji;
export interface ZodNanoID extends ZodStringFormat<"nanoid"> {
_zod: core.$ZodNanoIDInternals;
}
export declare const ZodNanoID: core.$constructor<ZodNanoID>;
export declare function nanoid(params?: string | core.$ZodNanoIDParams): ZodNanoID;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export interface ZodCUID extends ZodStringFormat<"cuid"> {
_zod: core.$ZodCUIDInternals;
}
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare const ZodCUID: core.$constructor<ZodCUID>;
/**
* Validates a CUID v1 string.
*
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare function cuid(params?: string | core.$ZodCUIDParams): ZodCUID;
export interface ZodCUID2 extends ZodStringFormat<"cuid2"> {
_zod: core.$ZodCUID2Internals;
}
export declare const ZodCUID2: core.$constructor<ZodCUID2>;
export declare function cuid2(params?: string | core.$ZodCUID2Params): ZodCUID2;
export interface ZodULID extends ZodStringFormat<"ulid"> {
_zod: core.$ZodULIDInternals;
}
export declare const ZodULID: core.$constructor<ZodULID>;
export declare function ulid(params?: string | core.$ZodULIDParams): ZodULID;
export interface ZodXID extends ZodStringFormat<"xid"> {
_zod: core.$ZodXIDInternals;
}
export declare const ZodXID: core.$constructor<ZodXID>;
export declare function xid(params?: string | core.$ZodXIDParams): ZodXID;
export interface ZodKSUID extends ZodStringFormat<"ksuid"> {
_zod: core.$ZodKSUIDInternals;
}
export declare const ZodKSUID: core.$constructor<ZodKSUID>;
export declare function ksuid(params?: string | core.$ZodKSUIDParams): ZodKSUID;
export interface ZodIPv4 extends ZodStringFormat<"ipv4"> {
_zod: core.$ZodIPv4Internals;
}
export declare const ZodIPv4: core.$constructor<ZodIPv4>;
export declare function ipv4(params?: string | core.$ZodIPv4Params): ZodIPv4;
export interface ZodMAC extends ZodStringFormat<"mac"> {
_zod: core.$ZodMACInternals;
}
export declare const ZodMAC: core.$constructor<ZodMAC>;
export declare function mac(params?: string | core.$ZodMACParams): ZodMAC;
export interface ZodIPv6 extends ZodStringFormat<"ipv6"> {
_zod: core.$ZodIPv6Internals;
}
export declare const ZodIPv6: core.$constructor<ZodIPv6>;
export declare function ipv6(params?: string | core.$ZodIPv6Params): ZodIPv6;
export interface ZodCIDRv4 extends ZodStringFormat<"cidrv4"> {
_zod: core.$ZodCIDRv4Internals;
}
export declare const ZodCIDRv4: core.$constructor<ZodCIDRv4>;
export declare function cidrv4(params?: string | core.$ZodCIDRv4Params): ZodCIDRv4;
export interface ZodCIDRv6 extends ZodStringFormat<"cidrv6"> {
_zod: core.$ZodCIDRv6Internals;
}
export declare const ZodCIDRv6: core.$constructor<ZodCIDRv6>;
export declare function cidrv6(params?: string | core.$ZodCIDRv6Params): ZodCIDRv6;
export interface ZodBase64 extends ZodStringFormat<"base64"> {
_zod: core.$ZodBase64Internals;
}
export declare const ZodBase64: core.$constructor<ZodBase64>;
export declare function base64(params?: string | core.$ZodBase64Params): ZodBase64;
export interface ZodBase64URL extends ZodStringFormat<"base64url"> {
_zod: core.$ZodBase64URLInternals;
}
export declare const ZodBase64URL: core.$constructor<ZodBase64URL>;
export declare function base64url(params?: string | core.$ZodBase64URLParams): ZodBase64URL;
export interface ZodE164 extends ZodStringFormat<"e164"> {
_zod: core.$ZodE164Internals;
}
export declare const ZodE164: core.$constructor<ZodE164>;
export declare function e164(params?: string | core.$ZodE164Params): ZodE164;
export interface ZodJWT extends ZodStringFormat<"jwt"> {
_zod: core.$ZodJWTInternals;
}
export declare const ZodJWT: core.$constructor<ZodJWT>;
export declare function jwt(params?: string | core.$ZodJWTParams): ZodJWT;
export interface ZodCustomStringFormat<Format extends string = string> extends ZodStringFormat<Format>, core.$ZodCustomStringFormat<Format> {
_zod: core.$ZodCustomStringFormatInternals<Format>;
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodCustomStringFormat: core.$constructor<ZodCustomStringFormat>;
export declare function stringFormat<Format extends string>(format: Format, fnOrRegex: ((arg: string) => util.MaybeAsync<unknown>) | RegExp, _params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<Format>;
export declare function hostname(_params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<"hostname">;
export declare function hex(_params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<"hex">;
export declare function hash<Alg extends util.HashAlgorithm, Enc extends util.HashEncoding = "hex">(alg: Alg, params?: {
enc?: Enc;
} & core.$ZodStringFormatParams): ZodCustomStringFormat<`${Alg}_${Enc}`>;
export interface _ZodNumber<Internals extends core.$ZodNumberInternals = core.$ZodNumberInternals> extends _ZodType<Internals> {
gt(value: number, params?: string | core.$ZodCheckGreaterThanParams): this;
/** Identical to .min() */
gte(value: number, params?: string | core.$ZodCheckGreaterThanParams): this;
min(value: number, params?: string | core.$ZodCheckGreaterThanParams): this;
lt(value: number, params?: string | core.$ZodCheckLessThanParams): this;
/** Identical to .max() */
lte(value: number, params?: string | core.$ZodCheckLessThanParams): this;
max(value: number, params?: string | core.$ZodCheckLessThanParams): this;
/** Consider `z.int()` instead. This API is considered *legacy*; it will never be removed but a better alternative exists. */
int(params?: string | core.$ZodCheckNumberFormatParams): this;
/** @deprecated This is now identical to `.int()`. Only numbers in the safe integer range are accepted. */
safe(params?: string | core.$ZodCheckNumberFormatParams): this;
positive(params?: string | core.$ZodCheckGreaterThanParams): this;
nonnegative(params?: string | core.$ZodCheckGreaterThanParams): this;
negative(params?: string | core.$ZodCheckLessThanParams): this;
nonpositive(params?: string | core.$ZodCheckLessThanParams): this;
multipleOf(value: number, params?: string | core.$ZodCheckMultipleOfParams): this;
/** @deprecated Use `.multipleOf()` instead. */
step(value: number, params?: string | core.$ZodCheckMultipleOfParams): this;
/** @deprecated In v4 and later, z.number() does not allow infinite values by default. This is a no-op. */
finite(params?: unknown): this;
minValue: number | null;
maxValue: number | null;
/** @deprecated Check the `format` property instead. */
isInt: boolean;
/** @deprecated Number schemas no longer accept infinite values, so this always returns `true`. */
isFinite: boolean;
format: string | null;
}
export interface ZodNumber extends _ZodNumber<core.$ZodNumberInternals<number>> {
}
export declare const ZodNumber: core.$constructor<ZodNumber>;
export declare function number(params?: string | core.$ZodNumberParams): ZodNumber;
export interface ZodNumberFormat extends ZodNumber {
_zod: core.$ZodNumberFormatInternals;
}
export declare const ZodNumberFormat: core.$constructor<ZodNumberFormat>;
export interface ZodInt extends ZodNumberFormat {
}
export declare function int(params?: string | core.$ZodCheckNumberFormatParams): ZodInt;
export interface ZodFloat32 extends ZodNumberFormat {
}
export declare function float32(params?: string | core.$ZodCheckNumberFormatParams): ZodFloat32;
export interface ZodFloat64 extends ZodNumberFormat {
}
export declare function float64(params?: string | core.$ZodCheckNumberFormatParams): ZodFloat64;
export interface ZodInt32 extends ZodNumberFormat {
}
export declare function int32(params?: string | core.$ZodCheckNumberFormatParams): ZodInt32;
export interface ZodUInt32 extends ZodNumberFormat {
}
export declare function uint32(params?: string | core.$ZodCheckNumberFormatParams): ZodUInt32;
export interface _ZodBoolean<T extends core.$ZodBooleanInternals = core.$ZodBooleanInternals> extends _ZodType<T> {
}
export interface ZodBoolean extends _ZodBoolean<core.$ZodBooleanInternals<boolean>> {
}
export declare const ZodBoolean: core.$constructor<ZodBoolean>;
export declare function boolean(params?: string | core.$ZodBooleanParams): ZodBoolean;
export interface _ZodBigInt<T extends core.$ZodBigIntInternals = core.$ZodBigIntInternals> extends _ZodType<T> {
gte(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this;
/** Alias of `.gte()` */
min(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this;
gt(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this;
/** Alias of `.lte()` */
lte(value: bigint, params?: string | core.$ZodCheckLessThanParams): this;
max(value: bigint, params?: string | core.$ZodCheckLessThanParams): this;
lt(value: bigint, params?: string | core.$ZodCheckLessThanParams): this;
positive(params?: string | core.$ZodCheckGreaterThanParams): this;
negative(params?: string | core.$ZodCheckLessThanParams): this;
nonpositive(params?: string | core.$ZodCheckLessThanParams): this;
nonnegative(params?: string | core.$ZodCheckGreaterThanParams): this;
multipleOf(value: bigint, params?: string | core.$ZodCheckMultipleOfParams): this;
minValue: bigint | null;
maxValue: bigint | null;
format: string | null;
}
export interface ZodBigInt extends _ZodBigInt<core.$ZodBigIntInternals<bigint>> {
}
export declare const ZodBigInt: core.$constructor<ZodBigInt>;
export declare function bigint(params?: string | core.$ZodBigIntParams): ZodBigInt;
export interface ZodBigIntFormat extends ZodBigInt {
_zod: core.$ZodBigIntFormatInternals;
}
export declare const ZodBigIntFormat: core.$constructor<ZodBigIntFormat>;
export declare function int64(params?: string | core.$ZodBigIntFormatParams): ZodBigIntFormat;
export declare function uint64(params?: string | core.$ZodBigIntFormatParams): ZodBigIntFormat;
export interface ZodSymbol extends _ZodType<core.$ZodSymbolInternals> {
}
export declare const ZodSymbol: core.$constructor<ZodSymbol>;
export declare function symbol(params?: string | core.$ZodSymbolParams): ZodSymbol;
export interface ZodUndefined extends _ZodType<core.$ZodUndefinedInternals> {
}
export declare const ZodUndefined: core.$constructor<ZodUndefined>;
declare function _undefined(params?: string | core.$ZodUndefinedParams): ZodUndefined;
export { _undefined as undefined };
export interface ZodNull extends _ZodType<core.$ZodNullInternals> {
}
export declare const ZodNull: core.$constructor<ZodNull>;
declare function _null(params?: string | core.$ZodNullParams): ZodNull;
export { _null as null };
export interface ZodAny extends _ZodType<core.$ZodAnyInternals> {
}
export declare const ZodAny: core.$constructor<ZodAny>;
export declare function any(): ZodAny;
export interface ZodUnknown extends _ZodType<core.$ZodUnknownInternals> {
}
export declare const ZodUnknown: core.$constructor<ZodUnknown>;
export declare function unknown(): ZodUnknown;
export interface ZodNever extends _ZodType<core.$ZodNeverInternals> {
}
export declare const ZodNever: core.$constructor<ZodNever>;
export declare function never(params?: string | core.$ZodNeverParams): ZodNever;
export interface ZodVoid extends _ZodType<core.$ZodVoidInternals> {
}
export declare const ZodVoid: core.$constructor<ZodVoid>;
declare function _void(params?: string | core.$ZodVoidParams): ZodVoid;
export { _void as void };
export interface _ZodDate<T extends core.$ZodDateInternals = core.$ZodDateInternals> extends _ZodType<T> {
min(value: number | Date, params?: string | core.$ZodCheckGreaterThanParams): this;
max(value: number | Date, params?: string | core.$ZodCheckLessThanParams): this;
/** @deprecated Not recommended. */
minDate: Date | null;
/** @deprecated Not recommended. */
maxDate: Date | null;
}
export interface ZodDate extends _ZodDate<core.$ZodDateInternals<Date>> {
}
export declare const ZodDate: core.$constructor<ZodDate>;
export declare function date(params?: string | core.$ZodDateParams): ZodDate;
export interface ZodArray<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodArrayInternals<T>>, core.$ZodArray<T> {
element: T;
min(minLength: number, params?: string | core.$ZodCheckMinLengthParams): this;
nonempty(params?: string | core.$ZodCheckMinLengthParams): this;
max(maxLength: number, params?: string | core.$ZodCheckMaxLengthParams): this;
length(len: number, params?: string | core.$ZodCheckLengthEqualsParams): this;
unwrap(): T;
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodArray: core.$constructor<ZodArray>;
export declare function array<T extends core.SomeType>(element: T, params?: string | core.$ZodArrayParams): ZodArray<T>;
export declare function keyof<T extends ZodObject>(schema: T): ZodEnum<util.KeysEnum<T["_zod"]["output"]>>;
export type SafeExtendShape<Base extends core.$ZodShape, Ext extends core.$ZodLooseShape> = {
[K in keyof Ext]: K extends keyof Base ? core.output<Ext[K]> extends core.output<Base[K]> ? core.input<Ext[K]> extends core.input<Base[K]> ? Ext[K] : never : never : Ext[K];
};
export interface ZodObject<
/** @ts-ignore Cast variance */
out Shape extends core.$ZodShape = core.$ZodLooseShape, out Config extends core.$ZodObjectConfig = core.$strip> extends _ZodType<core.$ZodObjectInternals<Shape, Config>>, core.$ZodObject<Shape, Config> {
"~standard": ZodStandardSchemaWithJSON<this>;
shape: Shape;
keyof(): ZodEnum<util.ToEnum<keyof Shape & string>>;
/** Define a schema to validate all unrecognized keys. This overrides the existing strict/loose behavior. */
catchall<T extends core.SomeType>(schema: T): ZodObject<Shape, core.$catchall<T>>;
/** @deprecated Use `z.looseObject()` or `.loose()` instead. */
passthrough(): ZodObject<Shape, core.$loose>;
/** Consider `z.looseObject(A.shape)` instead */
loose(): ZodObject<Shape, core.$loose>;
/** Consider `z.strictObject(A.shape)` instead */
strict(): ZodObject<Shape, core.$strict>;
/** This is the default behavior. This method call is likely unnecessary. */
strip(): ZodObject<Shape, core.$strip>;
extend<U extends core.$ZodLooseShape>(shape: U): ZodObject<util.Extend<Shape, util.Writeable<U>>, Config>;
safeExtend<U extends core.$ZodLooseShape>(shape: SafeExtendShape<Shape, U> & Partial<Record<keyof Shape, core.SomeType>>): ZodObject<util.Extend<Shape, util.Writeable<U>>, Config>;
/**
* @deprecated Use [`A.extend(B.shape)`](https://zod.dev/api?id=extend) instead.
*/
merge<U extends ZodObject>(other: U): ZodObject<util.Extend<Shape, U["shape"]>, U["_zod"]["config"]>;
pick<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<util.Flatten<Pick<Shape, Extract<keyof Shape, keyof M>>>, Config>;
omit<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<util.Flatten<Omit<Shape, Extract<keyof Shape, keyof M>>>, Config>;
partial(): ZodObject<{
-readonly [k in keyof Shape]: ZodOptional<Shape[k]>;
}, Config>;
partial<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
-readonly [k in keyof Shape]: k extends keyof M ? ZodOptional<Shape[k]> : Shape[k];
}, Config>;
required(): ZodObject<{
-readonly [k in keyof Shape]: ZodNonOptional<Shape[k]>;
}, Config>;
required<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
-readonly [k in keyof Shape]: k extends keyof M ? ZodNonOptional<Shape[k]> : Shape[k];
}, Config>;
}
export declare const ZodObject: core.$constructor<ZodObject>;
export declare function object<T extends core.$ZodLooseShape = Partial<Record<never, core.SomeType>>>(shape?: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$strip>;
export declare function strictObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$strict>;
export declare function looseObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$loose>;
export interface ZodUnion<T extends readonly core.SomeType[] = readonly core.$ZodType[]> extends _ZodType<core.$ZodUnionInternals<T>>, core.$ZodUnion<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
options: T;
}
export declare const ZodUnion: core.$constructor<ZodUnion>;
export declare function union<const T extends readonly core.SomeType[]>(options: T, params?: string | core.$ZodUnionParams): ZodUnion<T>;
export interface ZodXor<T extends readonly core.SomeType[] = readonly core.$ZodType[]> extends _ZodType<core.$ZodXorInternals<T>>, core.$ZodXor<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
options: T;
}
export declare const ZodXor: core.$constructor<ZodXor>;
/** Creates an exclusive union (XOR) where exactly one option must match.
* Unlike regular unions that succeed when any option matches, xor fails if
* zero or more than one option matches the input. */
export declare function xor<const T extends readonly core.SomeType[]>(options: T, params?: string | core.$ZodXorParams): ZodXor<T>;
export interface ZodDiscriminatedUnion<Options extends readonly core.SomeType[] = readonly core.$ZodType[], Disc extends string = string> extends ZodUnion<Options>, core.$ZodDiscriminatedUnion<Options, Disc> {
"~standard": ZodStandardSchemaWithJSON<this>;
_zod: core.$ZodDiscriminatedUnionInternals<Options, Disc>;
def: core.$ZodDiscriminatedUnionDef<Options, Disc>;
}
export declare const ZodDiscriminatedUnion: core.$constructor<ZodDiscriminatedUnion>;
export declare function discriminatedUnion<Types extends readonly [core.$ZodTypeDiscriminable<Disc>, ...core.$ZodTypeDiscriminable<Disc>[]], Disc extends string>(discriminator: Disc, options: Types, params?: string | core.$ZodDiscriminatedUnionParams): ZodDiscriminatedUnion<Types, Disc>;
export interface ZodIntersection<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodIntersectionInternals<A, B>>, core.$ZodIntersection<A, B> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodIntersection: core.$constructor<ZodIntersection>;
export declare function intersection<T extends core.SomeType, U extends core.SomeType>(left: T, right: U): ZodIntersection<T, U>;
export interface ZodTuple<T extends util.TupleItems = readonly core.$ZodType[], Rest extends core.SomeType | null = core.$ZodType | null> extends _ZodType<core.$ZodTupleInternals<T, Rest>>, core.$ZodTuple<T, Rest> {
"~standard": ZodStandardSchemaWithJSON<this>;
rest<Rest extends core.SomeType = core.$ZodType>(rest: Rest): ZodTuple<T, Rest>;
}
export declare const ZodTuple: core.$constructor<ZodTuple>;
export declare function tuple<T extends readonly [core.SomeType, ...core.SomeType[]]>(items: T, params?: string | core.$ZodTupleParams): ZodTuple<T, null>;
export declare function tuple<T extends readonly [core.SomeType, ...core.SomeType[]], Rest extends core.SomeType>(items: T, rest: Rest, params?: string | core.$ZodTupleParams): ZodTuple<T, Rest>;
export declare function tuple(items: [], params?: string | core.$ZodTupleParams): ZodTuple<[], null>;
export interface ZodRecord<Key extends core.$ZodRecordKey = core.$ZodRecordKey, Value extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodRecordInternals<Key, Value>>, core.$ZodRecord<Key, Value> {
"~standard": ZodStandardSchemaWithJSON<this>;
keyType: Key;
valueType: Value;
}
export declare const ZodRecord: core.$constructor<ZodRecord>;
export declare function record<Key extends core.$ZodRecordKey, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodRecord<Key, Value>;
export declare function partialRecord<Key extends core.$ZodRecordKey, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodRecord<Key & core.$partial, Value>;
export declare function looseRecord<Key extends core.$ZodRecordKey, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodRecord<Key, Value>;
export interface ZodMap<Key extends core.SomeType = core.$ZodType, Value extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodMapInternals<Key, Value>>, core.$ZodMap<Key, Value> {
"~standard": ZodStandardSchemaWithJSON<this>;
keyType: Key;
valueType: Value;
min(minSize: number, params?: string | core.$ZodCheckMinSizeParams): this;
nonempty(params?: string | core.$ZodCheckMinSizeParams): this;
max(maxSize: number, params?: string | core.$ZodCheckMaxSizeParams): this;
size(size: number, params?: string | core.$ZodCheckSizeEqualsParams): this;
}
export declare const ZodMap: core.$constructor<ZodMap>;
export declare function map<Key extends core.SomeType, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodMapParams): ZodMap<Key, Value>;
export interface ZodSet<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodSetInternals<T>>, core.$ZodSet<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
min(minSize: number, params?: string | core.$ZodCheckMinSizeParams): this;
nonempty(params?: string | core.$ZodCheckMinSizeParams): this;
max(maxSize: number, params?: string | core.$ZodCheckMaxSizeParams): this;
size(size: number, params?: string | core.$ZodCheckSizeEqualsParams): this;
}
export declare const ZodSet: core.$constructor<ZodSet>;
export declare function set<Value extends core.SomeType>(valueType: Value, params?: string | core.$ZodSetParams): ZodSet<Value>;
export interface ZodEnum<
/** @ts-ignore Cast variance */
out T extends util.EnumLike = util.EnumLike> extends _ZodType<core.$ZodEnumInternals<T>>, core.$ZodEnum<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
enum: T;
options: Array<T[keyof T]>;
extract<const U extends readonly (keyof T)[]>(values: U, params?: string | core.$ZodEnumParams): ZodEnum<util.Flatten<Pick<T, U[number]>>>;
exclude<const U extends readonly (keyof T)[]>(values: U, params?: string | core.$ZodEnumParams): ZodEnum<util.Flatten<Omit<T, U[number]>>>;
}
export declare const ZodEnum: core.$constructor<ZodEnum>;
declare function _enum<const T extends readonly string[]>(values: T, params?: string | core.$ZodEnumParams): ZodEnum<util.ToEnum<T[number]>>;
declare function _enum<const T extends util.EnumLike>(entries: T, params?: string | core.$ZodEnumParams): ZodEnum<T>;
export { _enum as enum };
/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.
*
* ```ts
* enum Colors { red, green, blue }
* z.enum(Colors);
* ```
*/
export declare function nativeEnum<T extends util.EnumLike>(entries: T, params?: string | core.$ZodEnumParams): ZodEnum<T>;
export interface ZodLiteral<T extends util.Literal = util.Literal> extends _ZodType<core.$ZodLiteralInternals<T>>, core.$ZodLiteral<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
values: Set<T>;
/** @legacy Use `.values` instead. Accessing this property will throw an error if the literal accepts multiple values. */
value: T;
}
export declare const ZodLiteral: core.$constructor<ZodLiteral>;
export declare function literal<const T extends ReadonlyArray<util.Literal>>(value: T, params?: string | core.$ZodLiteralParams): ZodLiteral<T[number]>;
export declare function literal<const T extends util.Literal>(value: T, params?: string | core.$ZodLiteralParams): ZodLiteral<T>;
export interface ZodFile extends _ZodType<core.$ZodFileInternals>, core.$ZodFile {
"~standard": ZodStandardSchemaWithJSON<this>;
min(size: number, params?: string | core.$ZodCheckMinSizeParams): this;
max(size: number, params?: string | core.$ZodCheckMaxSizeParams): this;
mime(types: util.MimeTypes | Array<util.MimeTypes>, params?: string | core.$ZodCheckMimeTypeParams): this;
}
export declare const ZodFile: core.$constructor<ZodFile>;
export declare function file(params?: string | core.$ZodFileParams): ZodFile;
export interface ZodTransform<O = unknown, I = unknown> extends _ZodType<core.$ZodTransformInternals<O, I>>, core.$ZodTransform<O, I> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodTransform: core.$constructor<ZodTransform>;
export declare function transform<I = unknown, O = I>(fn: (input: I, ctx: core.$RefinementCtx) => O): ZodTransform<Awaited<O>, I>;
export interface ZodOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodOptionalInternals<T>>, core.$ZodOptional<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodOptional: core.$constructor<ZodOptional>;
export declare function optional<T extends core.SomeType>(innerType: T): ZodOptional<T>;
export interface ZodExactOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodExactOptionalInternals<T>>, core.$ZodExactOptional<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodExactOptional: core.$constructor<ZodExactOptional>;
export declare function exactOptional<T extends core.SomeType>(innerType: T): ZodExactOptional<T>;
export interface ZodNullable<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodNullableInternals<T>>, core.$ZodNullable<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodNullable: core.$constructor<ZodNullable>;
export declare function nullable<T extends core.SomeType>(innerType: T): ZodNullable<T>;
export declare function nullish<T extends core.SomeType>(innerType: T): ZodOptional<ZodNullable<T>>;
export interface ZodDefault<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodDefaultInternals<T>>, core.$ZodDefault<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
/** @deprecated Use `.unwrap()` instead. */
removeDefault(): T;
}
export declare const ZodDefault: core.$constructor<ZodDefault>;
export declare function _default<T extends core.SomeType>(innerType: T, defaultValue: util.NoUndefined<core.output<T>> | (() => util.NoUndefined<core.output<T>>)): ZodDefault<T>;
export interface ZodPrefault<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodPrefaultInternals<T>>, core.$ZodPrefault<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodPrefault: core.$constructor<ZodPrefault>;
export declare function prefault<T extends core.SomeType>(innerType: T, defaultValue: core.input<T> | (() => core.input<T>)): ZodPrefault<T>;
export interface ZodNonOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodNonOptionalInternals<T>>, core.$ZodNonOptional<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodNonOptional: core.$constructor<ZodNonOptional>;
export declare function nonoptional<T extends core.SomeType>(innerType: T, params?: string | core.$ZodNonOptionalParams): ZodNonOptional<T>;
export interface ZodSuccess<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodSuccessInternals<T>>, core.$ZodSuccess<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodSuccess: core.$constructor<ZodSuccess>;
export declare function success<T extends core.SomeType>(innerType: T): ZodSuccess<T>;
export interface ZodCatch<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodCatchInternals<T>>, core.$ZodCatch<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
/** @deprecated Use `.unwrap()` instead. */
removeCatch(): T;
}
export declare const ZodCatch: core.$constructor<ZodCatch>;
declare function _catch<T extends core.SomeType>(innerType: T, catchValue: core.output<T> | ((ctx: core.$ZodCatchCtx) => core.output<T>)): ZodCatch<T>;
export { _catch as catch };
export interface ZodNaN extends _ZodType<core.$ZodNaNInternals>, core.$ZodNaN {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodNaN: core.$constructor<ZodNaN>;
export declare function nan(params?: string | core.$ZodNaNParams): ZodNaN;
export interface ZodPipe<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodPipeInternals<A, B>>, core.$ZodPipe<A, B> {
"~standard": ZodStandardSchemaWithJSON<this>;
in: A;
out: B;
}
export declare const ZodPipe: core.$constructor<ZodPipe>;
export declare function pipe<const A extends core.SomeType, B extends core.$ZodType<unknown, core.output<A>> = core.$ZodType<unknown, core.output<A>>>(in_: A, out: B | core.$ZodType<unknown, core.output<A>>): ZodPipe<A, B>;
export interface ZodCodec<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends ZodPipe<A, B>, core.$ZodCodec<A, B> {
"~standard": ZodStandardSchemaWithJSON<this>;
_zod: core.$ZodCodecInternals<A, B>;
def: core.$ZodCodecDef<A, B>;
}
export declare const ZodCodec: core.$constructor<ZodCodec>;
export declare function codec<const A extends core.SomeType, B extends core.SomeType = core.$ZodType>(in_: A, out: B, params: {
decode: (value: core.output<A>, payload: core.ParsePayload<core.output<A>>) => core.util.MaybeAsync<core.input<B>>;
encode: (value: core.input<B>, payload: core.ParsePayload<core.input<B>>) => core.util.MaybeAsync<core.output<A>>;
}): ZodCodec<A, B>;
export declare function invertCodec<A extends core.SomeType, B extends core.SomeType>(codec: ZodCodec<A, B>): ZodCodec<B, A>;
export interface ZodPreprocess<B extends core.SomeType = core.$ZodType> extends ZodPipe<core.$ZodTransform, B>, core.$ZodPreprocess<B> {
"~standard": ZodStandardSchemaWithJSON<this>;
_zod: core.$ZodPreprocessInternals<B>;
def: core.$ZodPreprocessDef<B>;
}
export declare const ZodPreprocess: core.$constructor<ZodPreprocess>;
export interface ZodReadonly<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodReadonlyInternals<T>>, core.$ZodReadonly<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodReadonly: core.$constructor<ZodReadonly>;
export declare function readonly<T extends core.SomeType>(innerType: T): ZodReadonly<T>;
export interface ZodTemplateLiteral<Template extends string = string> extends _ZodType<core.$ZodTemplateLiteralInternals<Template>>, core.$ZodTemplateLiteral<Template> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodTemplateLiteral: core.$constructor<ZodTemplateLiteral>;
export declare function templateLiteral<const Parts extends core.$ZodTemplateLiteralPart[]>(parts: Parts, params?: string | core.$ZodTemplateLiteralParams): ZodTemplateLiteral<core.$PartsToTemplateLiteral<Parts>>;
export interface ZodLazy<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodLazyInternals<T>>, core.$ZodLazy<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodLazy: core.$constructor<ZodLazy>;
export declare function lazy<T extends core.SomeType>(getter: () => T): ZodLazy<T>;
export interface ZodPromise<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodPromiseInternals<T>>, core.$ZodPromise<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodPromise: core.$constructor<ZodPromise>;
export declare function promise<T extends core.SomeType>(innerType: T): ZodPromise<T>;
export interface ZodFunction<Args extends core.$ZodFunctionIn = core.$ZodFunctionIn, Returns extends core.$ZodFunctionOut = core.$ZodFunctionOut> extends _ZodType<core.$ZodFunctionInternals<Args, Returns>>, core.$ZodFunction<Args, Returns> {
"~standard": ZodStandardSchemaWithJSON<this>;
_def: core.$ZodFunctionDef<Args, Returns>;
_input: core.$InferInnerFunctionType<Args, Returns>;
_output: core.$InferOuterFunctionType<Args, Returns>;
input<const Items extends util.TupleItems, const Rest extends core.$ZodFunctionOut = core.$ZodFunctionOut>(args: Items, rest?: Rest): ZodFunction<core.$ZodTuple<Items, Rest>, Returns>;
input<NewArgs extends core.$ZodFunctionIn>(args: NewArgs): ZodFunction<NewArgs, Returns>;
input(...args: any[]): ZodFunction<any, Returns>;
output<NewReturns extends core.$ZodType>(output: NewReturns): ZodFunction<Args, NewReturns>;
}
export declare const ZodFunction: core.$constructor<ZodFunction>;
export declare function _function(): ZodFunction;
export declare function _function<const In extends ReadonlyArray<core.$ZodType>>(params: {
input: In;
}): ZodFunction<ZodTuple<In, null>, core.$ZodFunctionOut>;
export declare function _function<const In extends ReadonlyArray<core.$ZodType>, const Out extends core.$ZodFunctionOut = core.$ZodFunctionOut>(params: {
input: In;
output: Out;
}): ZodFunction<ZodTuple<In, null>, Out>;
export declare function _function<const In extends core.$ZodFunctionIn = core.$ZodFunctionIn>(params: {
input: In;
}): ZodFunction<In, core.$ZodFunctionOut>;
export declare function _function<const Out extends core.$ZodFunctionOut = core.$ZodFunctionOut>(params: {
output: Out;
}): ZodFunction<core.$ZodFunctionIn, Out>;
export declare function _function<In extends core.$ZodFunctionIn = core.$ZodFunctionIn, Out extends core.$ZodType = core.$ZodType>(params?: {
input: In;
output: Out;
}): ZodFunction<In, Out>;
export { _function as function };
export interface ZodCustom<O = unknown, I = unknown> extends _ZodType<core.$ZodCustomInternals<O, I>>, core.$ZodCustom<O, I> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodCustom: core.$constructor<ZodCustom>;
export declare function check<O = unknown>(fn: core.CheckFn<O>): core.$ZodCheck<O>;
export declare function custom<O>(fn?: (data: unknown) => unknown, _params?: string | core.$ZodCustomParams | undefined): ZodCustom<O, O>;
export declare function refine<T>(fn: (arg: NoInfer<T>) => util.MaybeAsync<unknown>, _params?: string | core.$ZodCustomParams): core.$ZodCheck<T>;
export declare function superRefine<T>(fn: (arg: T, payload: core.$RefinementCtx<T>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): core.$ZodCheck<T>;
export declare const describe: typeof core.describe;
export declare const meta: typeof core.meta;
type ZodInstanceOfParams = core.Params<ZodCustom, core.$ZodIssueCustom, "type" | "check" | "checks" | "fn" | "abort" | "error" | "params" | "path">;
declare function _instanceof<T extends typeof util.Class>(cls: T, params?: ZodInstanceOfParams): ZodCustom<InstanceType<T>, InstanceType<T>>;
export { _instanceof as instanceof };
export declare const stringbool: (_params?: string | core.$ZodStringBoolParams) => ZodCodec<ZodString, ZodBoolean>;
type _ZodJSONSchema = ZodUnion<[
ZodString,
ZodNumber,
ZodBoolean,
ZodNull,
ZodArray<ZodJSONSchema>,
ZodRecord<ZodString, ZodJSONSchema>
]>;
type _ZodJSONSchemaInternals = _ZodJSONSchema["_zod"];
export interface ZodJSONSchemaInternals extends _ZodJSONSchemaInternals {
output: util.JSONType;
input: util.JSONType;
}
export interface ZodJSONSchema extends _ZodJSONSchema {
_zod: ZodJSONSchemaInternals;
}
export declare function json(params?: string | core.$ZodCustomParams): ZodJSONSchema;
export declare function preprocess<A, U extends core.SomeType, B = unknown>(fn: (arg: B, ctx: core.$RefinementCtx) => A, schema: U): ZodPreprocess<U>;

View File

@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @internal
*/
const secret = Symbol('secret');
/**
* @internal
*/
const mismatch = Symbol('mismatch');
/**
* A type which should match anything passed as a value but *doesn't*
* match {@linkcode Mismatch}. It helps TypeScript select the right overload
* for {@linkcode PositiveExpectTypeOf.toEqualTypeOf | .toEqualTypeOf()} and
* {@linkcode PositiveExpectTypeOf.toMatchTypeOf | .toMatchTypeOf()}.
*
* @internal
*/
const avalue = Symbol('avalue');

View File

@@ -0,0 +1,7 @@
import type { ParserServicesWithTypeInformation, TSESTree } from '@typescript-eslint/utils';
import type { RuleContext } from '@typescript-eslint/utils/ts-eslint';
import type { LastChainOperand, ValidOperand } from './gatherLogicalOperands';
import type { PreferOptionalChainMessageIds, PreferOptionalChainOptions } from './PreferOptionalChainOptions';
export declare function analyzeChain(context: RuleContext<PreferOptionalChainMessageIds, [
PreferOptionalChainOptions
]>, parserServices: ParserServicesWithTypeInformation, options: PreferOptionalChainOptions, node: TSESTree.Node, operator: TSESTree.LogicalExpression['operator'], chain: ValidOperand[], lastChainOperand?: LastChainOperand): void;

View File

@@ -0,0 +1,46 @@
'use strict';
const {Transform} = require('stream');
const alwaysFalse = () => false;
class SkipWhile extends Transform {
constructor(options) {
super(Object.assign({}, options, {writableObjectMode: true, readableObjectMode: true}));
this._condition = alwaysFalse;
if (options) {
'condition' in options && (this._condition = options.condition);
}
}
_transform(chunk, encoding, callback) {
const result = this._condition.call(this, chunk);
if (result && typeof result.then == 'function') {
result.then(
flag => {
if (!flag) {
this._transform = this._passThrough;
this.push(chunk);
}
callback(null);
},
error => callback(error)
);
} else {
if (!result) {
this._transform = this._passThrough;
this.push(chunk);
}
callback(null);
}
}
_passThrough(chunk, encoding, callback) {
this.push(chunk);
callback(null);
}
static make(condition) {
return new SkipWhile(typeof condition == 'object' ? condition : {condition});
}
}
SkipWhile.make.Constructor = SkipWhile;
module.exports = SkipWhile.make;

View File

@@ -0,0 +1,205 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useProgramFromProjectService = useProgramFromProjectService;
const debug_1 = __importDefault(require("debug"));
const minimatch_1 = require("minimatch");
const node_path_1 = __importDefault(require("node:path"));
const node_util_1 = __importDefault(require("node:util"));
const ts = __importStar(require("typescript"));
const createProjectProgram_1 = require("./create-program/createProjectProgram");
const createSourceFile_1 = require("./create-program/createSourceFile");
const shared_1 = require("./create-program/shared");
const validateDefaultProjectForFilesGlob_1 = require("./create-program/validateDefaultProjectForFilesGlob");
const RELOAD_THROTTLE_MS = 250;
const log = (0, debug_1.default)('typescript-eslint:typescript-estree:useProgramFromProjectService');
const serviceFileExtensions = new WeakMap();
const updateExtraFileExtensions = (service, extraFileExtensions) => {
const currentServiceFileExtensions = serviceFileExtensions.get(service) ?? [];
if (!node_util_1.default.isDeepStrictEqual(currentServiceFileExtensions, extraFileExtensions)) {
log('Updating extra file extensions: before=%s: after=%s', currentServiceFileExtensions, extraFileExtensions);
service.setHostConfiguration({
extraFileExtensions: extraFileExtensions.map(extension => ({
extension,
isMixedContent: false,
scriptKind: ts.ScriptKind.Deferred,
})),
});
serviceFileExtensions.set(service, extraFileExtensions);
log('Extra file extensions updated: %o', extraFileExtensions);
}
};
function openClientFileFromProjectService(defaultProjectMatchedFiles, isDefaultProjectAllowed, filePathAbsolute, parseSettings, serviceAndSettings) {
const opened = openClientFileAndMaybeReload();
log('Result from attempting to open client file: %o', opened);
log('Default project allowed path: %s, based on config file: %s', isDefaultProjectAllowed, opened.configFileName);
if (opened.configFileName) {
if (isDefaultProjectAllowed) {
throw new Error(`${parseSettings.filePath} was included by allowDefaultProject but also was found in the project service. Consider removing it from allowDefaultProject.`);
}
}
else {
const wasNotFound = `${parseSettings.filePath} was not found by the project service`;
const fileExtension = node_path_1.default.extname(parseSettings.filePath);
const extraFileExtensions = parseSettings.extraFileExtensions;
if (!shared_1.DEFAULT_EXTRA_FILE_EXTENSIONS.has(fileExtension) &&
!extraFileExtensions.includes(fileExtension)) {
const nonStandardExt = `${wasNotFound} because the extension for the file (\`${fileExtension}\`) is non-standard`;
if (extraFileExtensions.length > 0) {
throw new Error(`${nonStandardExt}. It should be added to your existing \`parserOptions.extraFileExtensions\`.`);
}
else {
throw new Error(`${nonStandardExt}. You should add \`parserOptions.extraFileExtensions\` to your config.`);
}
}
if (!isDefaultProjectAllowed) {
const baseMessage = `${wasNotFound}. Consider either including it in the tsconfig.json or including it in allowDefaultProject.`;
const allowDefaultProject = parseSettings.projectService?.allowDefaultProject;
if (!allowDefaultProject) {
throw new Error(baseMessage);
}
const relativeFilePath = node_path_1.default.relative(parseSettings.tsconfigRootDir, filePathAbsolute);
throw new Error([
baseMessage,
`allowDefaultProject is set to ${JSON.stringify(allowDefaultProject)}, which does not match '${relativeFilePath}'.`,
].join('\n'));
}
}
// No a configFileName indicates this file wasn't included in a TSConfig.
// That means it must get its type information from the default project.
if (!opened.configFileName) {
defaultProjectMatchedFiles.add(filePathAbsolute);
if (defaultProjectMatchedFiles.size >
serviceAndSettings.maximumDefaultProjectFileMatchCount) {
const filePrintLimit = 20;
const filesToPrint = [...defaultProjectMatchedFiles].slice(0, filePrintLimit);
const truncatedFileCount = defaultProjectMatchedFiles.size - filesToPrint.length;
throw new Error(`Too many files (>${serviceAndSettings.maximumDefaultProjectFileMatchCount}) have matched the default project.${validateDefaultProjectForFilesGlob_1.DEFAULT_PROJECT_FILES_ERROR_EXPLANATION}
Matching files:
${filesToPrint.map(file => `- ${file}`).join('\n')}
${truncatedFileCount ? `...and ${truncatedFileCount} more files\n` : ''}
If you absolutely need more files included, set parserOptions.projectService.maximumDefaultProjectFileMatchCount_THIS_WILL_SLOW_DOWN_LINTING to a larger value.
`);
}
}
return opened;
function openClientFile() {
return serviceAndSettings.service.openClientFile(filePathAbsolute, parseSettings.codeFullText,
/* scriptKind */ undefined, parseSettings.tsconfigRootDir);
}
function openClientFileAndMaybeReload() {
log('Opening project service client file at path: %s', filePathAbsolute);
let opened = openClientFile();
// If no project included the file and we're not in single-run mode,
// we might be running in an editor with outdated file info.
// We can try refreshing the project service - debounced for performance.
if (!opened.configFileErrors &&
!opened.configFileName &&
!parseSettings.singleRun &&
!isDefaultProjectAllowed &&
performance.now() - serviceAndSettings.lastReloadTimestamp >
RELOAD_THROTTLE_MS) {
log('No config file found; reloading project service and retrying.');
serviceAndSettings.service.reloadProjects();
opened = openClientFile();
serviceAndSettings.lastReloadTimestamp = performance.now();
}
return opened;
}
}
function createNoProgramWithProjectService(filePathAbsolute, parseSettings, service) {
log('No project service information available. Creating no program.');
// If the project service knows about this file, this informs if of changes.
// Doing so ensures that:
// - if the file is not part of a project, we don't waste time creating a program (fast non-type-aware linting)
// - otherwise, we refresh the file in the project service (moderately fast, since the project is already loaded)
if (service.getScriptInfo(filePathAbsolute)) {
log('Script info available. Opening client file in project service.');
service.openClientFile(filePathAbsolute, parseSettings.codeFullText,
/* scriptKind */ undefined, parseSettings.tsconfigRootDir);
}
return (0, createSourceFile_1.createNoProgram)(parseSettings);
}
function retrieveASTAndProgramFor(filePathAbsolute, parseSettings, serviceAndSettings) {
log('Retrieving script info and then program for: %s', filePathAbsolute);
const scriptInfo = serviceAndSettings.service.getScriptInfo(filePathAbsolute);
/* eslint-disable @typescript-eslint/no-non-null-assertion */
const program = serviceAndSettings.service
.getDefaultProjectForFile(scriptInfo.fileName, true)
.getLanguageService(/*ensureSynchronized*/ true)
.getProgram();
/* eslint-enable @typescript-eslint/no-non-null-assertion */
if (!program) {
log('Could not find project service program for: %s', filePathAbsolute);
return undefined;
}
log('Found project service program for: %s', filePathAbsolute);
return (0, createProjectProgram_1.createProjectProgram)(parseSettings, [program]);
}
function useProgramFromProjectService(serviceAndSettings, parseSettings, hasFullTypeInformation, defaultProjectMatchedFiles) {
// NOTE: triggers a full project reload when changes are detected
updateExtraFileExtensions(serviceAndSettings.service, parseSettings.extraFileExtensions);
// We don't canonicalize the filename because it caused a performance regression.
// See https://github.com/typescript-eslint/typescript-eslint/issues/8519
const filePathAbsolute = absolutify(parseSettings.filePath, serviceAndSettings);
log('Opening project service file for: %s at absolute path %s', parseSettings.filePath, filePathAbsolute);
const filePathRelative = node_path_1.default.relative(parseSettings.tsconfigRootDir, filePathAbsolute);
const isDefaultProjectAllowed = filePathMatchedBy(filePathRelative, serviceAndSettings.allowDefaultProject);
// Type-aware linting is disabled for this file.
// However, type-aware lint rules might still rely on its contents.
if (!hasFullTypeInformation && !isDefaultProjectAllowed) {
return createNoProgramWithProjectService(filePathAbsolute, parseSettings, serviceAndSettings.service);
}
// If type info was requested, we attempt to open it in the project service.
// By now, the file is known to be one of:
// - in the project service (valid configuration)
// - allowlisted in the default project (valid configuration)
// - neither, which openClientFileFromProjectService will throw an error for
const opened = hasFullTypeInformation &&
openClientFileFromProjectService(defaultProjectMatchedFiles, isDefaultProjectAllowed, filePathAbsolute, parseSettings, serviceAndSettings);
log('Opened project service file: %o', opened);
return retrieveASTAndProgramFor(filePathAbsolute, parseSettings, serviceAndSettings);
}
function absolutify(filePath, serviceAndSettings) {
return node_path_1.default.isAbsolute(filePath)
? filePath
: node_path_1.default.join(serviceAndSettings.service.host.getCurrentDirectory(), filePath);
}
function filePathMatchedBy(filePath, allowDefaultProject) {
return !!allowDefaultProject?.some(pattern => (0, minimatch_1.minimatch)(filePath, pattern, { dot: true }));
}

View File

@@ -0,0 +1 @@
export declare function assert(value: unknown, message?: string): asserts value;

View File

@@ -0,0 +1,35 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// SEE https://typescript-eslint.io/users/configs
//
// For developers working in the typescript-eslint monorepo:
// You can regenerate it using `pnpm run generate-configs`
module.exports = {
extends: ['./configs/eslintrc/base', './configs/eslintrc/eslint-recommended'],
rules: {
'@typescript-eslint/adjacent-overload-signatures': 'error',
'@typescript-eslint/array-type': 'error',
'@typescript-eslint/ban-tslint-comment': 'error',
'@typescript-eslint/class-literal-property-style': 'error',
'@typescript-eslint/consistent-generic-constructors': 'error',
'@typescript-eslint/consistent-indexed-object-style': 'error',
'@typescript-eslint/consistent-type-assertions': 'error',
'@typescript-eslint/consistent-type-definitions': 'error',
'dot-notation': 'off',
'@typescript-eslint/dot-notation': 'error',
'@typescript-eslint/no-confusing-non-null-assertion': 'error',
'no-empty-function': 'off',
'@typescript-eslint/no-empty-function': 'error',
'@typescript-eslint/no-inferrable-types': 'error',
'@typescript-eslint/non-nullable-type-assertion-style': 'error',
'@typescript-eslint/prefer-find': 'error',
'@typescript-eslint/prefer-for-of': 'error',
'@typescript-eslint/prefer-function-type': 'error',
'@typescript-eslint/prefer-includes': 'error',
'@typescript-eslint/prefer-nullish-coalescing': 'error',
'@typescript-eslint/prefer-optional-chain': 'error',
'@typescript-eslint/prefer-regexp-exec': 'error',
'@typescript-eslint/prefer-string-starts-ends-with': 'error',
},
};

View File

@@ -0,0 +1,178 @@
declare module "node:path" {
namespace path {
/**
* A parsed path object generated by path.parse() or consumed by path.format().
*/
interface ParsedPath {
/**
* The root of the path such as '/' or 'c:\'
*/
root: string;
/**
* The full directory path such as '/home/user/dir' or 'c:\path\dir'
*/
dir: string;
/**
* The file name including extension (if any) such as 'index.html'
*/
base: string;
/**
* The file extension (if any) such as '.html'
*/
ext: string;
/**
* The file name without extension (if any) such as 'index'
*/
name: string;
}
interface FormatInputPathObject {
/**
* The root of the path such as '/' or 'c:\'
*/
root?: string | undefined;
/**
* The full directory path such as '/home/user/dir' or 'c:\path\dir'
*/
dir?: string | undefined;
/**
* The file name including extension (if any) such as 'index.html'
*/
base?: string | undefined;
/**
* The file extension (if any) such as '.html'
*/
ext?: string | undefined;
/**
* The file name without extension (if any) such as 'index'
*/
name?: string | undefined;
}
/**
* Normalize a string path, reducing '..' and '.' parts.
* When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. If the path is a zero-length string, '.' is returned, representing the current working directory.
*
* @param path string path to normalize.
* @throws {TypeError} if `path` is not a string.
*/
function normalize(path: string): string;
/**
* Join all arguments together and normalize the resulting path.
*
* @param paths paths to join.
* @throws {TypeError} if any of the path segments is not a string.
*/
function join(...paths: string[]): string;
/**
* The right-most parameter is considered {to}. Other parameters are considered an array of {from}.
*
* Starting from leftmost {from} parameter, resolves {to} to an absolute path.
*
* If {to} isn't already absolute, {from} arguments are prepended in right to left order,
* until an absolute path is found. If after using all {from} paths still no absolute path is found,
* the current working directory is used as well. The resulting path is normalized,
* and trailing slashes are removed unless the path gets resolved to the root directory.
*
* @param paths A sequence of paths or path segments.
* @throws {TypeError} if any of the arguments is not a string.
*/
function resolve(...paths: string[]): string;
/**
* The `path.matchesGlob()` method determines if `path` matches the `pattern`.
* @param path The path to glob-match against.
* @param pattern The glob to check the path against.
* @returns Whether or not the `path` matched the `pattern`.
* @throws {TypeError} if `path` or `pattern` are not strings.
* @since v22.5.0
*/
function matchesGlob(path: string, pattern: string): boolean;
/**
* Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory.
*
* If the given {path} is a zero-length string, `false` will be returned.
*
* @param path path to test.
* @throws {TypeError} if `path` is not a string.
*/
function isAbsolute(path: string): boolean;
/**
* Solve the relative path from {from} to {to} based on the current working directory.
* At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve.
*
* @throws {TypeError} if either `from` or `to` is not a string.
*/
function relative(from: string, to: string): string;
/**
* Return the directory name of a path. Similar to the Unix dirname command.
*
* @param path the path to evaluate.
* @throws {TypeError} if `path` is not a string.
*/
function dirname(path: string): string;
/**
* Return the last portion of a path. Similar to the Unix basename command.
* Often used to extract the file name from a fully qualified path.
*
* @param path the path to evaluate.
* @param suffix optionally, an extension to remove from the result.
* @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string.
*/
function basename(path: string, suffix?: string): string;
/**
* Return the extension of the path, from the last '.' to end of string in the last portion of the path.
* If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string.
*
* @param path the path to evaluate.
* @throws {TypeError} if `path` is not a string.
*/
function extname(path: string): string;
/**
* The platform-specific file separator. '\\' or '/'.
*/
const sep: "\\" | "/";
/**
* The platform-specific file delimiter. ';' or ':'.
*/
const delimiter: ";" | ":";
/**
* Returns an object from a path string - the opposite of format().
*
* @param path path to evaluate.
* @throws {TypeError} if `path` is not a string.
*/
function parse(path: string): ParsedPath;
/**
* Returns a path string from an object - the opposite of parse().
*
* @param pathObject path to evaluate.
*/
function format(pathObject: FormatInputPathObject): string;
/**
* On Windows systems only, returns an equivalent namespace-prefixed path for the given path.
* If path is not a string, path will be returned without modifications.
* This method is meaningful only on Windows system.
* On POSIX systems, the method is non-operational and always returns path without modifications.
*/
function toNamespacedPath(path: string): string;
}
namespace path {
export {
/**
* The `path.posix` property provides access to POSIX specific implementations of the `path` methods.
*
* The API is accessible via `require('node:path').posix` or `require('node:path/posix')`.
*/
path as posix,
/**
* The `path.win32` property provides access to Windows-specific implementations of the `path` methods.
*
* The API is accessible via `require('node:path').win32` or `require('node:path/win32')`.
*/
path as win32,
};
}
export = path;
}
declare module "path" {
import path = require("node:path");
export = path;
}