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,8 @@
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });
} else obj[key] = value;
return obj;
}
export { _define_property as _ };

View File

@@ -0,0 +1,785 @@
import { fileURLToPath, pathToFileURL } from 'node:url';
import vm, { isContext, runInContext } from 'node:vm';
import { dirname, basename, extname, normalize, resolve } from 'pathe';
import { l as loadEnvironment, a as listenForErrors, e as emitModuleRunner } from './init.k9zZ9sLh.js';
import { distDir } from '../path.js';
import { createCustomConsole } from './console.3WNpx0tS.js';
import fs from 'node:fs';
import { createRequire, Module, isBuiltin } from 'node:module';
import { toArray, splitFileAndPostfix, isBareImport } from '@vitest/utils/helpers';
import { findNearestPackageData } from '@vitest/utils/resolver';
import { dirname as dirname$1 } from 'node:path';
import { CSS_LANGS_RE, KNOWN_ASSET_RE } from '@vitest/utils/constants';
import { getDefaultRequestStubs } from '../module-evaluator.js';
import { s as startVitestModuleRunner, V as VITEST_VM_CONTEXT_SYMBOL, c as createNodeImportMeta } from './startVitestModuleRunner.DB-7oCpn.js';
import { p as provideWorkerState } from './utils.BX5Fg8C4.js';
function interopCommonJsModule(interopDefault, mod) {
if (isPrimitive(mod) || Array.isArray(mod) || mod instanceof Promise) return {
keys: [],
moduleExports: {},
defaultExport: mod
};
if (interopDefault !== false && "__esModule" in mod && !isPrimitive(mod.default)) {
const defaultKets = Object.keys(mod.default);
const moduleKeys = Object.keys(mod);
const allKeys = new Set([...defaultKets, ...moduleKeys]);
allKeys.delete("default");
return {
keys: Array.from(allKeys),
moduleExports: new Proxy(mod, { get(mod, prop) {
return mod[prop] ?? mod.default?.[prop];
} }),
defaultExport: mod
};
}
return {
keys: Object.keys(mod).filter((key) => key !== "default"),
moduleExports: mod,
defaultExport: mod
};
}
function isPrimitive(obj) {
return !(obj != null && (typeof obj === "object" || typeof obj === "function"));
}
const SyntheticModule = vm.SyntheticModule;
const SourceTextModule = vm.SourceTextModule;
const _require = createRequire(import.meta.url);
const requiresCache = /* @__PURE__ */ new WeakMap();
class CommonjsExecutor {
context;
requireCache = /* @__PURE__ */ new Map();
publicRequireCache = this.createProxyCache();
moduleCache = /* @__PURE__ */ new Map();
builtinCache = Object.create(null);
extensions = Object.create(null);
fs;
Module;
interopDefault;
constructor(options) {
this.context = options.context;
this.fs = options.fileMap;
this.interopDefault = options.interopDefault;
const primitives = vm.runInContext("({ Object, Array, Error })", this.context);
// eslint-disable-next-line ts/no-this-alias
const executor = this;
this.Module = class Module$1 {
exports;
isPreloading = false;
id;
filename;
loaded;
parent;
children = [];
path;
paths = [];
constructor(id = "", parent) {
this.exports = primitives.Object.create(Object.prototype);
// in our case the path should always be resolved already
this.path = dirname(id);
this.id = id;
this.filename = id;
this.loaded = false;
this.parent = parent;
}
get require() {
const require = requiresCache.get(this);
if (require) return require;
const _require = Module$1.createRequire(this.id);
requiresCache.set(this, _require);
return _require;
}
static getSourceMapsSupport = () => ({
enabled: false,
nodeModules: false,
generatedCode: false
});
static setSourceMapsSupport = () => {
// noop
};
static register = () => {
throw new Error(`[vitest] "register" is not available when running in Vitest.`);
};
static registerHooks = () => {
throw new Error(`[vitest] "registerHooks" is not available when running in Vitest.`);
};
_compile(code, filename) {
const cjsModule = Module$1.wrap(code);
const script = new vm.Script(cjsModule, {
filename,
importModuleDynamically: options.importModuleDynamically
});
// @ts-expect-error mark script with current identifier
script.identifier = filename;
const fn = script.runInContext(executor.context);
const __dirname = dirname(filename);
executor.requireCache.set(filename, this);
try {
fn(this.exports, this.require, this, filename, __dirname);
return this.exports;
} finally {
this.loaded = true;
}
}
// exposed for external use, Node.js does the opposite
static _load = (request, parent, _isMain) => {
return Module$1.createRequire(parent?.filename ?? request)(request);
};
static wrap = (script) => {
return Module$1.wrapper[0] + script + Module$1.wrapper[1];
};
static wrapper = new primitives.Array("(function (exports, require, module, __filename, __dirname) { ", "\n});");
static builtinModules = Module.builtinModules;
static findSourceMap = Module.findSourceMap;
static SourceMap = Module.SourceMap;
static syncBuiltinESMExports = Module.syncBuiltinESMExports;
static _cache = executor.publicRequireCache;
static _extensions = executor.extensions;
static createRequire = (filename) => {
return executor.createRequire(filename);
};
static runMain = () => {
throw new primitives.Error("[vitest] \"runMain\" is not implemented.");
};
// @ts-expect-error not typed
static _resolveFilename = Module._resolveFilename;
// @ts-expect-error not typed
static _findPath = Module._findPath;
// @ts-expect-error not typed
static _initPaths = Module._initPaths;
// @ts-expect-error not typed
static _preloadModules = Module._preloadModules;
// @ts-expect-error not typed
static _resolveLookupPaths = Module._resolveLookupPaths;
// @ts-expect-error not typed
static globalPaths = Module.globalPaths;
static isBuiltin = Module.isBuiltin;
static constants = Module.constants;
static enableCompileCache = Module.enableCompileCache;
static getCompileCacheDir = Module.getCompileCacheDir;
static flushCompileCache = Module.flushCompileCache;
static stripTypeScriptTypes = Module.stripTypeScriptTypes;
static findPackageJSON = Module.findPackageJSON;
static Module = Module$1;
};
this.extensions[".js"] = this.requireJs;
this.extensions[".json"] = this.requireJson;
}
requireJs = (m, filename) => {
const content = this.fs.readFile(filename);
m._compile(content, filename);
};
requireJson = (m, filename) => {
const code = this.fs.readFile(filename);
m.exports = JSON.parse(code);
};
static cjsConditions;
static getCjsConditions() {
if (!CommonjsExecutor.cjsConditions) CommonjsExecutor.cjsConditions = parseCjsConditions(process.execArgv, process.env.NODE_OPTIONS);
return CommonjsExecutor.cjsConditions;
}
createRequire = (filename) => {
const _require = createRequire(filename);
const resolve = (id, options) => {
return _require.resolve(id, {
...options,
conditions: CommonjsExecutor.getCjsConditions()
});
};
const require = ((id) => {
const resolved = resolve(id);
if (extname(resolved) === ".node" || isBuiltin(resolved)) return this.requireCoreModule(resolved);
const module = new this.Module(resolved);
return this.loadCommonJSModule(module, resolved);
});
require.resolve = resolve;
require.resolve.paths = _require.resolve.paths;
Object.defineProperty(require, "extensions", {
get: () => this.extensions,
set: () => {},
configurable: true
});
require.main = void 0;
require.cache = this.publicRequireCache;
return require;
};
createProxyCache() {
return new Proxy(Object.create(null), {
defineProperty: () => true,
deleteProperty: () => true,
set: () => true,
get: (_, key) => this.requireCache.get(key),
has: (_, key) => this.requireCache.has(key),
ownKeys: () => Array.from(this.requireCache.keys()),
getOwnPropertyDescriptor() {
return {
configurable: true,
enumerable: true
};
}
});
}
// very naive implementation for Node.js require
loadCommonJSModule(module, filename) {
const cached = this.requireCache.get(filename);
if (cached) return cached.exports;
const extension = this.findLongestRegisteredExtension(filename);
(this.extensions[extension] || this.extensions[".js"])(module, filename);
return module.exports;
}
findLongestRegisteredExtension(filename) {
const name = basename(filename);
let currentExtension;
let index;
let startIndex = 0;
// eslint-disable-next-line no-cond-assign
while ((index = name.indexOf(".", startIndex)) !== -1) {
startIndex = index + 1;
if (index === 0) continue;
currentExtension = name.slice(index);
if (this.extensions[currentExtension]) return currentExtension;
}
return ".js";
}
getCoreSyntheticModule(identifier) {
if (this.moduleCache.has(identifier)) return this.moduleCache.get(identifier);
const exports$1 = this.require(identifier);
const keys = Object.keys(exports$1);
const module = new SyntheticModule([...keys, "default"], () => {
for (const key of keys) module.setExport(key, exports$1[key]);
module.setExport("default", exports$1);
}, {
context: this.context,
identifier
});
this.moduleCache.set(identifier, module);
return module;
}
getCjsSyntheticModule(path, identifier) {
if (this.moduleCache.has(identifier)) return this.moduleCache.get(identifier);
const exports$1 = this.require(path);
// TODO: technically module should be parsed to find static exports, implement for strict mode in #2854
const { keys, moduleExports, defaultExport } = interopCommonJsModule(this.interopDefault, exports$1);
const module = new SyntheticModule([...keys, "default"], function() {
for (const key of keys) this.setExport(key, moduleExports[key]);
this.setExport("default", defaultExport);
}, {
context: this.context,
identifier
});
this.moduleCache.set(identifier, module);
return module;
}
// TODO: use this in strict mode, when available in #2854
// private _getNamedCjsExports(path: string): Set<string> {
// const cachedNamedExports = this.cjsNamedExportsMap.get(path)
// if (cachedNamedExports) {
// return cachedNamedExports
// }
// if (extname(path) === '.node') {
// const moduleExports = this.require(path)
// const namedExports = new Set(Object.keys(moduleExports))
// this.cjsNamedExportsMap.set(path, namedExports)
// return namedExports
// }
// const code = this.fs.readFile(path)
// const { exports, reexports } = parseCjs(code, path)
// const namedExports = new Set(exports)
// this.cjsNamedExportsMap.set(path, namedExports)
// for (const reexport of reexports) {
// if (isNodeBuiltin(reexport)) {
// const exports = this.require(reexport)
// if (exports !== null && typeof exports === 'object') {
// for (const e of Object.keys(exports)) {
// namedExports.add(e)
// }
// }
// }
// else {
// const require = this.createRequire(path)
// const resolved = require.resolve(reexport)
// const exports = this._getNamedCjsExports(resolved)
// for (const e of exports) {
// namedExports.add(e)
// }
// }
// }
// return namedExports
// }
require(identifier) {
if (extname(identifier) === ".node" || isBuiltin(identifier)) return this.requireCoreModule(identifier);
const module = new this.Module(identifier);
return this.loadCommonJSModule(module, identifier);
}
requireCoreModule(identifier) {
const normalized = identifier.replace(/^node:/, "");
if (this.builtinCache[normalized]) return this.builtinCache[normalized].exports;
const moduleExports = _require(identifier);
if (identifier === "node:module" || identifier === "module") {
const module = new this.Module("/module.js");
module.exports = this.Module;
this.builtinCache[normalized] = module;
return module.exports;
}
this.builtinCache[normalized] = _require.cache[normalized];
// TODO: should we wrap module to rethrow context errors?
return moduleExports;
}
}
// The "module-sync" exports condition (added in Node 22.12/20.19 when
// require(esm) was unflagged) can resolve to ESM files that our CJS
// vm.Script executor cannot handle. We exclude it by passing explicit
// CJS conditions to require.resolve (Node 22.12+).
// Must be a Set because Node's internal resolver calls conditions.has().
// User-specified --conditions/-C flags are respected, except module-sync.
function parseCjsConditions(execArgv, nodeOptions) {
const conditions = [
"node",
"require",
"node-addons"
];
const args = [...execArgv, ...nodeOptions?.split(/\s+/) ?? []];
for (let i = 0; i < args.length; i++) {
const arg = args[i];
const eqMatch = arg.match(/^(?:--conditions|-C)=(.+)$/);
if (eqMatch) conditions.push(eqMatch[1]);
else if ((arg === "--conditions" || arg === "-C") && i + 1 < args.length) conditions.push(args[++i]);
}
return new Set(conditions.filter((c) => c !== "module-sync"));
}
const dataURIRegex = /^data:(?<mime>text\/javascript|application\/json|application\/wasm)(?:;(?<encoding>charset=utf-8|base64))?,(?<code>.*)$/;
class EsmExecutor {
moduleCache = /* @__PURE__ */ new Map();
esmLinkMap = /* @__PURE__ */ new WeakMap();
context;
#httpIp = IPnumber("127.0.0.0");
constructor(executor, options) {
this.executor = executor;
this.context = options.context;
}
async evaluateModule(m) {
if (m.status === "unlinked") this.esmLinkMap.set(m, m.link((identifier, referencer) => this.executor.resolveModule(identifier, referencer.identifier)));
await this.esmLinkMap.get(m);
if (m.status === "linked") await m.evaluate();
return m;
}
async createEsModule(fileURL, getCode) {
const cached = this.moduleCache.get(fileURL);
if (cached) return cached;
const promise = this.loadEsModule(fileURL, getCode);
this.moduleCache.set(fileURL, promise);
return promise;
}
async loadEsModule(fileURL, getCode) {
const code = await getCode();
// TODO: should not be allowed in strict mode, implement in #2854
if (fileURL.endsWith(".json")) {
const m = new SyntheticModule(["default"], function() {
const result = JSON.parse(code);
this.setExport("default", result);
});
this.moduleCache.set(fileURL, m);
return m;
}
const m = new SourceTextModule(code, {
identifier: fileURL,
context: this.context,
importModuleDynamically: this.executor.importModuleDynamically,
initializeImportMeta: (meta, mod) => {
meta.url = mod.identifier;
if (mod.identifier.startsWith("file:")) {
const filename = fileURLToPath(mod.identifier);
meta.filename = filename;
meta.dirname = dirname$1(filename);
}
meta.resolve = (specifier, importer) => {
return this.executor.resolve(specifier, importer != null ? importer.toString() : mod.identifier);
};
}
});
this.moduleCache.set(fileURL, m);
return m;
}
async createWebAssemblyModule(fileUrl, getCode) {
const cached = this.moduleCache.get(fileUrl);
if (cached) return cached;
const m = this.loadWebAssemblyModule(getCode(), fileUrl);
this.moduleCache.set(fileUrl, m);
return m;
}
async createNetworkModule(fileUrl) {
// https://nodejs.org/api/esm.html#https-and-http-imports
if (fileUrl.startsWith("http:")) {
const url = new URL(fileUrl);
if (url.hostname !== "localhost" && url.hostname !== "::1" && (IPnumber(url.hostname) & IPmask(8)) !== this.#httpIp) throw new Error(
// we don't know the importer, so it's undefined (the same happens in --pool=threads)
`import of '${fileUrl}' by undefined is not supported: http can only be used to load local resources (use https instead).`
);
}
return this.createEsModule(fileUrl, () => fetch(fileUrl).then((r) => r.text()));
}
async loadWebAssemblyModule(source, identifier) {
const cached = this.moduleCache.get(identifier);
if (cached) return cached;
const wasmModule = await WebAssembly.compile(source);
const exports$1 = WebAssembly.Module.exports(wasmModule);
const imports = WebAssembly.Module.imports(wasmModule);
const moduleLookup = {};
for (const { module } of imports) if (moduleLookup[module] === void 0) moduleLookup[module] = await this.executor.resolveModule(module, identifier);
const evaluateModule = (module) => this.evaluateModule(module);
return new SyntheticModule(exports$1.map(({ name }) => name), async function() {
const importsObject = {};
for (const { module, name } of imports) {
if (!importsObject[module]) importsObject[module] = {};
await evaluateModule(moduleLookup[module]);
importsObject[module][name] = moduleLookup[module].namespace[name];
}
const wasmInstance = new WebAssembly.Instance(wasmModule, importsObject);
for (const { name } of exports$1) this.setExport(name, wasmInstance.exports[name]);
}, {
context: this.context,
identifier
});
}
cacheModule(identifier, module) {
this.moduleCache.set(identifier, module);
}
resolveCachedModule(identifier) {
return this.moduleCache.get(identifier);
}
async createDataModule(identifier) {
const cached = this.moduleCache.get(identifier);
if (cached) return cached;
const match = identifier.match(dataURIRegex);
if (!match || !match.groups) throw new Error("Invalid data URI");
const mime = match.groups.mime;
const encoding = match.groups.encoding;
if (mime === "application/wasm") {
if (!encoding) throw new Error("Missing data URI encoding");
if (encoding !== "base64") throw new Error(`Invalid data URI encoding: ${encoding}`);
const module = this.loadWebAssemblyModule(Buffer.from(match.groups.code, "base64"), identifier);
this.moduleCache.set(identifier, module);
return module;
}
let code = match.groups.code;
if (!encoding || encoding === "charset=utf-8") code = decodeURIComponent(code);
else if (encoding === "base64") code = Buffer.from(code, "base64").toString();
else throw new Error(`Invalid data URI encoding: ${encoding}`);
if (mime === "application/json") {
const module = new SyntheticModule(["default"], function() {
const obj = JSON.parse(code);
this.setExport("default", obj);
}, {
context: this.context,
identifier
});
this.moduleCache.set(identifier, module);
return module;
}
return this.createEsModule(identifier, () => code);
}
}
function IPnumber(address) {
const ip = address.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
if (ip) return (+ip[1] << 24) + (+ip[2] << 16) + (+ip[3] << 8) + +ip[4];
throw new Error(`Expected IP address, received ${address}`);
}
function IPmask(maskSize) {
return -1 << 32 - maskSize;
}
const CLIENT_ID = "/@vite/client";
const CLIENT_FILE = pathToFileURL(CLIENT_ID).href;
class ViteExecutor {
esm;
constructor(options) {
this.options = options;
this.esm = options.esmExecutor;
}
resolve = (identifier) => {
if (identifier === CLIENT_ID) return identifier;
};
get workerState() {
return this.options.context.__vitest_worker__;
}
async createViteModule(fileUrl) {
if (fileUrl === CLIENT_FILE || fileUrl === CLIENT_ID) return this.createViteClientModule();
const cached = this.esm.resolveCachedModule(fileUrl);
if (cached) return cached;
return this.esm.createEsModule(fileUrl, async () => {
try {
const result = await this.options.transform(fileUrl);
if (result.code) return result.code;
} catch (cause) {
// rethrow vite error if it cannot load the module because it's not resolved
if (typeof cause === "object" && cause.code === "ERR_LOAD_URL" || typeof cause?.message === "string" && cause.message.includes("Failed to load url")) {
const error = new Error(`Cannot find module '${fileUrl}'`, { cause });
error.code = "ERR_MODULE_NOT_FOUND";
throw error;
}
}
throw new Error(`[vitest] Failed to transform ${fileUrl}. Does the file exist?`);
});
}
createViteClientModule() {
const identifier = CLIENT_ID;
const cached = this.esm.resolveCachedModule(identifier);
if (cached) return cached;
const stub = this.options.viteClientModule;
const moduleKeys = Object.keys(stub);
const module = new SyntheticModule(moduleKeys, function() {
moduleKeys.forEach((key) => {
this.setExport(key, stub[key]);
});
}, {
context: this.options.context,
identifier
});
this.esm.cacheModule(identifier, module);
return module;
}
canResolve = (fileUrl) => {
if (fileUrl === CLIENT_FILE) return true;
const config = this.workerState.config.deps?.web || {};
const [modulePath] = fileUrl.split("?");
if (config.transformCss && CSS_LANGS_RE.test(modulePath)) return true;
if (config.transformAssets && KNOWN_ASSET_RE.test(modulePath)) return true;
if (toArray(config.transformGlobPattern).some((pattern) => pattern.test(modulePath))) return true;
return false;
};
}
const { existsSync } = fs;
// always defined when we use vm pool
const nativeResolve = import.meta.resolve;
// TODO: improve Node.js strict mode support in #2854
class ExternalModulesExecutor {
cjs;
esm;
vite;
context;
fs;
resolvers = [];
#networkSupported = null;
constructor(options) {
this.options = options;
this.context = options.context;
this.fs = options.fileMap;
this.esm = new EsmExecutor(this, { context: this.context });
this.cjs = new CommonjsExecutor({
context: this.context,
importModuleDynamically: this.importModuleDynamically,
fileMap: options.fileMap,
interopDefault: options.interopDefault
});
this.vite = new ViteExecutor({
esmExecutor: this.esm,
context: this.context,
transform: options.transform,
viteClientModule: options.viteClientModule
});
this.resolvers = [this.vite.resolve];
}
async import(identifier) {
const module = await this.createModule(identifier);
await this.esm.evaluateModule(module);
return module.namespace;
}
require(identifier) {
return this.cjs.require(identifier);
}
createRequire(identifier) {
return this.cjs.createRequire(identifier);
}
// dynamic import can be used in both ESM and CJS, so we have it in the executor
importModuleDynamically = async (specifier, referencer) => {
const module = await this.resolveModule(specifier, referencer.identifier);
return await this.esm.evaluateModule(module);
};
resolveModule = async (specifier, referencer) => {
let identifier = this.resolve(specifier, referencer);
if (identifier instanceof Promise) identifier = await identifier;
return await this.createModule(identifier);
};
resolve(specifier, parent) {
for (const resolver of this.resolvers) {
const id = resolver(specifier, parent);
if (id) return id;
}
// import.meta.resolve can be asynchronous in older +18 Node versions
return nativeResolve(specifier, parent);
}
getModuleInformation(identifier) {
if (identifier.startsWith("data:")) return {
type: "data",
url: identifier,
path: identifier
};
const { file, postfix } = splitFileAndPostfix(identifier);
const extension = extname(file);
if (extension === ".node" || isBuiltin(identifier)) return {
type: "builtin",
url: identifier,
path: identifier
};
if (this.isNetworkSupported && (identifier.startsWith("http:") || identifier.startsWith("https:"))) return {
type: "network",
url: identifier,
path: identifier
};
const isFileUrl = identifier.startsWith("file://");
const pathUrl = isFileUrl ? fileURLToPath(file) : file;
const fileUrl = isFileUrl ? identifier : `${pathToFileURL(file)}${postfix}`;
let type;
if (this.vite.canResolve(fileUrl)) type = "vite";
else if (extension === ".mjs") type = "module";
else if (extension === ".cjs") type = "commonjs";
else if (extension === ".wasm")
// still experimental on NodeJS --experimental-wasm-modules
// cf. ESM_FILE_FORMAT(url) in https://nodejs.org/docs/latest-v20.x/api/esm.html#resolution-algorithm
type = "wasm";
else type = findNearestPackageData(normalize(pathUrl)).type === "module" ? "module" : "commonjs";
return {
type,
path: pathUrl,
url: fileUrl
};
}
createModule(identifier) {
const { type, url, path } = this.getModuleInformation(identifier);
// create ERR_MODULE_NOT_FOUND on our own since latest NodeJS's import.meta.resolve doesn't throw on non-existing namespace or path
// https://github.com/nodejs/node/pull/49038
if ((type === "module" || type === "commonjs" || type === "wasm") && !existsSync(path)) {
const error = /* @__PURE__ */ new Error(`Cannot find ${isBareImport(path) ? "package" : "module"} '${path}'`);
error.code = "ERR_MODULE_NOT_FOUND";
throw error;
}
switch (type) {
case "data": return this.esm.createDataModule(identifier);
case "builtin": return this.cjs.getCoreSyntheticModule(identifier);
case "vite": return this.vite.createViteModule(url);
case "wasm": return this.esm.createWebAssemblyModule(url, () => this.fs.readBuffer(path));
case "module": return this.esm.createEsModule(url, () => this.fs.readFileAsync(path));
case "commonjs": return this.cjs.getCjsSyntheticModule(path, identifier);
case "network": return this.esm.createNetworkModule(url);
default: return type;
}
}
get isNetworkSupported() {
if (this.#networkSupported == null) if (process.execArgv.includes("--experimental-network-imports")) this.#networkSupported = true;
else if (process.env.NODE_OPTIONS?.includes("--experimental-network-imports")) this.#networkSupported = true;
else this.#networkSupported = false;
return this.#networkSupported;
}
}
const { promises, readFileSync } = fs;
class FileMap {
fsCache = /* @__PURE__ */ new Map();
fsBufferCache = /* @__PURE__ */ new Map();
async readFileAsync(path) {
const cached = this.fsCache.get(path);
if (cached != null) return cached;
const source = await promises.readFile(path, "utf-8");
this.fsCache.set(path, source);
return source;
}
readFile(path) {
const cached = this.fsCache.get(path);
if (cached != null) return cached;
const source = readFileSync(path, "utf-8");
this.fsCache.set(path, source);
return source;
}
readBuffer(path) {
const cached = this.fsBufferCache.get(path);
if (cached != null) return cached;
const buffer = readFileSync(path);
this.fsBufferCache.set(path, buffer);
return buffer;
}
}
const entryFile = pathToFileURL(resolve(distDir, "workers/runVmTests.js")).href;
const fileMap = new FileMap();
const packageCache = /* @__PURE__ */ new Map();
async function runVmTests(method, state, traces) {
const { ctx, rpc } = state;
const beforeEnvironmentTime = performance.now();
const { environment } = await loadEnvironment(ctx.environment.name, ctx.config.root, rpc, traces, true);
state.environment = environment;
if (!environment.setupVM) {
const envName = ctx.environment.name;
const packageId = envName[0] === "." ? envName : `vitest-environment-${envName}`;
throw new TypeError(`Environment "${ctx.environment.name}" is not a valid environment. Path "${packageId}" doesn't support vm environment because it doesn't provide "setupVM" method.`);
}
const vm = await traces.$("vitest.runtime.environment.setup", { attributes: {
"vitest.environment": environment.name,
"vitest.environment.vite_environment": environment.viteEnvironment || environment.name
} }, () => environment.setupVM(ctx.environment.options || ctx.config.environmentOptions || {}));
state.durations.environment = performance.now() - beforeEnvironmentTime;
process.env.VITEST_VM_POOL = "1";
if (!vm.getVmContext) throw new TypeError(`Environment ${environment.name} doesn't provide "getVmContext" method. It should return a context created by "vm.createContext" method.`);
const context = vm.getVmContext();
if (!isContext(context)) throw new TypeError(`Environment ${environment.name} doesn't provide a valid context. It should be created by "vm.createContext" method.`);
provideWorkerState(context, state);
// this is unfortunately needed for our own dependencies
// we need to find a way to not rely on this by default
// because browser doesn't provide these globals
context.process = process;
context.global = context;
context.console = state.config.disableConsoleIntercept ? console : createCustomConsole(state);
// TODO: don't hardcode setImmediate in fake timers defaults
context.setImmediate = setImmediate;
context.clearImmediate = clearImmediate;
const stubs = getDefaultRequestStubs(context);
const externalModulesExecutor = new ExternalModulesExecutor({
context,
fileMap,
packageCache,
transform: rpc.transform,
viteClientModule: stubs["/@vite/client"]
});
process.exit = (code = process.exitCode || 0) => {
throw new Error(`process.exit unexpectedly called with "${code}"`);
};
listenForErrors(() => state);
const moduleRunner = startVitestModuleRunner({
context,
evaluatedModules: state.evaluatedModules,
state,
externalModulesExecutor,
createImportMeta: createNodeImportMeta,
traces
});
emitModuleRunner(moduleRunner);
Object.defineProperty(context, VITEST_VM_CONTEXT_SYMBOL, {
value: {
context,
externalModulesExecutor
},
configurable: true,
enumerable: false,
writable: false
});
context.__vitest_mocker__ = moduleRunner.mocker;
if (ctx.config.serializedDefines) try {
runInContext(ctx.config.serializedDefines, context, { filename: "virtual:load-defines.js" });
} catch (error) {
throw new Error(`Failed to load custom "defines": ${error.message}`);
}
await moduleRunner.mocker.initializeSpyModule();
const { run } = await moduleRunner.import(entryFile);
try {
await run(method, ctx.files, ctx.config, moduleRunner, traces);
} finally {
await traces.$("vitest.runtime.environment.teardown", () => vm.teardown?.());
}
}
function setupVmWorker(context) {
if (context.config.experimental.viteModuleRunner === false) throw new Error(`Pool "${context.pool}" cannot run with "experimental.viteModuleRunner: false". Please, use "threads" or "forks" instead.`);
}
export { runVmTests as r, setupVmWorker as s };

View File

@@ -0,0 +1 @@
{"version":3,"file":"_assert.d.ts","sourceRoot":"","sources":["src/_assert.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACL,MAAM,IAAI,EAAE,EACZ,OAAO,IAAI,EAAE,EACb,OAAO,IAAI,EAAE,EACb,OAAO,IAAI,EAAE,EACb,KAAK,KAAK,IAAI,CAAC,EAChB,MAAM,YAAY,CAAC;AACpB,8DAA8D;AAC9D,eAAO,MAAM,MAAM,EAAE,OAAO,EAAO,CAAC;AACpC,8DAA8D;AAC9D,eAAO,MAAM,OAAO,EAAE,OAAO,EAAO,CAAC;AACrC,8DAA8D;AAC9D,eAAO,MAAM,OAAO,EAAE,OAAO,EAAO,CAAC;AACrC,8DAA8D;AAC9D,eAAO,MAAM,OAAO,EAAE,OAAO,EAAO,CAAC;AACrC,8DAA8D;AAC9D,MAAM,MAAM,IAAI,GAAG,CAAC,CAAC"}

View File

@@ -0,0 +1,11 @@
export declare enum ScriptKind {
Unknown = 0,
JS = 1,
JSX = 2,
TS = 3,
TSX = 4,
External = 5,
JSON = 6,
Deferred = 7
}
//# sourceMappingURL=scriptKind.enum.d.ts.map

View File

@@ -0,0 +1,112 @@
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: "თარიღი-დრო",
date: "თარიღი",
time: "დრო",
duration: "ხანგრძლივობა",
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: "რიცხვი",
string: "ველი",
boolean: "ბულეანი",
function: "ფუნქცია",
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 ?? "მნიშვნელობა"} ${sizing.verb} ${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} ${sizing.verb} ${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}`;
return `არასწორი ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `არასწორი რიცხვი: უნდა იყოს ${issue.divisor}-ის ჯერადი`;
case "unrecognized_keys":
return `უცნობი გასაღებ${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,7 @@
import { resolve } from 'node:path';
import url from 'node:url';
const rootDir = resolve(url.fileURLToPath(import.meta.url), "../../");
const distDir = resolve(url.fileURLToPath(import.meta.url), "../../dist");
export { distDir, rootDir };

View File

@@ -0,0 +1,687 @@
/**
* @fileoverview Rule to preserve caught errors when re-throwing exceptions
* @author Amnish Singh Arora
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Types
//------------------------------------------------------------------------------
/** @typedef {import("estree").Node} ASTNode */
/** @typedef {import("eslint").Rule.Fix} Fix */
/** @typedef {import("eslint").Rule.RuleFixer} RuleFixer */
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/*
* This is an indicator of an error cause node, that is too complicated to be detected and fixed.
* Eg, when error options is an `Identifier` or a `SpreadElement`.
*/
const UNKNOWN_CAUSE = Symbol("unknown_cause");
const BUILT_IN_ERROR_TYPES = new Set([
"Error",
"EvalError",
"RangeError",
"ReferenceError",
"SyntaxError",
"TypeError",
"URIError",
"AggregateError",
]);
/**
* Finds and returns information about the `cause` property of an error being thrown.
* @param {ASTNode} throwStatement `ThrowStatement` to be checked.
* @param {number} optionsIndex The index of the options argument in the error constructor.
* @returns {{ value: ASTNode; multipleDefinitions: boolean; } | UNKNOWN_CAUSE | null}
* Information about the `cause` of the error being thrown, such as the value node and
* whether there are multiple definitions of `cause`. `null` if there is no `cause`.
*/
function getErrorCause(throwStatement, optionsIndex) {
const throwExpression = throwStatement.argument;
/*
* Make sure there is no `SpreadElement` at or before the `optionsIndex`
* as this messes up the effective order of arguments and makes it complicated
* to track where the actual error options need to be at
*/
const spreadExpressionIndex = throwExpression.arguments.findIndex(
arg => arg.type === "SpreadElement",
);
if (spreadExpressionIndex >= 0 && spreadExpressionIndex <= optionsIndex) {
return UNKNOWN_CAUSE;
}
const errorOptions = throwExpression.arguments[optionsIndex];
if (errorOptions) {
if (errorOptions.type === "ObjectExpression") {
if (
errorOptions.properties.some(
prop => prop.type === "SpreadElement",
)
) {
/*
* If there is a spread element as part of error options, it is too complicated
* to verify if the cause is used properly and auto-fix.
*/
return UNKNOWN_CAUSE;
}
const causeProperties = errorOptions.properties.filter(
prop => astUtils.getStaticPropertyName(prop) === "cause",
);
const causeProperty = causeProperties.at(-1);
return causeProperty
? {
value: causeProperty.value,
multipleDefinitions: causeProperties.length > 1,
}
: null;
}
// Error options exist, but too complicated to be analyzed/fixed
return UNKNOWN_CAUSE;
}
return null;
}
/**
* Finds and returns the `CatchClause` node, that the `node` is part of.
* @param {ASTNode} node The AST node to be evaluated.
* @returns {ASTNode | null } The closest parent `CatchClause` node, `null` if the `node` is not in a catch block.
*/
function findParentCatch(node) {
let currentNode = node;
while (currentNode && currentNode.type !== "CatchClause") {
if (
[
"FunctionDeclaration",
"FunctionExpression",
"ArrowFunctionExpression",
"StaticBlock",
].includes(currentNode.type)
) {
/*
* Make sure the ThrowStatement is not made inside a function definition or a static block inside a high level catch.
* In such cases, the caught error is not directly related to the Throw.
*
* For example,
* try {
* } catch (error) {
* foo = {
* bar() {
* throw new Error();
* }
* };
* }
*/
return null;
}
currentNode = currentNode.parent;
}
return currentNode;
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
defaultOptions: [
{
requireCatchParameter: false,
errorClassNames: [],
},
],
docs: {
description:
"Disallow losing originally caught error when re-throwing custom errors",
recommended: true,
url: "https://eslint.org/docs/latest/rules/preserve-caught-error", // URL to the documentation page for this rule
},
schema: [
{
type: "object",
properties: {
requireCatchParameter: {
type: "boolean",
description:
"Requires the catch blocks to always have the caught error parameter so it is not discarded.",
},
errorClassNames: {
type: "array",
description:
"Additional error class names to check for cause preservation.",
items: {
oneOf: [
{
type: "string",
},
{
type: "object",
required: ["name", "argumentPosition"],
properties: {
name: {
type: "string",
},
argumentPosition: {
type: "integer",
minimum: 1,
},
},
additionalProperties: false,
},
],
},
uniqueItems: true,
},
},
additionalProperties: false,
},
],
messages: {
missingCause:
"There is no `cause` attached to the symptom error being thrown.",
incorrectCause:
"The symptom error is being thrown with an incorrect `cause`.",
includeCause:
"Include the original caught error as the `cause` of the symptom error.",
missingCatchErrorParam:
"The caught error is not accessible because the catch clause lacks the error parameter. Start referencing the caught error using the catch parameter.",
partiallyLostError:
"Re-throws cannot preserve the caught error as a part of it is being lost due to destructuring.",
caughtErrorShadowed:
"The caught error is being attached as `cause`, but is shadowed by a closer scoped redeclaration.",
},
hasSuggestions: true,
},
create(context) {
const sourceCode = context.sourceCode;
const [{ requireCatchParameter, errorClassNames }] = context.options;
const errorClassNamesMap = new Map();
for (const item of errorClassNames) {
const name = typeof item === "string" ? item : item.name;
const argumentPosition =
typeof item === "string" ? 2 : item.argumentPosition;
errorClassNamesMap.set(name, argumentPosition);
}
//----------------------------------------------------------------------
// Helpers
//----------------------------------------------------------------------
/**
* Checks if the given callee refers to a built-in global Error constructor.
* @param {ASTNode} callee The callee node.
* @returns {boolean} `true` if the callee is a built-in global Error constructor.
*/
function isBuiltInGlobalError(callee) {
return (
callee.type === "Identifier" &&
BUILT_IN_ERROR_TYPES.has(callee.name) &&
sourceCode.isGlobalReference(callee)
);
}
/**
* Checks if a `ThrowStatement` is constructing and throwing a new `Error` object.
*
* Covers all the error types on `globalThis` that support `cause` property:
* https://github.com/microsoft/TypeScript/blob/main/src/lib/es2022.error.d.ts
* @param {ASTNode} throwStatement The `ThrowStatement` that needs to be checked.
* @returns {boolean} `true` if a new "Error" is being thrown, else `false`.
*/
function isThrowingNewError(throwStatement) {
if (!(
throwStatement.argument.type === "NewExpression" ||
throwStatement.argument.type === "CallExpression"
)) {
return false;
}
const callee = throwStatement.argument.callee;
/*
* Make sure the thrown Error instance is one of the built-in global error types.
* Custom imports could shadow this, which would lead to false positives.
* e.g. import { Error } from "./my-custom-error.js";
* throw Error("Failed to perform error prone operations");
*/
if (isBuiltInGlobalError(callee)) {
return true;
}
const target =
callee.type === "MemberExpression" && !callee.computed
? callee.property
: callee;
return (
target.type === "Identifier" &&
errorClassNamesMap.has(target.name)
);
}
/**
* Inserts `cause: <caughtErrorName>` into an inline options object expression.
* @param {RuleFixer} fixer The fixer object.
* @param {ASTNode} optionsNode The options object node.
* @param {string} caughtErrorName The name of the caught error (e.g., "err").
* @returns {Fix} The fix object.
*/
function insertCauseIntoOptions(fixer, optionsNode, caughtErrorName) {
const properties = optionsNode.properties;
if (properties.length === 0) {
// Insert inside empty braces: `{}` → `{ cause: err }`
return fixer.insertTextAfter(
sourceCode.getFirstToken(optionsNode),
`cause: ${caughtErrorName}`,
);
}
const lastProp = properties.at(-1);
return fixer.insertTextAfter(
lastProp,
`, cause: ${caughtErrorName}`,
);
}
/**
* Finds the first token that isn't followed by a closing parenthesis in a specified range.
* This is the token after which new arguments should be inserted.
* @param {Token} firstToken The first token to start searching from.
* @param {Token} lastToken The last token to scan up to (inclusive).
* @returns {Token} The first token that isn't followed by a closing parenthesis, or `lastToken` if none is found.
*/
function findInsertionTokenAfterParens(firstToken, lastToken) {
const lastIndex = lastToken.range[1];
let token = firstToken;
let nextToken = sourceCode.getTokenAfter(token);
while (
nextToken.range[1] <= lastIndex &&
astUtils.isClosingParenToken(nextToken)
) {
token = nextToken;
nextToken = sourceCode.getTokenAfter(token);
}
return token;
}
/**
* Adds arguments for a call/new expression with no arguments.
* Works for `new Error`, `new (Error)`, and forms that already include empty argument parentheses.
* @param {RuleFixer} fixer The fixer instance.
* @param {ASTNode & { callee: ASTNode }} throwExpression The thrown CallExpression or NewExpression node.
* @param {string} text The arguments to insert.
* @returns {Fix} The fixer operation.
*/
function addArgumentsToEmptyCall(fixer, throwExpression, text) {
const callClosingParenToken =
sourceCode.getLastToken(throwExpression);
const lastCalleeToken = sourceCode.getLastToken(
throwExpression.callee,
);
const parenToken = sourceCode.getFirstTokenBetween(
lastCalleeToken,
callClosingParenToken,
astUtils.isOpeningParenToken,
);
if (parenToken) {
return fixer.insertTextAfter(parenToken, text);
}
const insertionToken = findInsertionTokenAfterParens(
lastCalleeToken,
callClosingParenToken,
);
return fixer.insertTextAfter(insertionToken, `(${text})`);
}
/**
* Appends additional arguments after the last argument of a call/new expression,
* accounting for any wrapping parentheses around that argument.
* @param {RuleFixer} fixer The fixer instance.
* @param {ASTNode & { arguments: ASTNode[] }} throwExpression The thrown CallExpression or NewExpression node.
* @param {string} text The additional arguments to insert, including the leading comma.
* @returns {Fix} The fixer operation.
*/
function appendArguments(fixer, throwExpression, text) {
const lastArgument = throwExpression.arguments.at(-1);
const lastArgumentToken = sourceCode.getLastToken(lastArgument);
const lastTokenBeforeArgListParen = sourceCode.getLastToken(
throwExpression,
{ skip: 1 },
);
const insertionToken = findInsertionTokenAfterParens(
lastArgumentToken,
lastTokenBeforeArgListParen,
);
return fixer.insertTextAfter(insertionToken, text);
}
//----------------------------------------------------------------------
// Public
//----------------------------------------------------------------------
return {
ThrowStatement(node) {
// Check if the throw is inside a catch block
const parentCatch = findParentCatch(node);
const throwStatement = node;
// Check if a new error is being thrown in a catch block
if (parentCatch && isThrowingNewError(throwStatement)) {
if (
parentCatch.param &&
parentCatch.param.type !== "Identifier"
) {
/*
* When a part of the caught error is being lost at the parameter level, commonly due to destructuring.
* e.g. catch({ message, ...rest })
*/
context.report({
messageId: "partiallyLostError",
node: parentCatch,
});
return;
}
const caughtError =
parentCatch.param?.type === "Identifier"
? parentCatch.param
: null;
// Check if there are throw statements and caught error is being ignored
if (!caughtError) {
if (requireCatchParameter) {
context.report({
node: throwStatement,
messageId: "missingCatchErrorParam",
});
return;
}
return;
}
// Determine the options argument index
const callee = throwStatement.argument.callee;
const errorClassName =
callee.type === "Identifier"
? callee.name
: callee.property.name;
const builtInGlobalError = isBuiltInGlobalError(callee);
let optionsIndex;
if (builtInGlobalError) {
optionsIndex =
errorClassName === "AggregateError" ? 2 : 1;
} else {
const argumentPosition =
errorClassNamesMap.get(errorClassName);
optionsIndex = argumentPosition - 1;
}
// Check if there is a cause attached to the new error
const errorCauseInfo = getErrorCause(
throwStatement,
optionsIndex,
);
if (errorCauseInfo === UNKNOWN_CAUSE) {
// Error options exist, but too complicated to be analyzed/fixed
return;
}
if (errorCauseInfo === null) {
// If there is no `cause` attached to the error being thrown.
context.report({
messageId: "missingCause",
node: throwStatement,
suggest: [
{
messageId: "includeCause",
fix(fixer) {
const throwExpression =
throwStatement.argument;
const args = throwExpression.arguments;
/**
* Inserts `cause` into the options argument if it is an `ObjectExpression`.
* @param {ASTNode} optionsArg The options argument node.
* @returns {Fix | null} The fix, or `null` if the argument is not an object.
*/
function fixExistingOptions(
optionsArg,
) {
if (
optionsArg.type ===
"ObjectExpression"
) {
return insertCauseIntoOptions(
fixer,
optionsArg,
caughtError.name,
);
}
return null;
}
// AggregateError: errors, message, options
if (
builtInGlobalError &&
errorClassName === "AggregateError"
) {
const errorsArg = args[0];
const messageArg = args[1];
const optionsArg = args[2];
if (!errorsArg) {
// Case: `throw new AggregateError()` → insert all arguments
return addArgumentsToEmptyCall(
fixer,
throwExpression,
`[], "", { cause: ${caughtError.name} }`,
);
}
if (!messageArg) {
// Case: `throw new AggregateError([])` → insert message and options
return appendArguments(
fixer,
throwExpression,
`, "", { cause: ${caughtError.name} }`,
);
}
if (!optionsArg) {
// Case: `throw new AggregateError([], "")` → insert error options only
return appendArguments(
fixer,
throwExpression,
`, { cause: ${caughtError.name} }`,
);
}
return fixExistingOptions(
optionsArg,
);
}
// Normal Error types
if (builtInGlobalError) {
const messageArg = args[0];
const optionsArg = args[1];
if (!messageArg) {
// Case: `throw new Error()` → insert both message and options
return addArgumentsToEmptyCall(
fixer,
throwExpression,
`"", { cause: ${caughtError.name} }`,
);
}
if (!optionsArg) {
// Case: `throw new Error("Some message")` → insert only options
return appendArguments(
fixer,
throwExpression,
`, { cause: ${caughtError.name} }`,
);
}
return fixExistingOptions(
optionsArg,
);
}
// Custom error types
const optionsArg = args[optionsIndex];
/*
* Custom error signature is unknown, so skip the suggestion rather
* than synthesize placeholder values for missing positional args.
*/
if (args.length < optionsIndex) {
return null;
}
if (!optionsArg) {
const lastProvidedArg = args.at(-1);
if (lastProvidedArg) {
// Options slot missing, all prior args provided → append options
return appendArguments(
fixer,
throwExpression,
`, { cause: ${caughtError.name} }`,
);
}
// argumentPosition: 1 and no args → insert options inside parens
return addArgumentsToEmptyCall(
fixer,
throwExpression,
`{ cause: ${caughtError.name} }`,
);
}
return fixExistingOptions(optionsArg);
},
},
],
});
// We don't need to check further
return;
}
const { value: thrownErrorCause } = errorCauseInfo;
// If there is an attached cause, verify that it matches the caught error
if (!(
thrownErrorCause.type === "Identifier" &&
thrownErrorCause.name === caughtError.name
)) {
const suggest = errorCauseInfo.multipleDefinitions
? null // If there are multiple `cause` definitions, a suggestion could be confusing.
: [
{
messageId: "includeCause",
fix(fixer) {
/*
* In case `cause` is attached using object property shorthand or as a method or accessor.
* e.g. throw Error("fail", { cause });
* throw Error("fail", { cause() { doSomething(); } });
* throw Error("fail", { get cause() { return error; } });
*/
if (
thrownErrorCause.parent
.method ||
thrownErrorCause.parent
.shorthand ||
thrownErrorCause.parent.kind !==
"init"
) {
return fixer.replaceText(
thrownErrorCause.parent,
`cause: ${caughtError.name}`,
);
}
return fixer.replaceText(
thrownErrorCause,
caughtError.name,
);
},
},
];
context.report({
messageId: "incorrectCause",
node: thrownErrorCause,
suggest,
});
return;
}
/*
* If the attached cause matches the identifier name of the caught error,
* make sure it is not being shadowed by a closer scoped redeclaration.
*
* e.g. try {
* doSomething();
* } catch (error) {
* if (whatever) {
* const error = anotherError;
* throw new Error("Something went wrong");
* }
* }
*/
let scope = sourceCode.getScope(throwStatement);
do {
const variable = scope.set.get(caughtError.name);
if (variable) {
break;
}
scope = scope.upper;
} while (scope);
if (scope?.block !== parentCatch) {
// Caught error is being shadowed
context.report({
messageId: "caughtErrorShadowed",
node: throwStatement,
});
}
}
},
};
},
};

View File

@@ -0,0 +1,45 @@
/**
* Internal helpers for blake hash.
* @module
*/
import { rotr } from "./utils.js";
/**
* Internal blake variable.
* For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1].
*/
// prettier-ignore
export const BSIGMA = /* @__PURE__ */ Uint8Array.from([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,
13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,
6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,
10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
// Blake1, unused in others
11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
]);
// Mixing function G splitted in two halfs
export function G1s(a, b, c, d, x) {
a = (a + b + x) | 0;
d = rotr(d ^ a, 16);
c = (c + d) | 0;
b = rotr(b ^ c, 12);
return { a, b, c, d };
}
export function G2s(a, b, c, d, x) {
a = (a + b + x) | 0;
d = rotr(d ^ a, 8);
c = (c + d) | 0;
b = rotr(b ^ c, 7);
return { a, b, c, d };
}
//# sourceMappingURL=_blake.js.map

View File

@@ -0,0 +1 @@
export { _ as default } from "../esm/_is_native_function.js";

View File

@@ -0,0 +1 @@
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).uuidVersion=t()}(this,(function(){"use strict";var e=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;return function(t){if(!function(t){return"string"==typeof t&&e.test(t)}(t))throw TypeError("Invalid UUID");return parseInt(t.substr(14,1),16)}}));

View File

@@ -0,0 +1,64 @@
"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 });
exports.meta = exports.version = exports.withoutProjectParserOptions = exports.createProgram = exports.clearCaches = exports.parseForESLint = exports.parse = void 0;
const ts = __importStar(require("typescript"));
// intentionally executing code before rest of the require()s. This will not work with ESM.
const [versionMajor, _versionMinor] = ts.versionMajorMinor
.split('.')
.map(Number);
if (versionMajor >= 7) {
// eslint-disable-next-line no-console
console.error([
'typescript-eslint does not support TS 7.0.',
'Please see https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0 to run typescript-eslint using the TS 6 API.',
"See also https://github.com/typescript-eslint/typescript-eslint/issues/10940 for tracking typescript-eslint's support for TS >=7.1",
].join('\n'));
throw new Error('typescript-eslint does not support TS 7.0.');
}
var parser_1 = require("./parser");
Object.defineProperty(exports, "parse", { enumerable: true, get: function () { return parser_1.parse; } });
Object.defineProperty(exports, "parseForESLint", { enumerable: true, get: function () { return parser_1.parseForESLint; } });
var typescript_estree_1 = require("@typescript-eslint/typescript-estree");
Object.defineProperty(exports, "clearCaches", { enumerable: true, get: function () { return typescript_estree_1.clearCaches; } });
Object.defineProperty(exports, "createProgram", { enumerable: true, get: function () { return typescript_estree_1.createProgram; } });
Object.defineProperty(exports, "withoutProjectParserOptions", { enumerable: true, get: function () { return typescript_estree_1.withoutProjectParserOptions; } });
// note - cannot migrate this to an import statement because it will make TSC copy the package.json to the dist folder
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
exports.version = require('../package.json').version;
exports.meta = {
name: 'typescript-eslint/parser',
version: exports.version,
};

View File

@@ -0,0 +1,17 @@
import { _ as _get_prototype_of } from "./_get_prototype_of.js";
import { _ as _is_native_reflect_construct } from "./_is_native_reflect_construct.js";
import { _ as _possible_constructor_return } from "./_possible_constructor_return.js";
function _call_super(_this, derived, args) {
// Super
derived = _get_prototype_of(derived);
return _possible_constructor_return(
_this,
_is_native_reflect_construct()
// NOTE: This doesn't work if this.__proto__.constructor has been modified.
? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor)
: derived.apply(_this, args)
);
}
export { _call_super as _ };

View File

@@ -0,0 +1,45 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABILITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
interface PromiseFulfilledResult<T> {
status: "fulfilled";
value: T;
}
interface PromiseRejectedResult {
status: "rejected";
reason: any;
}
type PromiseSettledResult<T> = PromiseFulfilledResult<T> | PromiseRejectedResult;
interface PromiseConstructor {
/**
* Creates a Promise that is resolved with an array of results when all
* of the provided Promises resolve or reject.
* @param values An array of Promises.
* @returns A new Promise.
*/
allSettled<T extends readonly unknown[] | []>(values: T): Promise<{ -readonly [P in keyof T]: PromiseSettledResult<Awaited<T[P]>>; }>;
/**
* Creates a Promise that is resolved with an array of results when all
* of the provided Promises resolve or reject.
* @param values An array of Promises.
* @returns A new Promise.
*/
allSettled<T>(values: Iterable<T | PromiseLike<T>>): Promise<PromiseSettledResult<Awaited<T>>[]>;
}

View File

@@ -0,0 +1,324 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABILITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference lib="es2015.symbol" />
interface SymbolConstructor {
/**
* A method that determines if a constructor object recognizes an object as one of the
* constructors instances. Called by the semantics of the instanceof operator.
*/
readonly hasInstance: unique symbol;
/**
* A Boolean value that if true indicates that an object should flatten to its array elements
* by Array.prototype.concat.
*/
readonly isConcatSpreadable: unique symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
*/
readonly match: unique symbol;
/**
* A regular expression method that replaces matched substrings of a string. Called by the
* String.prototype.replace method.
*/
readonly replace: unique symbol;
/**
* A regular expression method that returns the index within a string that matches the
* regular expression. Called by the String.prototype.search method.
*/
readonly search: unique symbol;
/**
* A function valued property that is the constructor function that is used to create
* derived objects.
*/
readonly species: unique symbol;
/**
* A regular expression method that splits a string at the indices that match the regular
* expression. Called by the String.prototype.split method.
*/
readonly split: unique symbol;
/**
* A method that converts an object to a corresponding primitive value.
* Called by the ToPrimitive abstract operation.
*/
readonly toPrimitive: unique symbol;
/**
* A String value that is used in the creation of the default string description of an object.
* Called by the built-in method Object.prototype.toString.
*/
readonly toStringTag: unique symbol;
/**
* An Object whose truthy properties are properties that are excluded from the 'with'
* environment bindings of the associated objects.
*/
readonly unscopables: unique symbol;
}
interface Symbol {
/**
* Converts a Symbol object to a symbol.
*/
[Symbol.toPrimitive](hint: string): symbol;
readonly [Symbol.toStringTag]: string;
}
interface Array<T> {
/**
* Is an object whose properties have the value 'true'
* when they will be absent when used in a 'with' statement.
*/
readonly [Symbol.unscopables]: {
[K in keyof any[]]?: boolean;
};
}
interface ReadonlyArray<T> {
/**
* Is an object whose properties have the value 'true'
* when they will be absent when used in a 'with' statement.
*/
readonly [Symbol.unscopables]: {
[K in keyof readonly any[]]?: boolean;
};
}
interface Date {
/**
* Converts a Date object to a string.
*/
[Symbol.toPrimitive](hint: "default"): string;
/**
* Converts a Date object to a string.
*/
[Symbol.toPrimitive](hint: "string"): string;
/**
* Converts a Date object to a number.
*/
[Symbol.toPrimitive](hint: "number"): number;
/**
* Converts a Date object to a string or number.
*
* @param hint The strings "number", "string", or "default" to specify what primitive to return.
*
* @throws {TypeError} If 'hint' was given something other than "number", "string", or "default".
* @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default".
*/
[Symbol.toPrimitive](hint: string): string | number;
}
interface Map<K, V> {
readonly [Symbol.toStringTag]: string;
}
interface WeakMap<K extends WeakKey, V> {
readonly [Symbol.toStringTag]: string;
}
interface Set<T> {
readonly [Symbol.toStringTag]: string;
}
interface WeakSet<T extends WeakKey> {
readonly [Symbol.toStringTag]: string;
}
interface JSON {
readonly [Symbol.toStringTag]: string;
}
interface Function {
/**
* Determines whether the given value inherits from this function if this function was used
* as a constructor function.
*
* A constructor function can control which objects are recognized as its instances by
* 'instanceof' by overriding this method.
*/
[Symbol.hasInstance](value: any): boolean;
}
interface GeneratorFunction {
readonly [Symbol.toStringTag]: string;
}
interface Math {
readonly [Symbol.toStringTag]: string;
}
interface Promise<T> {
readonly [Symbol.toStringTag]: string;
}
interface PromiseConstructor {
readonly [Symbol.species]: PromiseConstructor;
}
interface RegExp {
/**
* Matches a string with this regular expression, and returns an array containing the results of
* that search.
* @param string A string to search within.
*/
[Symbol.match](string: string): RegExpMatchArray | null;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replaceValue A String object or string literal containing the text to replace for every
* successful match of this regular expression.
*/
[Symbol.replace](string: string, replaceValue: string): string;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replacer A function that returns the replacement text.
*/
[Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the position beginning first substring match in a regular expression search
* using this regular expression.
*
* @param string The string to search within.
*/
[Symbol.search](string: string): number;
/**
* Returns an array of substrings that were delimited by strings in the original input that
* match against this regular expression.
*
* If the regular expression contains capturing parentheses, then each time this
* regular expression matches, the results (including any undefined results) of the
* capturing parentheses are spliced.
*
* @param string string value to split
* @param limit if not undefined, the output array is truncated so that it contains no more
* than 'limit' elements.
*/
[Symbol.split](string: string, limit?: number): string[];
}
interface RegExpConstructor {
readonly [Symbol.species]: RegExpConstructor;
}
interface String {
/**
* Matches a string or an object that supports being matched against, and returns an array
* containing the results of that search, or null if no matches are found.
* @param matcher An object that supports being matched against.
*/
match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null;
/**
* Passes a string and {@linkcode replaceValue} to the `[Symbol.replace]` method on {@linkcode searchValue}. This method is expected to implement its own replacement algorithm.
* @param searchValue An object that supports searching for and replacing matches within a string.
* @param replaceValue The replacement text.
*/
replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string;
/**
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replacer A function that returns the replacement text.
*/
replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the first substring match in a regular expression search.
* @param searcher An object which supports searching within a string.
*/
search(searcher: { [Symbol.search](string: string): number; }): number;
/**
* Split a string into substrings using the specified separator and return them as an array.
* @param splitter An object that can split a string.
* @param limit A value used to limit the number of elements returned in the array.
*/
split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[];
}
interface ArrayBuffer {
readonly [Symbol.toStringTag]: "ArrayBuffer";
}
interface DataView<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: string;
}
interface Int8Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Int8Array";
}
interface Uint8Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Uint8Array";
}
interface Uint8ClampedArray<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Uint8ClampedArray";
}
interface Int16Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Int16Array";
}
interface Uint16Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Uint16Array";
}
interface Int32Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Int32Array";
}
interface Uint32Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Uint32Array";
}
interface Float32Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Float32Array";
}
interface Float64Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Float64Array";
}
interface ArrayConstructor {
readonly [Symbol.species]: ArrayConstructor;
}
interface MapConstructor {
readonly [Symbol.species]: MapConstructor;
}
interface SetConstructor {
readonly [Symbol.species]: SetConstructor;
}
interface ArrayBufferConstructor {
readonly [Symbol.species]: ArrayBufferConstructor;
}