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,409 @@
import { a as cleanUrl, c as createManualModuleSource } from './chunk-utils.js';
import { a as automockModule, e as esmWalker } from './chunk-automock.js';
import MagicString from 'magic-string';
import { createFilter } from 'vite';
import { h as hoistMocks } from './chunk-hoistMocks.js';
import { readFile } from 'node:fs/promises';
import { join } from 'node:path/posix';
import { M as MockerRegistry, a as ManualMockedModule } from './chunk-registry.js';
import { fileURLToPath } from 'node:url';
import { existsSync, readFileSync } from 'node:fs';
import { findMockRedirect } from './redirect.js';
import { i as isAbsolute, j as join$1, r as resolve } from './chunk-pathe.M-eThtNZ.js';
import 'estree-walker';
import 'node:module';
import 'node:path';
import './chunk-helpers.js';
function automockPlugin(options = {}) {
return {
name: "vitest:automock",
enforce: "post",
transform(code, id) {
if (id.includes("mock=automock") || id.includes("mock=autospy")) {
const mockType = id.includes("mock=automock") ? "automock" : "autospy";
const ms = automockModule(code, mockType, this.parse, options);
return {
code: ms.toString(),
map: ms.generateMap({
hires: "boundary",
source: cleanUrl(id)
})
};
}
}
};
}
const regexDynamicImport = /import\s*\(/;
function dynamicImportPlugin(options = {}) {
return {
name: "vitest:browser:esm-injector",
enforce: "post",
transform(source, id) {
// TODO: test is not called for static imports
if (!regexDynamicImport.test(source)) {
return;
}
if (options.filter && !options.filter(id)) {
return;
}
return injectDynamicImport(source, id, this.parse, options);
}
};
}
function injectDynamicImport(code, id, parse, options = {}) {
if (code.includes("wrapDynamicImport")) {
return;
}
const s = new MagicString(code);
let ast;
try {
ast = parse(code);
} catch (err) {
console.error(`Cannot parse ${id}:\n${err.message}`);
return;
}
// 3. convert references to import bindings & import.meta references
esmWalker(ast, {
onImportMeta() {
// s.update(node.start, node.end, viImportMetaKey)
},
onDynamicImport(node) {
const globalThisAccessor = options.globalThisAccessor || "\"__vitest_mocker__\"";
const replaceString = `globalThis[${globalThisAccessor}].wrapDynamicImport(() => import(`;
const importSubstring = code.substring(node.start, node.end);
const hasIgnore = importSubstring.includes("/* @vite-ignore */");
s.overwrite(node.start, node.source.start, replaceString + (hasIgnore ? "/* @vite-ignore */ " : ""));
s.overwrite(node.end - 1, node.end, "))");
}
});
return {
code: s.toString(),
map: s.generateMap({
hires: "boundary",
source: id
})
};
}
function hoistMocksPlugin(options = {}) {
const filter = options.filter || createFilter(options.include, options.exclude);
const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [
"mock",
"unmock",
"doMock",
"doUnmock"
], hoistedMethodNames = ["hoisted"], utilsObjectNames = ["vi", "vitest"] } = options;
const methods = new Set([
...hoistableMockMethodNames,
...hoistedMethodNames,
...dynamicImportMockMethodNames
]);
const regexpHoistable = new RegExp(`\\b(?:${utilsObjectNames.join("|")})\\s*\.\\s*(?:${Array.from(methods).join("|")})\\s*\\(`);
return {
name: "vitest:mocks",
enforce: "post",
transform(code, id) {
if (!filter(id)) {
return;
}
const s = hoistMocks(code, id, this.parse, {
regexpHoistable,
hoistableMockMethodNames,
hoistedMethodNames,
utilsObjectNames,
dynamicImportMockMethodNames,
...options
});
if (s) {
return {
code: s.toString(),
map: s.generateMap({
hires: "boundary",
source: cleanUrl(id)
})
};
}
}
};
}
// to keeb backwards compat
function hoistMockAndResolve(code, id, parse, options = {}) {
const s = hoistMocks(code, id, parse, options);
if (s) {
return {
code: s.toString(),
map: s.generateMap({
hires: "boundary",
source: cleanUrl(id)
})
};
}
}
function interceptorPlugin(options = {}) {
const registry = options.registry || new MockerRegistry();
return {
name: "vitest:mocks:interceptor",
enforce: "pre",
load: {
order: "pre",
async handler(id) {
const mock = registry.getById(id);
if (!mock) {
return;
}
if (mock.type === "manual") {
const exports$1 = Object.keys(await mock.resolve());
const accessor = options.globalThisAccessor || "\"__vitest_mocker__\"";
return createManualModuleSource(mock.url, exports$1, accessor);
}
if (mock.type === "redirect") {
return readFile(mock.redirect, "utf-8");
}
}
},
transform: {
order: "post",
handler(code, id) {
const mock = registry.getById(id);
if (!mock) {
return;
}
if (mock.type === "automock" || mock.type === "autospy") {
const m = automockModule(code, mock.type, this.parse, { globalThisAccessor: options.globalThisAccessor });
return {
code: m.toString(),
map: m.generateMap({
hires: "boundary",
source: cleanUrl(id)
})
};
}
}
},
configureServer(server) {
server.ws.on("vitest:interceptor:register", (event) => {
if (event.type === "manual") {
const module = ManualMockedModule.fromJSON(event, async () => {
const keys = await getFactoryExports(event.url);
return Object.fromEntries(keys.map((key) => [key, null]));
});
registry.add(module);
} else {
if (event.type === "redirect") {
const redirectUrl = new URL(event.redirect);
event.redirect = join(server.config.root, redirectUrl.pathname);
}
registry.register(event);
}
server.ws.send("vitest:interceptor:register:result");
});
server.ws.on("vitest:interceptor:delete", (id) => {
registry.delete(id);
server.ws.send("vitest:interceptor:delete:result");
});
server.ws.on("vitest:interceptor:invalidate", () => {
registry.clear();
server.ws.send("vitest:interceptor:invalidate:result");
});
function getFactoryExports(url) {
server.ws.send("vitest:interceptor:resolve", url);
let timeout;
return new Promise((resolve, reject) => {
timeout = setTimeout(() => {
reject(new Error(`Timeout while waiting for factory exports of ${url}`));
}, 1e4);
server.ws.on("vitest:interceptor:resolved", ({ url: resolvedUrl, keys }) => {
if (resolvedUrl === url) {
clearTimeout(timeout);
resolve(keys);
}
});
});
}
}
};
}
const VALID_ID_PREFIX = "/@id/";
class ServerMockResolver {
constructor(server, options = {}) {
this.server = server;
this.options = options;
}
async resolveMock(rawId, importer, options) {
const { id, fsPath, external } = await this.resolveMockId(rawId, importer);
const resolvedUrl = this.normalizeResolveIdToUrl({ id }).url;
if (options.mock === "factory") {
const manifest = getViteDepsManifest(this.server.config);
const needsInterop = manifest?.[fsPath]?.needsInterop ?? false;
return {
mockType: "manual",
resolvedId: id,
resolvedUrl,
needsInterop
};
}
if (options.mock === "spy") {
return {
mockType: "autospy",
resolvedId: id,
resolvedUrl
};
}
const redirectUrl = findMockRedirect(this.server.config.root, fsPath, external);
return {
mockType: redirectUrl === null ? "automock" : "redirect",
redirectUrl,
resolvedId: id,
resolvedUrl
};
}
invalidate(ids) {
ids.forEach((id) => {
const moduleGraph = this.server.moduleGraph;
const module = moduleGraph.getModuleById(id);
if (module) {
module.transformResult = null;
}
});
}
async resolveId(id, importer) {
const resolved = await this.server.pluginContainer.resolveId(id, importer, { ssr: false });
if (!resolved) {
return null;
}
return this.normalizeResolveIdToUrl(resolved);
}
normalizeResolveIdToUrl(resolved) {
const isOptimized = resolved.id.startsWith(withTrailingSlash(this.server.config.cacheDir));
let url;
// normalise the URL to be acceptable by the browser
// https://github.com/vitejs/vite/blob/14027b0f2a9b01c14815c38aab22baf5b29594bb/packages/vite/src/node/plugins/importAnalysis.ts#L103
const root = this.server.config.root;
if (resolved.id.startsWith(withTrailingSlash(root))) {
url = resolved.id.slice(root.length);
} else if (resolved.id !== "/@react-refresh" && isAbsolute(resolved.id) && existsSync(cleanUrl(resolved.id))) {
url = join$1("/@fs/", resolved.id);
} else {
url = resolved.id;
}
if (url[0] !== "." && url[0] !== "/") {
url = resolved.id.startsWith(VALID_ID_PREFIX) ? resolved.id : VALID_ID_PREFIX + resolved.id.replace("\0", "__x00__");
}
return {
id: resolved.id,
url,
optimized: isOptimized
};
}
async resolveMockId(rawId, importer) {
if (!this.server.moduleGraph.getModuleById(importer) && !importer.startsWith(this.server.config.root)) {
importer = join$1(this.server.config.root, importer);
}
const resolved = await this.server.pluginContainer.resolveId(rawId, importer, { ssr: false });
return this.resolveModule(rawId, resolved);
}
resolveModule(rawId, resolved) {
const id = resolved?.id || rawId;
const external = !isAbsolute(id) || isModuleDirectory(this.options, id) ? rawId : null;
return {
id,
fsPath: cleanUrl(id),
external
};
}
}
function isModuleDirectory(config, path) {
const moduleDirectories = config.moduleDirectories || ["/node_modules/"];
return moduleDirectories.some((dir) => path.includes(dir));
}
const metadata = new WeakMap();
function getViteDepsManifest(config) {
if (metadata.has(config)) {
return metadata.get(config);
}
const cacheDirPath = getDepsCacheDir(config);
const metadataPath = resolve(cacheDirPath, "_metadata.json");
if (!existsSync(metadataPath)) {
return null;
}
const { optimized } = JSON.parse(readFileSync(metadataPath, "utf-8"));
const newManifest = {};
for (const name in optimized) {
const dep = optimized[name];
const file = resolve(cacheDirPath, dep.file);
newManifest[file] = {
hash: dep.fileHash,
needsInterop: dep.needsInterop
};
}
metadata.set(config, newManifest);
return newManifest;
}
function getDepsCacheDir(config) {
return resolve(config.cacheDir, "deps");
}
function withTrailingSlash(path) {
if (path.at(-1) !== "/") {
return `${path}/`;
}
return path;
}
// this is an implementation for public usage
// vitest doesn't use this plugin directly
function mockerPlugin(options = {}) {
let server;
const registerPath = resolve(fileURLToPath(new URL("./register.js", import.meta.url)));
return [
{
name: "vitest:mocker:ws-rpc",
config(_, { command }) {
if (command !== "serve") {
return;
}
return {
server: { preTransformRequests: false },
optimizeDeps: { exclude: ["@vitest/mocker/register", "@vitest/mocker/browser"] }
};
},
configureServer(server_) {
server = server_;
const mockResolver = new ServerMockResolver(server);
server.ws.on("vitest:mocks:resolveId", async ({ id, importer }) => {
const resolved = await mockResolver.resolveId(id, importer);
server.ws.send("vitest:mocks:resolvedId:result", resolved);
});
server.ws.on("vitest:mocks:resolveMock", async ({ id, importer, options }) => {
const resolved = await mockResolver.resolveMock(id, importer, options);
server.ws.send("vitest:mocks:resolveMock:result", resolved);
});
server.ws.on("vitest:mocks:invalidate", async ({ ids }) => {
mockResolver.invalidate(ids);
server.ws.send("vitest:mocks:invalidate:result");
});
},
async load(id) {
if (id !== registerPath) {
return;
}
if (!server) {
// mocker doesn't work during build
return "export {}";
}
const content = await readFile(registerPath, "utf-8");
const result = content.replace(/__VITEST_GLOBAL_THIS_ACCESSOR__/g, options.globalThisAccessor ?? "\"__vitest_mocker__\"").replace("__VITEST_MOCKER_ROOT__", JSON.stringify(server.config.root));
return result;
}
},
hoistMocksPlugin(options.hoistMocks),
interceptorPlugin(options),
automockPlugin(options),
dynamicImportPlugin(options)
];
}
export { ServerMockResolver, automockModule, automockPlugin, createManualModuleSource, dynamicImportPlugin, findMockRedirect, hoistMockAndResolve as hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin };

View File

@@ -0,0 +1,149 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parse = parse;
exports.parseForESLint = parseForESLint;
const scope_manager_1 = require("@typescript-eslint/scope-manager");
const typescript_estree_1 = require("@typescript-eslint/typescript-estree");
const visitor_keys_1 = require("@typescript-eslint/visitor-keys");
const debug_1 = __importDefault(require("debug"));
const typescript_1 = require("typescript");
const log = (0, debug_1.default)('typescript-eslint:parser:parser');
function validateBoolean(value, fallback = false) {
if (typeof value !== 'boolean') {
return fallback;
}
return value;
}
const LIB_FILENAME_REGEX = /lib\.(.+)\.d\.[cm]?ts$/;
function getLib(compilerOptions) {
if (compilerOptions.lib) {
return compilerOptions.lib
.map(lib => LIB_FILENAME_REGEX.exec(lib.toLowerCase())?.[1])
.filter((lib) => !!lib);
}
const defaultTarget = typescript_estree_1.typescriptVersionIsAtLeast['6.0']
? typescript_1.ScriptTarget.LatestStandard
: typescript_1.ScriptTarget.ES5; // eslint-disable-line @typescript-eslint/no-deprecated -- Deprecated in TS 6 but we support TS < 6
const target = compilerOptions.target ?? defaultTarget;
// https://github.com/microsoft/TypeScript/blob/35ff23d4b0cc715691323ebe54f523c16fe6e3a5/src/compiler/utilitiesPublic.ts#L312-L346
switch (target) {
case typescript_1.ScriptTarget.ES2015:
return ['es6'];
case typescript_1.ScriptTarget.ES2016:
return ['es2016.full'];
case typescript_1.ScriptTarget.ES2017:
return ['es2017.full'];
case typescript_1.ScriptTarget.ES2018:
return ['es2018.full'];
case typescript_1.ScriptTarget.ES2019:
return ['es2019.full'];
case typescript_1.ScriptTarget.ES2020:
return ['es2020.full'];
case typescript_1.ScriptTarget.ES2021:
return ['es2021.full'];
case typescript_1.ScriptTarget.ES2022:
return ['es2022.full'];
case typescript_1.ScriptTarget.ES2023:
return ['es2023.full'];
case typescript_1.ScriptTarget.ES2024:
return ['es2024.full'];
case typescript_1.ScriptTarget.ES2025:
return ['es2025.full'];
case typescript_1.ScriptTarget.ESNext:
return ['esnext.full'];
default:
return ['lib'];
}
}
function parse(code, options) {
return parseForESLint(code, options).ast;
}
function parseForESLint(code, parserOptions) {
if (!parserOptions || typeof parserOptions !== 'object') {
parserOptions = {};
}
else {
parserOptions = { ...parserOptions };
}
// https://eslint.org/docs/user-guide/configuring#specifying-parser-options
// if sourceType is not provided by default eslint expect that it will be set to "script"
if (parserOptions.sourceType !== 'module' &&
parserOptions.sourceType !== 'script') {
parserOptions.sourceType = 'script';
}
if (typeof parserOptions.ecmaFeatures !== 'object') {
parserOptions.ecmaFeatures = {};
}
if (parserOptions.onUnsupportedTypeScriptVersion != null &&
// eslint-disable-next-line @typescript-eslint/no-deprecated -- read for backwards compatibility
parserOptions.warnOnUnsupportedTypeScriptVersion != null) {
throw new Error('Cannot use both the `onUnsupportedTypeScriptVersion` and the deprecated `warnOnUnsupportedTypeScriptVersion` options. Please use only `onUnsupportedTypeScriptVersion`.');
}
const onUnsupportedTypeScriptVersion = parserOptions.onUnsupportedTypeScriptVersion ??
// eslint-disable-next-line @typescript-eslint/no-deprecated -- read for backwards compatibility
(validateBoolean(parserOptions.warnOnUnsupportedTypeScriptVersion, true)
? 'warn'
: 'ignore');
const tsestreeOptions = {
jsx: validateBoolean(parserOptions.ecmaFeatures.jsx),
...parserOptions,
onUnsupportedTypeScriptVersion,
// Override errorOnTypeScriptSyntacticAndSemanticIssues and set it to false to prevent use from user config
// https://github.com/typescript-eslint/typescript-eslint/issues/8681#issuecomment-2000411834
errorOnTypeScriptSyntacticAndSemanticIssues: false,
// comment, loc, range, and tokens should always be set for ESLint usage
// https://github.com/typescript-eslint/typescript-eslint/issues/8347
comment: true,
loc: true,
range: true,
tokens: true,
};
const analyzeOptions = {
globalReturn: parserOptions.ecmaFeatures.globalReturn,
jsxFragmentName: parserOptions.jsxFragmentName,
jsxPragma: parserOptions.jsxPragma,
lib: parserOptions.lib,
sourceType: parserOptions.sourceType,
};
const { ast, services } = (0, typescript_estree_1.parseAndGenerateServices)(code, tsestreeOptions);
ast.sourceType = parserOptions.sourceType;
if (services.program) {
// automatically apply the options configured for the program
const compilerOptions = services.program.getCompilerOptions();
if (analyzeOptions.lib == null) {
analyzeOptions.lib = getLib(compilerOptions);
log('Resolved libs from program: %o', analyzeOptions.lib);
}
if (
// eslint-disable-next-line @typescript-eslint/internal/eqeq-nullish
analyzeOptions.jsxPragma === undefined &&
compilerOptions.jsxFactory != null) {
// in case the user has specified something like "preact.h"
const factory = compilerOptions.jsxFactory.split('.')[0].trim();
analyzeOptions.jsxPragma = factory;
log('Resolved jsxPragma from program: %s', analyzeOptions.jsxPragma);
}
if (
// eslint-disable-next-line @typescript-eslint/internal/eqeq-nullish
analyzeOptions.jsxFragmentName === undefined &&
compilerOptions.jsxFragmentFactory != null) {
// in case the user has specified something like "preact.Fragment"
const fragFactory = compilerOptions.jsxFragmentFactory
.split('.')[0]
.trim();
analyzeOptions.jsxFragmentName = fragFactory;
log('Resolved jsxFragmentName from program: %s', analyzeOptions.jsxFragmentName);
}
}
const scopeManager = (0, scope_manager_1.analyze)(ast, analyzeOptions);
// if not defined - override from the parserOptions
services.emitDecoratorMetadata ??=
parserOptions.emitDecoratorMetadata === true;
services.experimentalDecorators ??=
parserOptions.experimentalDecorators === true;
services.isolatedDeclarations ??= parserOptions.isolatedDeclarations === true;
return { ast, scopeManager, services, visitorKeys: visitor_keys_1.visitorKeys };
}

View File

@@ -0,0 +1,11 @@
"use strict";
var _class_apply_descriptor_set = require("./_class_apply_descriptor_set.cjs");
var _class_extract_field_descriptor = require("./_class_extract_field_descriptor.cjs");
function _class_private_field_set(receiver, privateMap, value) {
var descriptor = _class_extract_field_descriptor._(receiver, privateMap, "set");
_class_apply_descriptor_set._(receiver, descriptor, value);
return value;
}
exports._ = _class_private_field_set;

View File

@@ -0,0 +1,24 @@
/*!
* humanize-ms - index.js
* Copyright(c) 2014 dead_horse <dead_horse@qq.com>
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
*/
var util = require('util');
var ms = require('ms');
module.exports = function (t) {
if (typeof t === 'number') return t;
var r = ms(t);
if (r === undefined) {
var err = new Error(util.format('humanize-ms(%j) result undefined', t));
console.warn(err.stack);
}
return r;
};

View File

@@ -0,0 +1,25 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}
{{
var $regExpCode = it.opts.regExp ? 'regExp' : 'new RegExp';
}}
{{? $isData }}
var {{=$valid}} = true;
try {
{{=$valid}} = {{=$regExpCode}}({{=$schemaValue}}).test({{=$data}});
} catch(e) {
{{=$valid}} = false;
}
if ({{# def.$dataNotType:'string' }} !{{=$valid}}) {
{{??}}
{{
var $regexp = it.usePattern($schema);
}}
if ({{# def.$dataNotType:'string' }} !{{=$regexp}}.test({{=$data}}) ) {
{{?}}
{{# def.error:'pattern' }}
} {{? $breakOnError }} else { {{?}}

View File

@@ -0,0 +1 @@
{"version":3,"file":"hash-to-curve.d.ts","sourceRoot":"","sources":["../src/abstract/hash-to-curve.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,sEAAsE;AACtE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAUzC,OAAO,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACvE,OAAO,EAAsB,KAAK,MAAM,EAAE,MAAM,cAAc,CAAC;AAE/D,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,UAAU,CAAC;AAEjD;;;;;;;GAOG;AACH,MAAM,MAAM,OAAO,GAAG;IACpB,GAAG,EAAE,cAAc,CAAC;IACpB,MAAM,EAAE,KAAK,GAAG,KAAK,CAAC;IACtB,IAAI,EAAE,KAAK,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;CACX,CAAC;AACF,MAAM,MAAM,WAAW,GAAG;IACxB,MAAM,EAAE,KAAK,GAAG,KAAK,CAAC;IACtB,IAAI,EAAE,KAAK,CAAC;CACb,CAAC;AAEF,MAAM,MAAM,IAAI,GAAG,OAAO,CAAC;AAmC3B;;;GAGG;AACH,wBAAgB,kBAAkB,CAChC,GAAG,EAAE,UAAU,EACf,GAAG,EAAE,cAAc,EACnB,UAAU,EAAE,MAAM,EAClB,CAAC,EAAE,KAAK,GACP,UAAU,CAqBZ;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,GAAG,EAAE,UAAU,EACf,GAAG,EAAE,cAAc,EACnB,UAAU,EAAE,MAAM,EAClB,CAAC,EAAE,MAAM,EACT,CAAC,EAAE,KAAK,GACP,UAAU,CAqBZ;AAED;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,MAAM,EAAE,EAAE,CAoC1F;AAED,MAAM,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK;IAAE,CAAC,EAAE,CAAC,CAAC;IAAC,CAAC,EAAE,CAAC,CAAA;CAAE,CAAC;AACnD,MAAM,MAAM,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC;AAC9C,wBAAgB,UAAU,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAgBnF;AAED,sFAAsF;AACtF,MAAM,WAAW,QAAQ,CAAC,CAAC,CAAE,SAAQ,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;IACrD,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;IACnC,QAAQ,CAAC,EAAE,CAAC,EAAE,MAAM,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC;IACtC,aAAa,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC;IAC7B,cAAc,IAAI,IAAI,CAAC;CACxB;AAED,MAAM,WAAW,mBAAmB,CAAC,CAAC,CAAE,SAAQ,gBAAgB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;IAC3E,UAAU,CAAC,EAAE,EAAE,WAAW,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;CAC7C;AAED,MAAM,MAAM,UAAU,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,WAAW,CAAC,CAAC,CAAC,CAAC;AAIjE,MAAM,MAAM,YAAY,GAAG;IAAE,GAAG,EAAE,cAAc,CAAA;CAAE,CAAC;AACnD,MAAM,MAAM,SAAS,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,UAAU,EAAE,OAAO,CAAC,EAAE,YAAY,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC;AAEpF,MAAM,MAAM,SAAS,CAAC,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC;AACxC,MAAM,MAAM,SAAS,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC;AAC9D,MAAM,MAAM,aAAa,CAAC,CAAC,IAAI;IAC7B,WAAW,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;IAC1B,YAAY,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,OAAO,EAAE,YAAY,KAAK,MAAM,CAAC;CAClE,CAAC;AACF;;;;;;GAMG;AACH,MAAM,MAAM,SAAS,CAAC,CAAC,IAAI,aAAa,CAAC,CAAC,CAAC,GAAG;IAC5C,aAAa,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;IAC5B,UAAU,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;IACzB,QAAQ,EAAE,OAAO,GAAG;QAAE,SAAS,CAAC,EAAE,cAAc,CAAA;KAAE,CAAC;CACpD,CAAC;AAEF,MAAM,MAAM,MAAM,CAAC,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC;AAErC,eAAO,MAAM,WAAW,EAAE,UAAyC,CAAC;AAEpE,kGAAkG;AAClG,wBAAgB,YAAY,CAAC,CAAC,EAC5B,KAAK,EAAE,mBAAmB,CAAC,CAAC,CAAC,EAC7B,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,EACzB,QAAQ,EAAE,OAAO,GAAG;IAAE,SAAS,CAAC,EAAE,cAAc,CAAA;CAAE,GACjD,SAAS,CAAC,CAAC,CAAC,CA8Cd"}

View File

@@ -0,0 +1,83 @@
{
"name": "@solana/codecs-core",
"version": "2.3.0",
"description": "Core types and helpers for encoding and decoding byte arrays on Solana",
"exports": {
"edge-light": {
"import": "./dist/index.node.mjs",
"require": "./dist/index.node.cjs"
},
"workerd": {
"import": "./dist/index.node.mjs",
"require": "./dist/index.node.cjs"
},
"browser": {
"import": "./dist/index.browser.mjs",
"require": "./dist/index.browser.cjs"
},
"node": {
"import": "./dist/index.node.mjs",
"require": "./dist/index.node.cjs"
},
"react-native": "./dist/index.native.mjs",
"types": "./dist/types/index.d.ts"
},
"browser": {
"./dist/index.node.cjs": "./dist/index.browser.cjs",
"./dist/index.node.mjs": "./dist/index.browser.mjs"
},
"main": "./dist/index.node.cjs",
"module": "./dist/index.node.mjs",
"react-native": "./dist/index.native.mjs",
"types": "./dist/types/index.d.ts",
"type": "commonjs",
"files": [
"./dist/"
],
"sideEffects": false,
"keywords": [
"blockchain",
"solana",
"web3"
],
"author": "Solana Labs Maintainers <maintainers@solanalabs.com>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/anza-xyz/kit"
},
"bugs": {
"url": "https://github.com/anza-xyz/kit/issues"
},
"browserslist": [
"supports bigint and not dead",
"maintained node versions"
],
"dependencies": {
"@solana/errors": "2.3.0"
},
"peerDependencies": {
"typescript": ">=5.3.3"
},
"engines": {
"node": ">=20.18.0"
},
"scripts": {
"benchmark": "./src/__benchmarks__/run.ts",
"compile:docs": "typedoc",
"compile:js": "tsup --config build-scripts/tsup.config.package.ts",
"compile:typedefs": "tsc -p ./tsconfig.declarations.json",
"dev": "jest -c ../../node_modules/@solana/test-config/jest-dev.config.ts --rootDir . --watch",
"publish-impl": "npm view $npm_package_name@$npm_package_version > /dev/null 2>&1 || (pnpm publish --tag ${PUBLISH_TAG:-canary} --access public --no-git-checks && (([ \"$PUBLISH_TAG\" != \"canary\" ] && pnpm dist-tag add $npm_package_name@$npm_package_version latest) || true))",
"publish-packages": "pnpm prepublishOnly && pnpm publish-impl",
"style:fix": "pnpm eslint --fix src && pnpm prettier --log-level warn --ignore-unknown --write ./*",
"test:lint": "TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@solana/test-config/jest-lint.config.ts --rootDir . --silent",
"test:prettier": "TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@solana/test-config/jest-prettier.config.ts --rootDir . --silent",
"test:treeshakability:browser": "agadoo dist/index.browser.mjs",
"test:treeshakability:native": "agadoo dist/index.native.mjs",
"test:treeshakability:node": "agadoo dist/index.node.mjs",
"test:typecheck": "tsc --noEmit",
"test:unit:browser": "TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@solana/test-config/jest-unit.config.browser.ts --rootDir . --silent",
"test:unit:node": "TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@solana/test-config/jest-unit.config.node.ts --rootDir . --silent"
}
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/ast/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,cAAc,UAAU,CAAC;AACzB,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC;AAC7B,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC"}

View File

@@ -0,0 +1 @@
{"version":3,"file":"p384.js","sourceRoot":"","sources":["../src/p384.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,sEAAsE;AACtE,OAAO,EAAkB,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,IAAI,IAAI,KAAK,EAAE,MAAM,WAAW,CAAC;AACvD,sEAAsE;AACtE,MAAM,CAAC,MAAM,IAAI,GAAiB,KAAK,CAAC;AACxC,sEAAsE;AACtE,MAAM,CAAC,MAAM,SAAS,GAAiB,KAAK,CAAC;AAC7C,6EAA6E;AAC7E,MAAM,CAAC,MAAM,WAAW,GAAsB,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,WAAW,CAAC,WAAW,CAAC,EAAE,CAAC;AAChG,6EAA6E;AAC7E,MAAM,CAAC,MAAM,aAAa,GAAsB,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,WAAW,CAAC,aAAa,CAAC,EAAE,CAAC"}

View File

@@ -0,0 +1,642 @@
import { M as ModuleDefinitionDurationsDiagnostic, U as UntrackedModuleDefinitionDiagnostic, S as SerializedTestSpecification, a as ModuleDefinitionDiagnostic, b as ModuleDefinitionLocation, c as SourceModuleDiagnostic, d as SourceModuleLocations } from './chunks/browser.d.BcoexmFG.js';
export { B as BrowserTesterOptions } from './chunks/browser.d.BcoexmFG.js';
import './chunks/global.d.DVsSRdQ5.js';
import { File, TestAnnotation, TestArtifact, TaskResultPack, TaskEventPack, Test, TaskPopulated } from '@vitest/runner';
export { CancelReason, ImportDuration, OnTestFailedHandler, OnTestFinishedHandler, RunMode, Task as RunnerTask, TaskBase as RunnerTaskBase, TaskEventPack as RunnerTaskEventPack, TaskResult as RunnerTaskResult, TaskResultPack as RunnerTaskResultPack, Test as RunnerTestCase, File as RunnerTestFile, Suite as RunnerTestSuite, SuiteAPI, SuiteCollector, SuiteFactory, SuiteOptions, TaskCustomOptions, TaskMeta, TaskState, TestAPI, TestAnnotation, TestAnnotationArtifact, TestArtifact, TestArtifactBase, TestArtifactLocation, TestArtifactRegistry, TestAttachment, TestContext, TestFunction, TestOptions, VitestRunnerConfig as TestRunnerConfig, TestTags, VitestRunner as VitestTestRunner, afterAll, afterEach, aroundAll, aroundEach, beforeAll, beforeEach, describe, it, onTestFailed, onTestFinished, recordArtifact, suite, test } from '@vitest/runner';
import { Awaitable } from '@vitest/utils';
export { ParsedStack, SerializedError, TestError } from '@vitest/utils';
import { b as BirpcReturn } from './chunks/worker.d.ZpHpO4yb.js';
export { C as ContextRPC, c as ContextTestEnvironment, T as TestExecutionMethod, W as WorkerGlobalState } from './chunks/worker.d.ZpHpO4yb.js';
import { b as SerializedRootConfig, F as FakeTimerInstallOpts, R as RuntimeOptions } from './chunks/config.d.A1h_Y6Jt.js';
export { c as RuntimeConfig, S as SerializedConfig, a as SerializedCoverageConfig } from './chunks/config.d.A1h_Y6Jt.js';
import { U as UserConsoleLog, L as LabelColor, M as ModuleGraphData, P as ProvidedContext } from './chunks/traces.d.D2T_R8rx.js';
export { a as AfterSuiteRunMeta } from './chunks/traces.d.D2T_R8rx.js';
import { ExpectStatic, MatcherState, SyncExpectationResult, AsyncExpectationResult, ExpectationResult } from '@vitest/expect';
export { Assertion, AsymmetricMatchersContaining, DeeplyAllowMatchers, ExpectPollOptions, ExpectStatic, JestAssertion, RawMatcherFn as Matcher, ExpectationResult as MatcherResult, MatcherState, Matchers, chai } from '@vitest/expect';
import { DomainSnapshotAdapter } from '@vitest/snapshot';
export { SnapshotData, SnapshotMatchOptions, SnapshotResult, SnapshotSerializer, SnapshotStateOptions, SnapshotSummary, SnapshotUpdateState, UncheckedSnapshot } from '@vitest/snapshot';
import { spyOn, fn, MaybeMockedDeep, MaybeMocked, MaybePartiallyMocked, MaybePartiallyMockedDeep, MockInstance } from '@vitest/spy';
export { Mock, MockContext, MockInstance, MockResult, MockResultIncomplete, MockResultReturn, MockResultThrow, MockSettledResult, MockSettledResultFulfilled, MockSettledResultIncomplete, MockSettledResultRejected, Mocked, MockedClass, MockedFunction, MockedObject } from '@vitest/spy';
import { Disposable } from 'vitest/optional-runtime-types.js';
import { ModuleMockFactoryWithHelper, ModuleMockOptions } from '@vitest/mocker';
export { b as bench } from './chunks/suite.d.udJtyAgw.js';
export { V as EvaluatedModules } from './chunks/evaluatedModules.d.BxJ5omdx.js';
export { NodeBenchmarkRunner as BenchmarkRunner, VitestTestRunner as TestRunner } from './runners.js';
export { a as BenchFunction, b as Benchmark, c as BenchmarkAPI, B as BenchmarkResult } from './chunks/benchmark.d.DAaHLpsq.js';
export { ExpectTypeOf, expectTypeOf } from 'expect-type';
export { a as RunnerRPC, R as RuntimeRPC } from './chunks/rpc.d.B_8sPU0w.js';
export { DiffOptions } from '@vitest/utils/diff';
export { Bench as BenchFactory, Options as BenchOptions, Task as BenchTask, TaskResult as BenchTaskResult } from 'tinybench';
import '@vitest/pretty-format';
import 'vite/module-runner';
import './chunks/environment.d.CrsxCzP1.js';
import '@vitest/runner/utils';
interface SourceMap {
file: string;
mappings: string;
names: string[];
sources: string[];
sourcesContent?: string[];
version: number;
toString: () => string;
toUrl: () => string;
}
interface ExternalResult {
source?: string;
}
interface TransformResultWithSource {
code: string;
map: SourceMap | {
mappings: "";
} | null;
etag?: string;
deps?: string[];
dynamicDeps?: string[];
source?: string;
transformTime?: number;
modules?: ModuleDefinitionDurationsDiagnostic[];
untrackedModules?: UntrackedModuleDefinitionDiagnostic[];
}
interface WebSocketHandlers {
getFiles: () => File[];
getTestFiles: () => Promise<SerializedTestSpecification[]>;
getPaths: () => string[];
getConfig: () => SerializedRootConfig;
/**
* @deprecated Use `getConfig().projects` instead.
*/
getResolvedProjectLabels: () => {
name: string;
color?: LabelColor;
}[];
getModuleGraph: (projectName: string, id: string, browser?: boolean) => Promise<ModuleGraphData>;
getTransformResult: (projectName: string, id: string, testFileId: string, browser?: boolean) => Promise<TransformResultWithSource | undefined>;
getExternalResult: (id: string, testFileId: string) => Promise<ExternalResult | undefined>;
readTestFile: (id: string) => Promise<string | null>;
saveTestFile: (id: string, content: string) => Promise<void>;
rerun: (files: string[], resetTestNamePattern?: boolean) => Promise<void>;
rerunTask: (id: string) => Promise<void>;
updateSnapshot: (file?: File) => Promise<void>;
getUnhandledErrors: () => unknown[];
}
interface WebSocketEvents {
onCollected?: (files?: File[]) => Awaitable<void>;
onFinished?: (files: File[], errors: unknown[], coverage?: unknown, executionTime?: number) => Awaitable<void>;
onTestAnnotate?: (testId: string, annotation: TestAnnotation) => Awaitable<void>;
onTestArtifactRecord?: (testId: string, artifact: TestArtifact) => Awaitable<void>;
onTaskUpdate?: (packs: TaskResultPack[], events: TaskEventPack[]) => Awaitable<void>;
onUserConsoleLog?: (log: UserConsoleLog) => Awaitable<void>;
onPathsCollected?: (paths?: string[]) => Awaitable<void>;
onSpecsCollected?: (specs?: SerializedTestSpecification[], startTime?: number) => Awaitable<void>;
onFinishedReportCoverage: () => void;
}
type WebSocketRPC = BirpcReturn<WebSocketEvents, WebSocketHandlers>;
declare function createExpect(test?: Test | TaskPopulated): ExpectStatic;
declare const globalExpect: ExpectStatic;
declare const assert: Chai.Assert;
declare const should: () => Chai.Should;
/**
* Gives access to injected context provided from the main thread.
* This usually returns a value provided by `globalSetup` or an external library.
*/
declare function inject<T extends keyof ProvidedContext & string>(key: T): ProvidedContext[T];
/**
* Composable snapshot matcher helpers for building custom snapshot matchers
* with `expect.extend`.
*
* @experimental
* @see https://vitest.dev/guide/snapshot.html#custom-snapshot-matchers
*/
declare const Snapshots: {
/**
* Composable for building custom snapshot matchers via `expect.extend`.
* Call with `this` bound to the matcher state. Returns `{ pass, message }`
* compatible with the custom matcher return contract.
*
* @example
* ```ts
* import { Snapshots } from 'vitest/runtime'
*
* expect.extend({
* toMatchTrimmedSnapshot(received: string) {
* return Snapshots.toMatchSnapshot.call(this, received.slice(0, 10))
* },
* })
* ```
*
* @experimental
* @see https://vitest.dev/guide/snapshot.html#custom-snapshot-matchers
*/
toMatchSnapshot(this: MatcherState, received: unknown, propertiesOrHint?: object | string, hint?: string): SyncExpectationResult;
/**
* Composable for building custom inline snapshot matchers via `expect.extend`.
* Call with `this` bound to the matcher state. Returns `{ pass, message }`
* compatible with the custom matcher return contract.
*
* @example
* ```ts
* import { Snapshots } from 'vitest/runtime'
*
* expect.extend({
* toMatchTrimmedInlineSnapshot(received: string, inlineSnapshot?: string) {
* return Snapshots.toMatchInlineSnapshot.call(this, received.slice(0, 10), inlineSnapshot)
* },
* })
* ```
*
* @experimental
* @see https://vitest.dev/guide/snapshot.html#custom-snapshot-matchers
*/
toMatchInlineSnapshot(this: MatcherState, received: unknown, propertiesOrInlineSnapshot?: object | string, inlineSnapshotOrHint?: string, hint?: string): SyncExpectationResult;
/**
* Composable for building custom file snapshot matchers via `expect.extend`.
* Call with `this` bound to the matcher state. Returns a `Promise<{ pass, message }>`
* compatible with the custom matcher return contract.
*
* @example
* ```ts
* import { Snapshots } from 'vitest/runtime'
*
* expect.extend({
* async toMatchTrimmedFileSnapshot(received: string, file: string) {
* return Snapshots.toMatchFileSnapshot.call(this, received.slice(0, 10), file)
* },
* })
* ```
*
* @experimental
* @see https://vitest.dev/guide/snapshot.html#custom-snapshot-matchers
*/
toMatchFileSnapshot(this: MatcherState, received: unknown, filepath: string, hint?: string): AsyncExpectationResult;
/**
* Composable for building custom domain-based snapshot matchers via `expect.extend`.
*
* Call this from a matcher and pass the domain adapter that defines capture,
* rendering, parsing, and semantic matching behavior.
*
* @experimental
*/
toMatchDomainSnapshot(this: MatcherState, domain: DomainSnapshotAdapter<any, any>, received: unknown): ExpectationResult;
/**
* Composable for building custom domain-based inline snapshot matchers via `expect.extend`.
*
* Call this from a matcher and pass the domain adapter that defines capture,
* rendering, parsing, and semantic matching behavior.
*
* @experimental
*/
toMatchDomainInlineSnapshot(this: MatcherState, domain: DomainSnapshotAdapter<any, any>, received: unknown, inlineSnapshot?: string): ExpectationResult;
};
type WaitForCallback<T> = () => T | Promise<T>;
interface WaitForOptions {
/**
* @description Time in ms between each check callback
* @default 50ms
*/
interval?: number;
/**
* @description Time in ms after which the throw a timeout error
* @default 1000ms
*/
timeout?: number;
}
declare function waitFor<T>(callback: WaitForCallback<T>, options?: number | WaitForOptions): Promise<T>;
type WaitUntilCallback<T> = () => T | Promise<T>;
interface WaitUntilOptions extends Pick<WaitForOptions, "interval" | "timeout"> {}
type Truthy<T> = T extends false | "" | 0 | null | undefined ? never : T;
declare function waitUntil<T>(callback: WaitUntilCallback<T>, options?: number | WaitUntilOptions): Promise<Truthy<T>>;
type ESModuleExports = Record<string, unknown>;
interface VitestUtils {
/**
* Checks if fake timers are enabled.
*/
isFakeTimers: () => boolean;
/**
* This method wraps all further calls to timers until [`vi.useRealTimers()`](https://vitest.dev/api/vi#vi-userealtimers) is called.
*/
useFakeTimers: (config?: FakeTimerInstallOpts) => VitestUtils;
/**
* Restores mocked timers to their original implementations. All timers that were scheduled before will be discarded.
*/
useRealTimers: () => VitestUtils;
/**
* This method will call every timer that was initiated after [`vi.useFakeTimers`](https://vitest.dev/api/vi#vi-usefaketimers) call.
* It will not fire any timer that was initiated during its call.
*/
runOnlyPendingTimers: () => VitestUtils;
/**
* This method will asynchronously call every timer that was initiated after [`vi.useFakeTimers`](https://vitest.dev/api/vi#vi-usefaketimers) call, even asynchronous ones.
* It will not fire any timer that was initiated during its call.
*/
runOnlyPendingTimersAsync: () => Promise<VitestUtils>;
/**
* This method will invoke every initiated timer until the timer queue is empty. It means that every timer called during `runAllTimers` will be fired.
* If you have an infinite interval, it will throw after 10,000 tries (can be configured with [`fakeTimers.loopLimit`](https://vitest.dev/config/faketimers#faketimers-looplimit)).
*/
runAllTimers: () => VitestUtils;
/**
* This method will asynchronously invoke every initiated timer until the timer queue is empty. It means that every timer called during `runAllTimersAsync` will be fired even asynchronous timers.
* If you have an infinite interval, it will throw after 10 000 tries (can be configured with [`fakeTimers.loopLimit`](https://vitest.dev/config/faketimers#faketimers-looplimit)).
*/
runAllTimersAsync: () => Promise<VitestUtils>;
/**
* Calls every microtask that was queued by `process.nextTick`. This will also run all microtasks scheduled by themselves.
*/
runAllTicks: () => VitestUtils;
/**
* This method will invoke every initiated timer until the specified number of milliseconds is passed or the queue is empty - whatever comes first.
*/
advanceTimersByTime: (ms: number) => VitestUtils;
/**
* This method will invoke every initiated timer until the specified number of milliseconds is passed or the queue is empty - whatever comes first. This will include and await asynchronously set timers.
*/
advanceTimersByTimeAsync: (ms: number) => Promise<VitestUtils>;
/**
* Will call next available timer. Useful to make assertions between each timer call. You can chain call it to manage timers by yourself.
*/
advanceTimersToNextTimer: () => VitestUtils;
/**
* Will call next available timer and wait until it's resolved if it was set asynchronously. Useful to make assertions between each timer call.
*/
advanceTimersToNextTimerAsync: () => Promise<VitestUtils>;
/**
* Similar to [`vi.advanceTimersByTime`](https://vitest.dev/api/vi#vi-advancetimersbytime), but will advance timers by the milliseconds needed to execute callbacks currently scheduled with `requestAnimationFrame`.
*/
advanceTimersToNextFrame: () => VitestUtils;
/**
* Get the number of waiting timers.
*/
getTimerCount: () => number;
/**
* If fake timers are enabled, this method simulates a user changing the system clock (will affect date related API like `hrtime`, `performance.now` or `new Date()`) - however, it will not fire any timers.
* If fake timers are not enabled, this method will only mock `Date.*` and `new Date()` calls.
*/
setSystemTime: (time: number | string | Date) => VitestUtils;
/**
* Returns mocked current date. If date is not mocked the method will return `null`.
*/
getMockedSystemTime: () => Date | null;
/**
* When using `vi.useFakeTimers`, `Date.now` calls are mocked. If you need to get real time in milliseconds, you can call this function.
*/
getRealSystemTime: () => number;
/**
* Removes all timers that are scheduled to run. These timers will never run in the future.
*/
clearAllTimers: () => VitestUtils;
/**
* Controls how fake timers are advanced.
* @param mode The mode to use for advancing timers.
* - `manual`: The default behavior. Timers will only advance when you call one of `vi.advanceTimers...()` methods.
* - `nextTimerAsync`: Timers will be advanced automatically to the next available timer after each macrotask.
* - `interval`: Timers are advanced automatically by a specified interval.
* @param interval The interval in milliseconds to use when `mode` is `'interval'`.
*/
setTimerTickMode: ((mode: "manual" | "nextTimerAsync") => VitestUtils) & ((mode: "interval", interval?: number) => VitestUtils);
/**
* Creates a spy on a method or getter/setter of an object similar to [`vi.fn()`](https://vitest.dev/api/vi#vi-fn). It returns a [mock function](https://vitest.dev/api/mock).
* @example
* ```ts
* const cart = {
* getApples: () => 42
* }
*
* const spy = vi.spyOn(cart, 'getApples').mockReturnValue(10)
*
* expect(cart.getApples()).toBe(10)
* expect(spy).toHaveBeenCalled()
* expect(spy).toHaveReturnedWith(10)
* ```
*/
spyOn: typeof spyOn;
/**
* Creates a spy on a function, though can be initiated without one. Every time a function is invoked, it stores its call arguments, returns, and instances. Also, you can manipulate its behavior with [methods](https://vitest.dev/api/mock).
*
* If no function is given, mock will return `undefined`, when invoked.
* @example
* ```ts
* const getApples = vi.fn(() => 0)
*
* getApples()
*
* expect(getApples).toHaveBeenCalled()
* expect(getApples).toHaveReturnedWith(0)
*
* getApples.mockReturnValueOnce(5)
*
* expect(getApples()).toBe(5)
* expect(getApples).toHaveNthReturnedWith(2, 5)
* ```
*/
fn: typeof fn;
/**
* Wait for the callback to execute successfully. If the callback throws an error or returns a rejected promise it will continue to wait until it succeeds or times out.
*
* This is very useful when you need to wait for some asynchronous action to complete, for example, when you start a server and need to wait for it to start.
* @example
* ```ts
* const server = createServer()
*
* await vi.waitFor(
* () => {
* if (!server.isReady)
* throw new Error('Server not started')
*
* console.log('Server started')
* }, {
* timeout: 500, // default is 1000
* interval: 20, // default is 50
* }
* )
* ```
*/
waitFor: typeof waitFor;
/**
* Wraps a function to create an assertion helper. When an assertion fails inside the helper,
* the error stack trace will point to where the helper was called, not inside the helper itself.
* Works with both synchronous and asynchronous functions, and supports `expect.soft()`.
*
* @example
* ```ts
* const myEqual = vi.defineHelper((x, y) => {
* expect(x).toEqual(y)
* })
*
* test('example', () => {
* myEqual('left', 'right') // Error points to this line
* })
* ```
* Example output:
* ```
* FAIL example.test.ts > example
* AssertionError: expected 'left' to deeply equal 'right'
*
* Expected: "right"
* Received: "left"
*
* example.test.ts:6:3
* 4| test('example', () => {
* 5| myEqual('left', 'right')
* | ^
* 6| })
* ```
* @param fn The assertion function to wrap
* @returns A wrapped function with the same signature
*/
defineHelper: <F extends (...args: any) => any>(fn: F) => F;
/**
* This is similar to [`vi.waitFor`](https://vitest.dev/api/vi#vi-waitfor), but if the callback throws any errors, execution is immediately interrupted and an error message is received.
*
* If the callback returns a falsy value, the next check will continue until a truthy value is returned. This is useful when you need to wait for something to exist before taking the next step.
* @example
* ```ts
* const element = await vi.waitUntil(
* () => document.querySelector('.element'),
* {
* timeout: 500, // default is 1000
* interval: 20, // default is 50
* }
* )
*
* // do something with the element
* expect(element.querySelector('.element-child')).toBeTruthy()
* ```
*/
waitUntil: typeof waitUntil;
/**
* Run the factory before imports are evaluated. You can return a value from the factory
* to reuse it inside your [`vi.mock`](https://vitest.dev/api/vi#vi-mock) factory and tests.
*
* If used with [`vi.mock`](https://vitest.dev/api/vi#vi-mock), both will be hoisted in the order they are defined in.
*/
hoisted: <T>(factory: () => T) => T;
/**
* Mocks every import call to the module even if it was already statically imported.
*
* The call to `vi.mock` is hoisted to the top of the file, so you don't have access to variables declared in the global file scope
* unless they are defined with [`vi.hoisted`](https://vitest.dev/api/vi#vi-hoisted) before this call.
*
* Mocking algorithm is described in [documentation](https://vitest.dev/guide/mocking/modules).
* @param path Path to the module. Can be aliased, if your Vitest config supports it
* @param factory Mocked module factory. The result of this function will be an exports object
*/
mock(path: string, factory?: ModuleMockFactoryWithHelper | ModuleMockOptions): void;
mock<T>(module: Promise<T>, factory?: ModuleMockFactoryWithHelper<T> | ModuleMockOptions): void;
/**
* Removes module from mocked registry. All calls to import will return the original module even if it was mocked before.
*
* This call is hoisted to the top of the file, so it will only unmock modules that were defined in `setupFiles`, for example.
* @param path Path to the module. Can be aliased, if your Vitest config supports it
*/
unmock(path: string): void;
unmock(module: Promise<unknown>): void;
/**
* Mocks every subsequent [dynamic import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) call.
*
* Unlike [`vi.mock`](https://vitest.dev/api/vi#vi-mock), this method will not mock statically imported modules because it is not hoisted to the top of the file.
*
* Mocking algorithm is described in [documentation](https://vitest.dev/guide/mocking/modules).
* @param path Path to the module. Can be aliased, if your Vitest config supports it
* @param factory Mocked module factory. The result of this function will be an exports object
*
* @returns A disposable object that calls {@link doUnmock()} when disposed
*/
doMock(path: string, factory?: ModuleMockFactoryWithHelper | ModuleMockOptions): Disposable;
doMock<T>(module: Promise<T>, factory?: ModuleMockFactoryWithHelper<T> | ModuleMockOptions): Disposable;
/**
* Removes module from mocked registry. All subsequent calls to import will return original module.
*
* Unlike [`vi.unmock`](https://vitest.dev/api/vi#vi-unmock), this method is not hoisted to the top of the file.
* @param path Path to the module. Can be aliased, if your Vitest config supports it
*/
doUnmock(path: string): void;
doUnmock(module: Promise<unknown>): void;
/**
* Imports module, bypassing all checks if it should be mocked.
* Can be useful if you want to mock module partially.
* @example
* ```ts
* vi.mock('./example.js', async () => {
* const axios = await vi.importActual<typeof import('./example.js')>('./example.js')
*
* return { ...axios, get: vi.fn() }
* })
* ```
* @param path Path to the module. Can be aliased, if your config supports it
*/
importActual: <T = ESModuleExports>(path: string) => Promise<T>;
/**
* Imports a module with all of its properties and nested properties mocked.
*
* Mocking algorithm is described in [documentation](https://vitest.dev/guide/mocking/modules).
* @example
* ```ts
* const example = await vi.importMock<typeof import('./example.js')>('./example.js')
* example.calc.mockReturnValue(10)
* expect(example.calc()).toBe(10)
* ```
* @param path Path to the module. Can be aliased, if your config supports it
* @returns Fully mocked module
*/
importMock: <T = ESModuleExports>(path: string) => Promise<MaybeMockedDeep<T>>;
/**
* Deeply mocks properties and methods of a given object
* in the same way as `vi.mock()` mocks module exports.
*
* @example
* ```ts
* const original = {
* simple: () => 'value',
* nested: {
* method: () => 'real'
* },
* prop: 'foo',
* }
*
* const mocked = vi.mockObject(original)
* expect(mocked.simple()).toBe(undefined)
* expect(mocked.nested.method()).toBe(undefined)
* expect(mocked.prop).toBe('foo')
*
* mocked.simple.mockReturnValue('mocked')
* mocked.nested.method.mockReturnValue('mocked nested')
*
* expect(mocked.simple()).toBe('mocked')
* expect(mocked.nested.method()).toBe('mocked nested')
*
* const spied = vi.mockObject(original, { spy: true })
* expect(spied.simple()).toBe('value')
* expect(spied.simple).toHaveBeenCalled()
* expect(spied.simple.mock.results[0]).toEqual({ type: 'return', value: 'value' })
* ```
*
* @param value - The object to be mocked
* @returns A deeply mocked version of the input object
*/
mockObject: <T>(value: T, options?: ModuleMockOptions) => MaybeMockedDeep<T>;
/**
* Type helper for TypeScript. Just returns the object that was passed.
*
* When `partial` is `true` it will expect a `Partial<T>` as a return value. By default, this will only make TypeScript believe that
* the first level values are mocked. You can pass down `{ partial: true, deep: true }` to make nested objects also partial recursively.
* @example
* ```ts
* import example from './example.js'
* vi.mock('./example.js')
*
* test('1 + 1 equals 10' async () => {
* vi.mocked(example.calc).mockReturnValue(10)
* expect(example.calc(1, '+', 1)).toBe(10)
* })
* ```
* @param item Anything that can be mocked
* @param deep If the object is deeply mocked
* @param options If the object is partially or deeply mocked
*/
mocked: (<T>(item: T, deep?: false) => MaybeMocked<T>) & (<T>(item: T, deep: true) => MaybeMockedDeep<T>) & (<T>(item: T, options: {
partial?: false;
deep?: false;
}) => MaybeMocked<T>) & (<T>(item: T, options: {
partial?: false;
deep: true;
}) => MaybeMockedDeep<T>) & (<T>(item: T, options: {
partial: true;
deep?: false;
}) => MaybePartiallyMocked<T>) & (<T>(item: T, options: {
partial: true;
deep: true;
}) => MaybePartiallyMockedDeep<T>) & (<T>(item: T) => MaybeMocked<T>);
/**
* Checks that a given parameter is a mock function. If you are using TypeScript, it will also narrow down its type.
*/
isMockFunction: (fn: any) => fn is MockInstance;
/**
* Calls [`.mockClear()`](https://vitest.dev/api/mock#mockclear) on every mocked function.
*
* This will only empty `.mock` state, it will not affect mock implementations.
*
* This is useful if you need to clean up mocks between different assertions within a test.
*/
clearAllMocks: () => VitestUtils;
/**
* Calls [`.mockReset()`](https://vitest.dev/api/mock#mockreset) on every mocked function.
*
* This will empty `.mock` state, reset "once" implementations, and reset each mock's base implementation to its original.
*
* This is useful when you want to reset all mocks to their original states.
*/
resetAllMocks: () => VitestUtils;
/**
* Calls [`.mockRestore()`](https://vitest.dev/api/mock#mockrestore) on every mocked function.
*
* This will empty `.mock` state, restore all original mock implementations, and restore original descriptors of spied-on objects.
*
* This is useful for inter-test cleanup and/or removing mocks created by [`vi.spyOn(...)`](https://vitest.dev/api/vi#vi-spyon).
*/
restoreAllMocks: () => VitestUtils;
/**
* Makes value available on global namespace.
* Useful, if you want to have global variables available, like `IntersectionObserver`.
* You can return it back to original value with `vi.unstubAllGlobals`, or by enabling `unstubGlobals` config option.
*/
stubGlobal: (name: string | symbol | number, value: unknown) => VitestUtils;
/**
* Changes the value of `import.meta.env` and `process.env`.
* You can return it back to original value with `vi.unstubAllEnvs`, or by enabling `unstubEnvs` config option.
*/
stubEnv: <T extends string>(name: T, value: T extends "PROD" | "DEV" | "SSR" ? boolean : string | undefined) => VitestUtils;
/**
* Reset the value to original value that was available before first `vi.stubGlobal` was called.
*/
unstubAllGlobals: () => VitestUtils;
/**
* Reset environmental variables to the ones that were available before first `vi.stubEnv` was called.
*/
unstubAllEnvs: () => VitestUtils;
/**
* Resets modules registry by clearing the cache of all modules. This allows modules to be reevaluated when reimported.
* Top-level imports cannot be re-evaluated. Might be useful to isolate modules where local state conflicts between tests.
*
* This method does not reset mocks registry. To clear mocks registry, use [`vi.unmock`](https://vitest.dev/api/vi#vi-unmock) or [`vi.doUnmock`](https://vitest.dev/api/vi#vi-dounmock).
*/
resetModules: () => VitestUtils;
/**
* Wait for all imports to load. Useful, if you have a synchronous call that starts
* importing a module that you cannot await otherwise.
* Will also wait for new imports, started during the wait.
*/
dynamicImportSettled: () => Promise<void>;
/**
* Updates runtime config. You can only change values that are used when executing tests.
*/
setConfig: (config: RuntimeOptions) => void;
/**
* If config was changed with `vi.setConfig`, this will reset it to the original state().
*/
resetConfig: () => void;
}
declare const vitest: VitestUtils;
declare const vi: VitestUtils;
interface AssertType {
<T>(value: T): void;
}
declare const assertType: AssertType;
interface BrowserUI {
setCurrentFileId: (fileId: string) => void;
setIframeViewport: (width: number, height: number) => Promise<void>;
}
declare namespace Experimental {
export { ModuleDefinitionDiagnostic, ModuleDefinitionDurationsDiagnostic, ModuleDefinitionLocation, SourceModuleDiagnostic, SourceModuleLocations, UntrackedModuleDefinitionDiagnostic };
}
export { Experimental, LabelColor, ModuleGraphData, ProvidedContext, SerializedRootConfig, SerializedTestSpecification, Snapshots, UserConsoleLog, assert, assertType, createExpect, globalExpect as expect, inject, should, vi, vitest };
export type { AssertType, BrowserUI, ExternalResult, TransformResultWithSource, VitestUtils, WebSocketEvents, WebSocketHandlers, WebSocketRPC };

View File

@@ -0,0 +1,2 @@
import { viteReactRefreshWrapperPlugin as reactRefreshWrapperPlugin } from "rolldown/experimental";
export { reactRefreshWrapperPlugin };

View File

@@ -0,0 +1,110 @@
import * as util from "../core/util.js";
const error = () => {
const Sizable = {
string: { unit: "tekens", verb: "heeft" },
file: { unit: "bytes", verb: "heeft" },
array: { unit: "elementen", verb: "heeft" },
set: { unit: "elementen", verb: "heeft" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "invoer",
email: "emailadres",
url: "URL",
emoji: "emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "ISO datum en tijd",
date: "ISO datum",
time: "ISO tijd",
duration: "ISO duur",
ipv4: "IPv4-adres",
ipv6: "IPv6-adres",
cidrv4: "IPv4-bereik",
cidrv6: "IPv6-bereik",
base64: "base64-gecodeerde tekst",
base64url: "base64 URL-gecodeerde tekst",
json_string: "JSON string",
e164: "E.164-nummer",
jwt: "JWT",
template_literal: "invoer",
};
const TypeDictionary = {
nan: "NaN",
number: "getal",
};
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 `Ongeldige invoer: verwacht instanceof ${issue.expected}, ontving ${received}`;
}
return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Ongeldige invoer: verwacht ${util.stringifyPrimitive(issue.values[0])}`;
return `Ongeldige optie: verwacht één van ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
const longName = issue.origin === "date" ? "laat" : issue.origin === "string" ? "lang" : "groot";
if (sizing)
return `Te ${longName}: verwacht dat ${issue.origin ?? "waarde"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementen"} ${sizing.verb}`;
return `Te ${longName}: verwacht dat ${issue.origin ?? "waarde"} ${adj}${issue.maximum.toString()} is`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
const shortName = issue.origin === "date" ? "vroeg" : issue.origin === "string" ? "kort" : "klein";
if (sizing) {
return `Te ${shortName}: verwacht dat ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
}
return `Te ${shortName}: verwacht dat ${issue.origin} ${adj}${issue.minimum.toString()} is`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with") {
return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`;
}
if (_issue.format === "ends_with")
return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`;
if (_issue.format === "includes")
return `Ongeldige tekst: moet "${_issue.includes}" bevatten`;
if (_issue.format === "regex")
return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`;
return `Ongeldig: ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Ongeldig getal: moet een veelvoud van ${issue.divisor} zijn`;
case "unrecognized_keys":
return `Onbekende key${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Ongeldige key in ${issue.origin}`;
case "invalid_union":
return "Ongeldige invoer";
case "invalid_element":
return `Ongeldige waarde in ${issue.origin}`;
default:
return `Ongeldige invoer`;
}
};
};
export default function () {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1,88 @@
{
"name": "postcss",
"version": "8.5.26",
"description": "Tool for transforming styles with JS plugins",
"keywords": [
"css",
"manipulation",
"parser",
"postcss",
"preprocessor",
"rework",
"source map",
"transform",
"transpiler"
],
"homepage": "https://postcss.org/",
"bugs": {
"url": "https://github.com/postcss/postcss/issues"
},
"license": "MIT",
"author": "Andrey Sitnik <andrey@sitnik.es>",
"repository": "postcss/postcss",
"funding": [
{
"type": "opencollective",
"url": "https://opencollective.com/postcss/"
},
{
"type": "tidelift",
"url": "https://tidelift.com/funding/github/npm/postcss"
},
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"main": "./lib/postcss.js",
"browser": {
"./lib/terminal-highlight": false,
"source-map-js": false,
"path": false,
"url": false,
"fs": false
},
"types": "./lib/postcss.d.ts",
"exports": {
".": {
"import": "./lib/postcss.mjs",
"require": "./lib/postcss.js"
},
"./lib/at-rule": "./lib/at-rule.js",
"./lib/comment": "./lib/comment.js",
"./lib/container": "./lib/container.js",
"./lib/css-syntax-error": "./lib/css-syntax-error.js",
"./lib/declaration": "./lib/declaration.js",
"./lib/fromJSON": "./lib/fromJSON.js",
"./lib/input": "./lib/input.js",
"./lib/lazy-result": "./lib/lazy-result.js",
"./lib/no-work-result": "./lib/no-work-result.js",
"./lib/list": "./lib/list.js",
"./lib/map-generator": "./lib/map-generator.js",
"./lib/node": "./lib/node.js",
"./lib/parse": "./lib/parse.js",
"./lib/parser": "./lib/parser.js",
"./lib/postcss": "./lib/postcss.js",
"./lib/previous-map": "./lib/previous-map.js",
"./lib/processor": "./lib/processor.js",
"./lib/result": "./lib/result.js",
"./lib/root": "./lib/root.js",
"./lib/rule": "./lib/rule.js",
"./lib/stringifier": "./lib/stringifier.js",
"./lib/stringify": "./lib/stringify.js",
"./lib/symbols": "./lib/symbols.js",
"./lib/terminal-highlight": "./lib/terminal-highlight.js",
"./lib/tokenize": "./lib/tokenize.js",
"./lib/warn-once": "./lib/warn-once.js",
"./lib/warning": "./lib/warning.js",
"./package.json": "./package.json"
},
"dependencies": {
"nanoid": "^3.3.17",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
"engines": {
"node": "^10 || ^12 || >=14"
}
}

View File

@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isTypeImport = isTypeImport;
const scope_manager_1 = require("@typescript-eslint/scope-manager");
const utils_1 = require("@typescript-eslint/utils");
/**
* Determine whether a variable definition is a type import. e.g.:
*
* ```ts
* import type { Foo } from 'foo';
* import { type Bar } from 'bar';
* ```
*
* @param definition - The variable definition to check.
*/
function isTypeImport(definition) {
return (definition?.type === scope_manager_1.DefinitionType.ImportBinding &&
(definition.parent.importKind === 'type' ||
(definition.node.type === utils_1.AST_NODE_TYPES.ImportSpecifier &&
definition.node.importKind === 'type')));
}

View File

@@ -0,0 +1,244 @@
/**
* @fileoverview Rule to check the spacing around the * in generator functions.
* @author Jamund Ferguson
* @deprecated in ESLint v8.53.0
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const OVERRIDE_SCHEMA = {
oneOf: [
{
enum: ["before", "after", "both", "neither"],
},
{
type: "object",
properties: {
before: { type: "boolean" },
after: { type: "boolean" },
},
additionalProperties: false,
},
],
};
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
deprecated: {
message: "Formatting rules are being moved out of ESLint core.",
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
deprecatedSince: "8.53.0",
availableUntil: "11.0.0",
replacedBy: [
{
message:
"ESLint Stylistic now maintains deprecated stylistic core rules.",
url: "https://eslint.style/guide/migration",
plugin: {
name: "@stylistic/eslint-plugin",
url: "https://eslint.style",
},
rule: {
name: "generator-star-spacing",
url: "https://eslint.style/rules/generator-star-spacing",
},
},
],
},
type: "layout",
docs: {
description:
"Enforce consistent spacing around `*` operators in generator functions",
recommended: false,
url: "https://eslint.org/docs/latest/rules/generator-star-spacing",
},
fixable: "whitespace",
schema: [
{
oneOf: [
{
enum: ["before", "after", "both", "neither"],
},
{
type: "object",
properties: {
before: { type: "boolean" },
after: { type: "boolean" },
named: OVERRIDE_SCHEMA,
anonymous: OVERRIDE_SCHEMA,
method: OVERRIDE_SCHEMA,
},
additionalProperties: false,
},
],
},
],
messages: {
missingBefore: "Missing space before *.",
missingAfter: "Missing space after *.",
unexpectedBefore: "Unexpected space before *.",
unexpectedAfter: "Unexpected space after *.",
},
},
create(context) {
const optionDefinitions = {
before: { before: true, after: false },
after: { before: false, after: true },
both: { before: true, after: true },
neither: { before: false, after: false },
};
/**
* Returns resolved option definitions based on an option and defaults
* @param {any} option The option object or string value
* @param {Object} defaults The defaults to use if options are not present
* @returns {Object} the resolved object definition
*/
function optionToDefinition(option, defaults) {
if (!option) {
return defaults;
}
return typeof option === "string"
? optionDefinitions[option]
: Object.assign({}, defaults, option);
}
const modes = (function (option) {
const defaults = optionToDefinition(
option,
optionDefinitions.before,
);
return {
named: optionToDefinition(option.named, defaults),
anonymous: optionToDefinition(option.anonymous, defaults),
method: optionToDefinition(option.method, defaults),
};
})(context.options[0] || {});
const sourceCode = context.sourceCode;
/**
* Checks if the given token is a star token or not.
* @param {Token} token The token to check.
* @returns {boolean} `true` if the token is a star token.
*/
function isStarToken(token) {
return token.value === "*" && token.type === "Punctuator";
}
/**
* Gets the generator star token of the given function node.
* @param {ASTNode} node The function node to get.
* @returns {Token} Found star token.
*/
function getStarToken(node) {
return sourceCode.getFirstToken(
node.parent.method || node.parent.type === "MethodDefinition"
? node.parent
: node,
isStarToken,
);
}
/**
* capitalize a given string.
* @param {string} str the given string.
* @returns {string} the capitalized string.
*/
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1);
}
/**
* Checks the spacing between two tokens before or after the star token.
* @param {string} kind Either "named", "anonymous", or "method"
* @param {string} side Either "before" or "after".
* @param {Token} leftToken `function` keyword token if side is "before", or
* star token if side is "after".
* @param {Token} rightToken Star token if side is "before", or identifier
* token if side is "after".
* @returns {void}
*/
function checkSpacing(kind, side, leftToken, rightToken) {
if (
!!(rightToken.range[0] - leftToken.range[1]) !==
modes[kind][side]
) {
const after = leftToken.value === "*";
const spaceRequired = modes[kind][side];
const node = after ? leftToken : rightToken;
const messageId = `${spaceRequired ? "missing" : "unexpected"}${capitalize(side)}`;
context.report({
node,
messageId,
fix(fixer) {
if (spaceRequired) {
if (after) {
return fixer.insertTextAfter(node, " ");
}
return fixer.insertTextBefore(node, " ");
}
return fixer.removeRange([
leftToken.range[1],
rightToken.range[0],
]);
},
});
}
}
/**
* Enforces the spacing around the star if node is a generator function.
* @param {ASTNode} node A function expression or declaration node.
* @returns {void}
*/
function checkFunction(node) {
if (!node.generator) {
return;
}
const starToken = getStarToken(node);
const prevToken = sourceCode.getTokenBefore(starToken);
const nextToken = sourceCode.getTokenAfter(starToken);
let kind = "named";
if (
node.parent.type === "MethodDefinition" ||
(node.parent.type === "Property" && node.parent.method)
) {
kind = "method";
} else if (!node.id) {
kind = "anonymous";
}
// Only check before when preceded by `function`|`static` keyword
if (!(
kind === "method" &&
starToken === sourceCode.getFirstToken(node.parent)
)) {
checkSpacing(kind, "before", prevToken, starToken);
}
checkSpacing(kind, "after", starToken, nextToken);
}
return {
FunctionDeclaration: checkFunction,
FunctionExpression: checkFunction,
};
},
};

View File

@@ -0,0 +1,148 @@
import module$1, { isBuiltin } from 'node:module';
import { fileURLToPath } from 'node:url';
import { MessageChannel } from 'node:worker_threads';
import { initSyntaxLexers, hoistMocks } from '@vitest/mocker/transforms';
import { cleanUrl } from '@vitest/utils/helpers';
import { p as parse } from './acorn.B2iPLyUM.js';
import MagicString from 'magic-string';
import { resolve } from 'pathe';
import c from 'tinyrainbow';
import { distDir } from '../path.js';
import { t as toBuiltin } from './modules.BJuCwlRJ.js';
import 'node:path';
const NOW_LENGTH = Date.now().toString().length;
const REGEXP_VITEST = new RegExp(`%3Fvitest=\\d{${NOW_LENGTH}}`);
const REGEXP_MOCK_ACTUAL = /\?mock=actual/;
async function setupNodeLoaderHooks(worker) {
if (module$1.setSourceMapsSupport) module$1.setSourceMapsSupport(true);
else if (process.setSourceMapsEnabled) process.setSourceMapsEnabled(true);
if (worker.config.experimental.nodeLoader !== false) await initSyntaxLexers();
if (typeof module$1.registerHooks === "function") module$1.registerHooks({
resolve(specifier, context, nextResolve) {
if (specifier.includes("mock=actual")) {
// url is already resolved by `importActual`
const moduleId = specifier.replace(REGEXP_MOCK_ACTUAL, "");
const builtin = isBuiltin(moduleId);
return {
url: builtin ? toBuiltin(moduleId) : moduleId,
format: builtin ? "builtin" : void 0,
shortCircuit: true
};
}
const isVitest = specifier.includes("%3Fvitest=");
const result = nextResolve(isVitest ? specifier.replace(REGEXP_VITEST, "") : specifier, context);
// avoid tracking /node_modules/ module graph for performance reasons
if (context.parentURL && result.url && !result.url.includes("/node_modules/")) worker.rpc.ensureModuleGraphEntry(result.url, context.parentURL).catch(() => {
// ignore errors
});
// this is require for in-source tests to be invalidated if
// one of the files already imported it in --maxWorkers=1 --no-isolate
if (isVitest) result.url = `${result.url}?vitest=${Date.now()}`;
if (worker.config.experimental.nodeLoader === false || !context.parentURL || result.url.includes(distDir) || context.parentURL?.toString().includes(distDir)) return result;
const mockedResult = getNativeMocker()?.resolveMockedModule(result.url, context.parentURL);
if (mockedResult != null) return mockedResult;
return result;
},
load: worker.config.experimental.nodeLoader === false ? void 0 : createLoadHook()
});
else if (module$1.register) {
if (worker.config.experimental.nodeLoader !== false) console.warn(`${c.bgYellow(" WARNING ")} "module.registerHooks" is not supported in Node.js ${process.version}. This means that some features like module mocking or in-source testing are not supported. Upgrade your Node.js version to at least 22.15 or disable "experimental.nodeLoader" flag manually.\n`);
const { port1, port2 } = new MessageChannel();
port1.unref();
port2.unref();
port1.on("message", (data) => {
if (!data || typeof data !== "object") return;
switch (data.event) {
case "register-module-graph-entry": {
const { url, parentURL } = data;
worker.rpc.ensureModuleGraphEntry(url, parentURL);
return;
}
default: console.error("Unknown message event:", data.event);
}
});
/** Registers {@link file://./../nodejsWorkerLoader.ts} */
module$1.register("#nodejs-worker-loader", {
parentURL: import.meta.url,
data: { port: port2 },
transferList: [port2]
});
} else if (!process.versions.deno && !process.versions.bun) console.warn("\"module.registerHooks\" and \"module.register\" are not supported. Some Vitest features may not work. Please, use Node.js 18.19.0 or higher.");
}
function replaceInSourceMarker(url, source, ms) {
const re = /import\.meta\.vitest/g;
let match;
let overridden = false;
// eslint-disable-next-line no-cond-assign
while (match = re.exec(source)) {
const { index, "0": code } = match;
overridden = true;
// should it support process.vitest for CJS modules?
ms().overwrite(index, index + code.length, "IMPORT_META_TEST()");
}
if (overridden) {
const filename = resolve(fileURLToPath(url));
// appending instead of prepending because functions are hoisted and we don't change the offset
ms().append(`;\nfunction IMPORT_META_TEST() { return typeof __vitest_worker__ !== 'undefined' && __vitest_worker__.filepath === "${filename.replace(/"/g, "\\\"")}" ? __vitest_index__ : undefined; }`);
}
}
const ignoreFormats = new Set([
"addon",
"builtin",
"wasm"
]);
function createLoadHook(_worker) {
return (url, context, nextLoad) => {
const result = url.includes("mock=") && isBuiltin(cleanUrl(url)) ? { format: "commonjs" } : nextLoad(url, context);
if (result.format && ignoreFormats.has(result.format) || url.includes(distDir)) return result;
const mocker = getNativeMocker();
mocker?.checkCircularManualMock(url);
if (url.includes("mock=automock") || url.includes("mock=autospy")) {
const automockedResult = mocker?.loadAutomock(url, result);
if (automockedResult != null) return automockedResult;
return result;
}
if (url.includes("mock=manual")) {
const mockedResult = mocker?.loadManualMock(url, result);
if (mockedResult != null) return mockedResult;
return result;
}
// ignore non-vitest modules for performance reasons,
// vi.hoisted and vi.mock won't work outside of test files or setup files
if (!result.source || !url.includes("vitest=")) return result;
const filename = url.startsWith("file://") ? fileURLToPath(url) : url;
const source = result.source.toString();
const transformedCode = result.format?.includes("typescript") ? module$1.stripTypeScriptTypes(source) : source;
let _ms;
const ms = () => _ms || (_ms = new MagicString(source));
if (source.includes("import.meta.vitest")) replaceInSourceMarker(url, source, ms);
hoistMocks(transformedCode, filename, (code) => parse(code, {
ecmaVersion: "latest",
sourceType: result.format === "module" || result.format === "module-typescript" || result.format === "typescript" ? "module" : "script"
}), {
magicString: ms,
globalThisAccessor: "\"__vitest_mocker__\""
});
let code;
if (_ms) code = `${_ms.toString()}\n//# sourceMappingURL=${genSourceMapUrl(_ms.generateMap({
hires: "boundary",
source: filename
}))}`;
else code = source;
return {
format: result.format,
shortCircuit: true,
source: code
};
};
}
function genSourceMapUrl(map) {
if (typeof map !== "string") map = JSON.stringify(map);
return `data:application/json;base64,${Buffer.from(map).toString("base64")}`;
}
function getNativeMocker() {
return typeof __vitest_mocker__ !== "undefined" ? __vitest_mocker__ : void 0;
}
export { setupNodeLoaderHooks };

View File

@@ -0,0 +1,40 @@
/*! *****************************************************************************
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="es2020.intl" />
interface Date {
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locales A locale string, array of locale strings, Intl.Locale object, or array of Intl.Locale objects that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locales A locale string, array of locale strings, Intl.Locale object, or array of Intl.Locale objects that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locales A locale string, array of locale strings, Intl.Locale object, or array of Intl.Locale objects that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string;
}

View File

@@ -0,0 +1,16 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.es2019_array = void 0;
const base_config_1 = require("./base-config");
exports.es2019_array = {
libs: [],
variables: [
['FlatArray', base_config_1.TYPE],
['ReadonlyArray', base_config_1.TYPE],
['Array', base_config_1.TYPE],
],
};

View File

@@ -0,0 +1,49 @@
import type { $ZodRegistry } from "./registries.cjs";
import type * as schemas from "./schemas.cjs";
import { type Processor, type RegistryToJSONSchemaParams, type ToJSONSchemaParams, type ZodStandardJSONSchemaPayload } from "./to-json-schema.cjs";
export declare const stringProcessor: Processor<schemas.$ZodString>;
export declare const numberProcessor: Processor<schemas.$ZodNumber>;
export declare const booleanProcessor: Processor<schemas.$ZodBoolean>;
export declare const bigintProcessor: Processor<schemas.$ZodBigInt>;
export declare const symbolProcessor: Processor<schemas.$ZodSymbol>;
export declare const nullProcessor: Processor<schemas.$ZodNull>;
export declare const undefinedProcessor: Processor<schemas.$ZodUndefined>;
export declare const voidProcessor: Processor<schemas.$ZodVoid>;
export declare const neverProcessor: Processor<schemas.$ZodNever>;
export declare const anyProcessor: Processor<schemas.$ZodAny>;
export declare const unknownProcessor: Processor<schemas.$ZodUnknown>;
export declare const dateProcessor: Processor<schemas.$ZodDate>;
export declare const enumProcessor: Processor<schemas.$ZodEnum>;
export declare const literalProcessor: Processor<schemas.$ZodLiteral>;
export declare const nanProcessor: Processor<schemas.$ZodNaN>;
export declare const templateLiteralProcessor: Processor<schemas.$ZodTemplateLiteral>;
export declare const fileProcessor: Processor<schemas.$ZodFile>;
export declare const successProcessor: Processor<schemas.$ZodSuccess>;
export declare const customProcessor: Processor<schemas.$ZodCustom>;
export declare const functionProcessor: Processor<schemas.$ZodFunction>;
export declare const transformProcessor: Processor<schemas.$ZodTransform>;
export declare const mapProcessor: Processor<schemas.$ZodMap>;
export declare const setProcessor: Processor<schemas.$ZodSet>;
export declare const arrayProcessor: Processor<schemas.$ZodArray>;
export declare const objectProcessor: Processor<schemas.$ZodObject>;
export declare const unionProcessor: Processor<schemas.$ZodUnion>;
export declare const intersectionProcessor: Processor<schemas.$ZodIntersection>;
export declare const tupleProcessor: Processor<schemas.$ZodTuple>;
export declare const recordProcessor: Processor<schemas.$ZodRecord>;
export declare const nullableProcessor: Processor<schemas.$ZodNullable>;
export declare const nonoptionalProcessor: Processor<schemas.$ZodNonOptional>;
export declare const defaultProcessor: Processor<schemas.$ZodDefault>;
export declare const prefaultProcessor: Processor<schemas.$ZodPrefault>;
export declare const catchProcessor: Processor<schemas.$ZodCatch>;
export declare const pipeProcessor: Processor<schemas.$ZodPipe>;
export declare const readonlyProcessor: Processor<schemas.$ZodReadonly>;
export declare const promiseProcessor: Processor<schemas.$ZodPromise>;
export declare const optionalProcessor: Processor<schemas.$ZodOptional>;
export declare const lazyProcessor: Processor<schemas.$ZodLazy>;
export declare const allProcessors: Record<string, Processor<any>>;
export declare function toJSONSchema<T extends schemas.$ZodType>(schema: T, params?: ToJSONSchemaParams): ZodStandardJSONSchemaPayload<T>;
export declare function toJSONSchema(registry: $ZodRegistry<{
id?: string | undefined;
}>, params?: RegistryToJSONSchemaParams): {
schemas: Record<string, ZodStandardJSONSchemaPayload<schemas.$ZodType>>;
};

View File

@@ -0,0 +1,333 @@
/**
* @fileoverview Traverser for SourceCode objects.
* @author Nicholas C. Zakas
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const { parse, matches } = require("./esquery");
const vk = require("eslint-visitor-keys");
//-----------------------------------------------------------------------------
// Typedefs
//-----------------------------------------------------------------------------
/**
* @import { Language, SourceCode } from "@eslint/core";
* @import { ESQueryOptions } from "esquery";
* @import { ESQueryParsedSelector } from "./esquery.js";
* @import { SourceCodeVisitor } from "./source-code-visitor.js";
*/
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
const STEP_KIND_VISIT = 1;
const STEP_KIND_CALL = 2;
/**
* Compares two ESQuery selectors by specificity.
* @param {ESQueryParsedSelector} a The first selector to compare.
* @param {ESQueryParsedSelector} b The second selector to compare.
* @returns {number} A negative number if `a` is less specific than `b` or they are equally specific and `a` <= `b` alphabetically, a positive number if `a` is more specific than `b`.
*/
function compareSpecificity(a, b) {
return a.compare(b);
}
/**
* Helper to wrap ESQuery operations.
*/
class ESQueryHelper {
/**
* Creates a new instance.
* @param {SourceCodeVisitor} visitor The visitor containing the functions to call.
* @param {ESQueryOptions} esqueryOptions `esquery` options for traversing custom nodes.
*/
constructor(visitor, esqueryOptions) {
/**
* The visitor to use during traversal.
* @type {SourceCodeVisitor}
*/
this.visitor = visitor;
/**
* The options for `esquery` to use during matching.
* @type {ESQueryOptions}
*/
this.esqueryOptions = esqueryOptions;
/**
* A map of node type to selectors targeting that node type on the
* enter phase of traversal.
* @type {Map<string, ESQueryParsedSelector[]>}
*/
this.enterSelectorsByNodeType = new Map();
/**
* A map of node type to selectors targeting that node type on the
* exit phase of traversal.
* @type {Map<string, ESQueryParsedSelector[]>}
*/
this.exitSelectorsByNodeType = new Map();
/**
* An array of selectors that match any node type on the
* enter phase of traversal.
* @type {ESQueryParsedSelector[]}
*/
this.anyTypeEnterSelectors = [];
/**
* An array of selectors that match any node type on the
* exit phase of traversal.
* @type {ESQueryParsedSelector[]}
*/
this.anyTypeExitSelectors = [];
visitor.forEachName(rawSelector => {
const selector = parse(rawSelector);
/*
* If this selector has identified specific node types,
* add it to the map for these node types for faster lookup.
*/
if (selector.nodeTypes) {
const typeMap = selector.isExit
? this.exitSelectorsByNodeType
: this.enterSelectorsByNodeType;
selector.nodeTypes.forEach(nodeType => {
if (!typeMap.has(nodeType)) {
typeMap.set(nodeType, []);
}
typeMap.get(nodeType).push(selector);
});
return;
}
/*
* Remaining selectors are added to the "any type" selectors
* list for the appropriate phase of traversal. This ensures
* that all selectors will still be applied even if no
* specific node type is matched.
*/
const selectors = selector.isExit
? this.anyTypeExitSelectors
: this.anyTypeEnterSelectors;
selectors.push(selector);
});
// sort all selectors by specificity for prioritizing call order
this.anyTypeEnterSelectors.sort(compareSpecificity);
this.anyTypeExitSelectors.sort(compareSpecificity);
this.enterSelectorsByNodeType.forEach(selectorList =>
selectorList.sort(compareSpecificity),
);
this.exitSelectorsByNodeType.forEach(selectorList =>
selectorList.sort(compareSpecificity),
);
}
/**
* Checks if a node matches a given selector.
* @param {ASTNode} node The node to check
* @param {ASTNode[]} ancestry The ancestry of the node being checked.
* @param {ESQueryParsedSelector} selector An AST selector descriptor
* @returns {boolean} `true` if the selector matches the node, `false` otherwise
*/
matches(node, ancestry, selector) {
return matches(node, selector.root, ancestry, this.esqueryOptions);
}
/**
* Calculates all appropriate selectors to a node, in specificity order
* @param {ASTNode} node The node to check
* @param {ASTNode[]} ancestry The ancestry of the node being checked.
* @param {boolean} isExit `false` if the node is currently being entered, `true` if it's currently being exited
* @returns {string[]} An array of selectors that match the node.
*/
calculateSelectors(node, ancestry, isExit) {
const nodeTypeKey = this.esqueryOptions?.nodeTypeKey || "type";
const selectors = [];
/*
* Get the selectors that may match this node. First, check
* to see if the node type has specific selectors,
* then gather the "any type" selectors.
*/
const selectorsByNodeType =
(isExit
? this.exitSelectorsByNodeType
: this.enterSelectorsByNodeType
).get(node[nodeTypeKey]) || [];
const anyTypeSelectors = isExit
? this.anyTypeExitSelectors
: this.anyTypeEnterSelectors;
/*
* selectorsByNodeType and anyTypeSelectors were already sorted by specificity in the constructor.
* Iterate through each of them, applying selectors in the right order.
*/
let selectorsByNodeTypeIndex = 0;
let anyTypeSelectorsIndex = 0;
while (
selectorsByNodeTypeIndex < selectorsByNodeType.length ||
anyTypeSelectorsIndex < anyTypeSelectors.length
) {
/*
* If we've already exhausted the selectors for this node type,
* or if the next any type selector is more specific than the
* next selector for this node type, apply the any type selector.
*/
const hasMoreNodeTypeSelectors =
selectorsByNodeTypeIndex < selectorsByNodeType.length;
const hasMoreAnyTypeSelectors =
anyTypeSelectorsIndex < anyTypeSelectors.length;
const anyTypeSelector = anyTypeSelectors[anyTypeSelectorsIndex];
const nodeTypeSelector =
selectorsByNodeType[selectorsByNodeTypeIndex];
// Only compare specificity if both selectors exist
const isAnyTypeSelectorLessSpecific =
hasMoreAnyTypeSelectors &&
hasMoreNodeTypeSelectors &&
anyTypeSelector.compare(nodeTypeSelector) < 0;
if (!hasMoreNodeTypeSelectors || isAnyTypeSelectorLessSpecific) {
anyTypeSelectorsIndex++;
if (this.matches(node, ancestry, anyTypeSelector)) {
selectors.push(anyTypeSelector.source);
}
} else {
selectorsByNodeTypeIndex++;
if (this.matches(node, ancestry, nodeTypeSelector)) {
selectors.push(nodeTypeSelector.source);
}
}
}
return selectors;
}
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Traverses source code and ensures that visitor methods are called when
* entering and leaving each node.
*/
class SourceCodeTraverser {
/**
* The language of the source code being traversed.
* @type {Language}
*/
#language;
/**
* Map of languages to instances of this class.
* @type {WeakMap<Language, SourceCodeTraverser>}
*/
static instances = new WeakMap();
/**
* Creates a new instance.
* @param {Language} language The language of the source code being traversed.
*/
constructor(language) {
this.#language = language;
}
static getInstance(language) {
if (!this.instances.has(language)) {
this.instances.set(language, new this(language));
}
return this.instances.get(language);
}
/**
* Traverses the given source code synchronously.
* @param {SourceCode} sourceCode The source code to traverse.
* @param {SourceCodeVisitor} visitor The emitter to use for events.
* @param {Object} options Options for traversal.
* @param {ReturnType<SourceCode["traverse"]>} options.steps The steps to take during traversal.
* @returns {void}
* @throws {Error} If an error occurs during traversal.
*/
traverseSync(sourceCode, visitor, { steps } = {}) {
const esquery = new ESQueryHelper(visitor, {
visitorKeys: sourceCode.visitorKeys ?? this.#language.visitorKeys,
fallback: vk.getKeys,
matchClass: this.#language.matchesSelectorClass ?? (() => false),
nodeTypeKey: this.#language.nodeTypeKey,
});
const currentAncestry = [];
for (const step of steps ?? sourceCode.traverse()) {
switch (step.kind) {
case STEP_KIND_VISIT: {
try {
if (step.phase === 1) {
esquery
.calculateSelectors(
step.target,
currentAncestry,
false,
)
.forEach(selector => {
visitor.callSync(
selector,
...(step.args ?? [step.target]),
);
});
currentAncestry.unshift(step.target);
} else {
currentAncestry.shift();
esquery
.calculateSelectors(
step.target,
currentAncestry,
true,
)
.forEach(selector => {
visitor.callSync(
selector,
...(step.args ?? [step.target]),
);
});
}
} catch (err) {
err.currentNode = step.target;
throw err;
}
break;
}
case STEP_KIND_CALL: {
visitor.callSync(step.target, ...step.args);
break;
}
default:
throw new Error(
`Invalid traversal step found: "${step.kind}".`,
);
}
}
}
}
module.exports = { SourceCodeTraverser };

View File

@@ -0,0 +1,248 @@
/**
* @fileoverview Disallow reassigning function parameters.
* @author Nat Burns
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const stopNodePattern =
/(?:Statement|Declaration|Function(?:Expression)?|Program)$/u;
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Disallow reassigning function parameters",
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-param-reassign",
},
schema: [
{
oneOf: [
{
type: "object",
properties: {
props: {
enum: [false],
},
},
additionalProperties: false,
},
{
type: "object",
properties: {
props: {
enum: [true],
},
ignorePropertyModificationsFor: {
type: "array",
items: {
type: "string",
},
uniqueItems: true,
},
ignorePropertyModificationsForRegex: {
type: "array",
items: {
type: "string",
},
uniqueItems: true,
},
},
additionalProperties: false,
},
],
},
],
messages: {
assignmentToFunctionParam:
"Assignment to function parameter '{{name}}'.",
assignmentToFunctionParamProp:
"Assignment to property of function parameter '{{name}}'.",
},
},
create(context) {
const props = context.options[0] && context.options[0].props;
const ignoredPropertyAssignmentsFor =
(context.options[0] &&
context.options[0].ignorePropertyModificationsFor) ||
[];
const ignoredPropertyAssignmentsForRegex =
(context.options[0] &&
context.options[0].ignorePropertyModificationsForRegex) ||
[];
const sourceCode = context.sourceCode;
/**
* Checks whether or not the reference modifies properties of its variable.
* @param {Reference} reference A reference to check.
* @returns {boolean} Whether or not the reference modifies properties of its variable.
*/
function isModifyingProp(reference) {
let node = reference.identifier;
let parent = node.parent;
while (
parent &&
(!stopNodePattern.test(parent.type) ||
parent.type === "ForInStatement" ||
parent.type === "ForOfStatement")
) {
switch (parent.type) {
// e.g. foo.a = 0;
case "AssignmentExpression":
return parent.left === node;
// e.g. ++foo.a;
case "UpdateExpression":
return true;
// e.g. delete foo.a;
case "UnaryExpression":
if (parent.operator === "delete") {
return true;
}
break;
// e.g. for (foo.a in b) {}
case "ForInStatement":
case "ForOfStatement":
if (parent.left === node) {
return true;
}
// this is a stop node for parent.right and parent.body
return false;
// EXCLUDES: e.g. cache.get(foo.a).b = 0;
case "CallExpression":
if (parent.callee !== node) {
return false;
}
break;
// EXCLUDES: e.g. cache[foo.a] = 0;
case "MemberExpression":
if (parent.property === node) {
return false;
}
break;
// EXCLUDES: e.g. ({ [foo]: a }) = bar;
case "Property":
if (parent.key === node) {
return false;
}
break;
// EXCLUDES: e.g. (foo ? a : b).c = bar;
case "ConditionalExpression":
if (parent.test === node) {
return false;
}
break;
// no default
}
node = parent;
parent = node.parent;
}
return false;
}
/**
* Tests that an identifier name matches any of the ignored property assignments.
* First we test strings in ignoredPropertyAssignmentsFor.
* Then we instantiate and test RegExp objects from ignoredPropertyAssignmentsForRegex strings.
* @param {string} identifierName A string that describes the name of an identifier to
* ignore property assignments for.
* @returns {boolean} Whether the string matches an ignored property assignment regular expression or not.
*/
function isIgnoredPropertyAssignment(identifierName) {
return (
ignoredPropertyAssignmentsFor.includes(identifierName) ||
ignoredPropertyAssignmentsForRegex.some(ignored =>
new RegExp(ignored, "u").test(identifierName),
)
);
}
/**
* Reports a reference if is non initializer and writable.
* @param {Reference} reference A reference to check.
* @param {number} index The index of the reference in the references.
* @param {Reference[]} references The array that the reference belongs to.
* @returns {void}
*/
function checkReference(reference, index, references) {
const identifier = reference.identifier;
if (
identifier &&
!reference.init &&
/*
* Destructuring assignments can have multiple default value,
* so possibly there are multiple writeable references for the same identifier.
*/
(index === 0 || references[index - 1].identifier !== identifier)
) {
if (reference.isWrite()) {
context.report({
node: identifier,
messageId: "assignmentToFunctionParam",
data: { name: identifier.name },
});
} else if (
props &&
isModifyingProp(reference) &&
!isIgnoredPropertyAssignment(identifier.name)
) {
context.report({
node: identifier,
messageId: "assignmentToFunctionParamProp",
data: { name: identifier.name },
});
}
}
}
/**
* Finds and reports references that are non initializer and writable.
* @param {Variable} variable A variable to check.
* @returns {void}
*/
function checkVariable(variable) {
if (variable.defs[0].type === "Parameter") {
variable.references.forEach(checkReference);
}
}
/**
* Checks parameters of a given function node.
* @param {ASTNode} node A function node to check.
* @returns {void}
*/
function checkForFunction(node) {
sourceCode.getDeclaredVariables(node).forEach(checkVariable);
}
return {
// `:exit` is needed for the `node.parent` property of identifier nodes.
"FunctionDeclaration:exit": checkForFunction,
"FunctionExpression:exit": checkForFunction,
"ArrowFunctionExpression:exit": checkForFunction,
};
},
};

View File

@@ -0,0 +1,278 @@
# flat-cache - Changelog
## v3.0.4
- **Refactoring**
- add files by name to the list of exported files - [89a2698](https://github.com/royriojas/flat-cache/commit/89a2698), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 02:35:39
## v3.0.3
- **Bug Fixes**
- Fix wrong eslint command - [f268e42](https://github.com/royriojas/flat-cache/commit/f268e42), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 02:15:04
## v3.0.2
- **Refactoring**
- Update the files paths - [6983a80](https://github.com/royriojas/flat-cache/commit/6983a80), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:58:39
- Move code to src/ - [18ed6e8](https://github.com/royriojas/flat-cache/commit/18ed6e8), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:57:17
- Change eslint-cache location - [beed74c](https://github.com/royriojas/flat-cache/commit/beed74c), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:48:32
## v3.0.1
- **Refactoring**
- Remove unused deps - [8c6d9dc](https://github.com/royriojas/flat-cache/commit/8c6d9dc), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:43:29
## v3.0.0
- **Refactoring**
- Fix engines - [52b824c](https://github.com/royriojas/flat-cache/commit/52b824c), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:01:52
- **Other changes**
- Replace write with combination of mkdir and writeFile ([#49](https://github.com/royriojas/flat-cache/issues/49)) - [ef48276](https://github.com/royriojas/flat-cache/commit/ef48276), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 08/11/2020 00:17:15
Node v10 introduced a great "recursive" option for mkdir which allows to
get rid from mkdirp package and easily rewrite "write" package usage
with two function calls.
https://nodejs.org/api/fs.html#fs_fs_mkdir_path_options_callback
- Added a testcase for clearAll ([#48](https://github.com/royriojas/flat-cache/issues/48)) - [45b51ca](https://github.com/royriojas/flat-cache/commit/45b51ca), [Aaron Chen](https://github.com/Aaron Chen), 21/05/2020 08:40:03
- requet node>=10 - [a5c482c](https://github.com/royriojas/flat-cache/commit/a5c482c), [yumetodo](https://github.com/yumetodo), 10/04/2020 23:14:53
thanks @SuperITMan
- Update README.md - [29fe40b](https://github.com/royriojas/flat-cache/commit/29fe40b), [Roy Riojas](https://github.com/Roy Riojas), 10/04/2020 20:08:05
- reduce vulnerability to 1 - [e9db1b2](https://github.com/royriojas/flat-cache/commit/e9db1b2), [yumetodo](https://github.com/yumetodo), 30/03/2020 11:10:43
- reduce vulnerabilities dependencies to 8 - [b58d196](https://github.com/royriojas/flat-cache/commit/b58d196), [yumetodo](https://github.com/yumetodo), 30/03/2020 10:54:56
- use prettier instead of esbeautifier - [03b1db7](https://github.com/royriojas/flat-cache/commit/03b1db7), [yumetodo](https://github.com/yumetodo), 30/03/2020 10:27:14
- update proxyquire - [c2f048d](https://github.com/royriojas/flat-cache/commit/c2f048d), [yumetodo](https://github.com/yumetodo), 30/03/2020 10:16:16
- update flatted and mocha - [a0e56da](https://github.com/royriojas/flat-cache/commit/a0e56da), [yumetodo](https://github.com/yumetodo), 30/03/2020 09:46:45
mocha > mkdirp is updated
istanble >>> optimist > minimist is not updated
- drop support node.js < 10 in develop - [beba691](https://github.com/royriojas/flat-cache/commit/beba691), [yumetodo](https://github.com/yumetodo), 18/03/2020 01:31:09
see mkdirp
- npm aufit fix(still remains) - [ce166cb](https://github.com/royriojas/flat-cache/commit/ce166cb), [yumetodo](https://github.com/yumetodo), 18/03/2020 01:18:08
37 vulnerabilities required manual review and could not be updated
- updtate sinon - [9f2d1b6](https://github.com/royriojas/flat-cache/commit/9f2d1b6), [yumetodo](https://github.com/yumetodo), 18/03/2020 01:17:51
- apply eslint-plugin-mocha - [07343b5](https://github.com/royriojas/flat-cache/commit/07343b5), [yumetodo](https://github.com/yumetodo), 13/03/2020 22:17:21
- Less strint version check ([#44](https://github.com/royriojas/flat-cache/issues/44)) - [92aca1c](https://github.com/royriojas/flat-cache/commit/92aca1c), [Wojciech Maj](https://github.com/Wojciech Maj), 13/11/2019 16:18:25
- Use ^ version matching for production dependencies
- Run npm audit fix
- **Bug Fixes**
- update dependencies and use eslint directly - [73fbed2](https://github.com/royriojas/flat-cache/commit/73fbed2), [yumetodo](https://github.com/yumetodo), 18/03/2020 01:17:27
## v2.0.1
- **Refactoring**
- upgrade node modules to latest versions - [6402ed3](https://github.com/royriojas/flat-cache/commit/6402ed3), [Roy Riojas](https://github.com/Roy Riojas), 08/01/2019 18:47:05
## v2.0.0
- **Bug Fixes**
- upgrade package.json lock file - [8d21c7b](https://github.com/royriojas/flat-cache/commit/8d21c7b), [Roy Riojas](https://github.com/Roy Riojas), 08/01/2019 17:03:13
- Use the same versions of node_js that eslint use - [8d23379](https://github.com/royriojas/flat-cache/commit/8d23379), [Roy Riojas](https://github.com/Roy Riojas), 08/01/2019 16:25:11
- **Other changes**
- Replace circular-json with flatted ([#36](https://github.com/royriojas/flat-cache/issues/36)) - [b93aced](https://github.com/royriojas/flat-cache/commit/b93aced), [C. K. Tang](https://github.com/C. K. Tang), 08/01/2019 17:03:01
- Change JSON parser from circular-json to flatted & 1 more changes ([#37](https://github.com/royriojas/flat-cache/issues/37)) - [745e65a](https://github.com/royriojas/flat-cache/commit/745e65a), [Andy Chen](https://github.com/Andy Chen), 08/01/2019 16:17:20
- Change JSON parser from circular-json to flatted & 1 more changes
- Change JSON parser from circular-json
- Audited 2 vulnerabilities
- Update package.json
- Update Engine require
- There's a bunch of dependencies in this pkg requires node >=4, so I changed it to 4
- Remove and add node versions
- I have seen this pkg is not available with node 0.12 so I removed it
- I have added a popular used LTS version of node - 10
## v1.3.4
- **Refactoring**
- Add del.js and utils.js to the list of files to be beautified - [9d0ca9b](https://github.com/royriojas/flat-cache/commit/9d0ca9b), [Roy Riojas](https://github.com/Roy Riojas), 14/11/2018 12:19:02
## v1.3.3
- **Refactoring**
- Make sure package-lock.json is up to date - [a7d2598](https://github.com/royriojas/flat-cache/commit/a7d2598), [Roy Riojas](https://github.com/Roy Riojas), 14/11/2018 11:36:08
- **Other changes**
- Removed the need for del ([#33](https://github.com/royriojas/flat-cache/issues/33)) - [c429012](https://github.com/royriojas/flat-cache/commit/c429012), [S. Gilroy](https://github.com/S. Gilroy), 13/11/2018 13:56:37
- Removed the need for del
Removed the need for del as newer versions have broken backwards
compatibility. del mainly uses rimraf for deleting folders
and files, replaceing it with rimraf only is a minimal change.
- Disable glob on rimraf calls
- Added glob disable to wrong call
- Wrapped rimraf to simplify solution
## v1.3.2
- **Refactoring**
- remove yarn.lock file - [704c6c4](https://github.com/royriojas/flat-cache/commit/704c6c4), [Roy Riojas](https://github.com/Roy Riojas), 07/11/2018 15:41:08
- **Other changes**
- replace circular-json with flatted ([#23](https://github.com/royriojas/flat-cache/issues/23))" - [db12d74](https://github.com/royriojas/flat-cache/commit/db12d74), [Roy Riojas](https://github.com/Roy Riojas), 07/11/2018 15:40:39
This reverts commit 00f689277a75e85fef28e6a048fad227afc525e6.
## v1.3.1
- **Refactoring**
- upgrade deps to remove some security warnings - [f405719](https://github.com/royriojas/flat-cache/commit/f405719), [Roy Riojas](https://github.com/Roy Riojas), 06/11/2018 12:07:31
- **Bug Fixes**
- replace circular-json with flatted ([#23](https://github.com/royriojas/flat-cache/issues/23)) - [00f6892](https://github.com/royriojas/flat-cache/commit/00f6892), [Terry](https://github.com/Terry), 05/11/2018 18:44:16
- **Other changes**
- update del to v3.0.0 ([#26](https://github.com/royriojas/flat-cache/issues/26)) - [d42883f](https://github.com/royriojas/flat-cache/commit/d42883f), [Patrick Silva](https://github.com/Patrick Silva), 03/11/2018 01:00:44
Closes <a target="_blank" class="info-link" href="https://github.com/royriojas/flat-cache/issues/25"><span>#25</span></a>
## v1.3.0
- **Other changes**
- Added #all method ([#16](https://github.com/royriojas/flat-cache/issues/16)) - [12293be](https://github.com/royriojas/flat-cache/commit/12293be), [Ozair Patel](https://github.com/Ozair Patel), 25/09/2017 14:46:38
- Added #all method
- Added #all method test
- Updated readme
- Added yarn.lock
- Added more keys for #all test
- Beautified file
- fix changelog title style ([#14](https://github.com/royriojas/flat-cache/issues/14)) - [af8338a](https://github.com/royriojas/flat-cache/commit/af8338a), [前端小武](https://github.com/前端小武), 19/12/2016 20:34:48
## v1.2.2
- **Bug Fixes**
- Do not crash if cache file is invalid JSON. ([#13](https://github.com/royriojas/flat-cache/issues/13)) - [87beaa6](https://github.com/royriojas/flat-cache/commit/87beaa6), [Roy Riojas](https://github.com/Roy Riojas), 19/12/2016 18:03:35
Fixes <a target="_blank" class="info-link" href="https://github.com/royriojas/flat-cache/issues/12"><span>#12</span></a>
Not sure under which situations a cache file might exist that does
not contain a valid JSON structure, but just in case to cover
the possibility of this happening a try catch block has been added
If the cache is somehow not valid the cache will be discarded an a
a new cache will be stored instead
- **Other changes**
- Added travis ci support for modern node versions ([#11](https://github.com/royriojas/flat-cache/issues/11)) - [1c2b1f7](https://github.com/royriojas/flat-cache/commit/1c2b1f7), [Amila Welihinda](https://github.com/Amila Welihinda), 10/11/2016 23:47:52
- Bumping `circular-son` version ([#10](https://github.com/royriojas/flat-cache/issues/10)) - [4d5e861](https://github.com/royriojas/flat-cache/commit/4d5e861), [Andrea Giammarchi](https://github.com/Andrea Giammarchi), 02/08/2016 07:13:52
As mentioned in https://github.com/WebReflection/circular-json/issues/25 `circular-json` wan't rightly implementing the license field.
Latest version bump changed only that bit so that ESLint should now be happy.
## v1.2.1
- **Bug Fixes**
- Add missing utils.js file to the package. closes [#8](https://github.com/royriojas/flat-cache/issues/8) - [ec10cf2](https://github.com/royriojas/flat-cache/commit/ec10cf2), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 02:18:57
## v1.2.0
- **Documentation**
- Add documentation about noPrune option - [23e11f9](https://github.com/royriojas/flat-cache/commit/23e11f9), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 02:06:49
## v1.0.11
- **Features**
- Add noPrune option to cache.save() method. closes [#7](https://github.com/royriojas/flat-cache/issues/7) - [2c8016a](https://github.com/royriojas/flat-cache/commit/2c8016a), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 02:00:29
- Add json read and write utility based on circular-json - [c31081e](https://github.com/royriojas/flat-cache/commit/c31081e), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 08:58:17
- **Bug Fixes**
- Remove UTF16 BOM stripping - [4a41e22](https://github.com/royriojas/flat-cache/commit/4a41e22), [Jean Ponchon](https://github.com/Jean Ponchon), 29/07/2016 02:18:06
Since we control both writing and reading of JSON stream, there no needs
to handle unicode BOM.
- Use circular-json to handle circular references (fix [#5](https://github.com/royriojas/flat-cache/issues/5)) - [cd7aeed](https://github.com/royriojas/flat-cache/commit/cd7aeed), [Jean Ponchon](https://github.com/Jean Ponchon), 25/07/2016 11:11:59
- **Tests Related fixes**
- Add missing file from eslint test - [d6fa3c3](https://github.com/royriojas/flat-cache/commit/d6fa3c3), [Jean Ponchon](https://github.com/Jean Ponchon), 29/07/2016 02:15:51
- Add test for circular json serialization / deserialization - [07d2ddd](https://github.com/royriojas/flat-cache/commit/07d2ddd), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 08:59:36
- **Refactoring**
- Remove unused read-json-sync - [2be1c24](https://github.com/royriojas/flat-cache/commit/2be1c24), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 08:59:18
- **Build Scripts Changes**
- travis tests on 0.12 and 4x - [3a613fd](https://github.com/royriojas/flat-cache/commit/3a613fd), [royriojas](https://github.com/royriojas), 15/11/2015 14:34:40
## v1.0.10
- **Build Scripts Changes**
- add eslint-fix task - [fd29e52](https://github.com/royriojas/flat-cache/commit/fd29e52), [royriojas](https://github.com/royriojas), 01/11/2015 15:04:08
- make sure the test script also verify beautification and linting of files before running tests - [e94e176](https://github.com/royriojas/flat-cache/commit/e94e176), [royriojas](https://github.com/royriojas), 01/11/2015 11:54:48
- **Other changes**
- add clearAll for cacheDir - [97383d9](https://github.com/royriojas/flat-cache/commit/97383d9), [xieyaowu](https://github.com/xieyaowu), 31/10/2015 21:02:18
## v1.0.9
- **Bug Fixes**
- wrong default values for changelogx user repo name - [7bb52d1](https://github.com/royriojas/flat-cache/commit/7bb52d1), [royriojas](https://github.com/royriojas), 11/09/2015 15:59:30
## v1.0.8
- **Build Scripts Changes**
- test against node 4 - [c395b66](https://github.com/royriojas/flat-cache/commit/c395b66), [royriojas](https://github.com/royriojas), 11/09/2015 15:51:39
## v1.0.7
- **Other changes**
- Move dependencies into devDep - [7e47099](https://github.com/royriojas/flat-cache/commit/7e47099), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 11/09/2015 15:10:57
- **Documentation**
- Add missing changelog link - [f51197a](https://github.com/royriojas/flat-cache/commit/f51197a), [royriojas](https://github.com/royriojas), 11/09/2015 14:48:05
## v1.0.6
- **Build Scripts Changes**
- Add helpers/code check scripts - [bdb82f3](https://github.com/royriojas/flat-cache/commit/bdb82f3), [royriojas](https://github.com/royriojas), 11/09/2015 14:44:31
## v1.0.5
- **Documentation**
- better description for the module - [436817f](https://github.com/royriojas/flat-cache/commit/436817f), [royriojas](https://github.com/royriojas), 11/09/2015 14:35:33
- **Other changes**
- Update dependencies - [be88aa3](https://github.com/royriojas/flat-cache/commit/be88aa3), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 11/09/2015 13:47:41
## v1.0.4
- **Refactoring**
- load a cache file using the full filepath - [b8f68c2](https://github.com/royriojas/flat-cache/commit/b8f68c2), [Roy Riojas](https://github.com/Roy Riojas), 30/08/2015 04:19:14
- **Documentation**
- Add documentation about `clearAll` and `clearCacheById` - [13947c1](https://github.com/royriojas/flat-cache/commit/13947c1), [Roy Riojas](https://github.com/Roy Riojas), 01/03/2015 23:44:05
- **Features**
- Add methods to remove the cache documents created - [af40443](https://github.com/royriojas/flat-cache/commit/af40443), [Roy Riojas](https://github.com/Roy Riojas), 01/03/2015 23:39:27
## v1.0.1
- **Other changes**
- Update README.md - [c2b6805](https://github.com/royriojas/flat-cache/commit/c2b6805), [Roy Riojas](https://github.com/Roy Riojas), 26/02/2015 04:28:07
## v1.0.0
- **Refactoring**
- flat-cache v.1.0.0 - [c984274](https://github.com/royriojas/flat-cache/commit/c984274), [Roy Riojas](https://github.com/Roy Riojas), 26/02/2015 04:11:50
- **Other changes**
- Initial commit - [d43cccf](https://github.com/royriojas/flat-cache/commit/d43cccf), [Roy Riojas](https://github.com/Roy Riojas), 26/02/2015 01:12:16

View File

@@ -0,0 +1,11 @@
import superPropBase from "./superPropBase.js";
function _get() {
return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) {
var p = superPropBase(e, t);
if (p) {
var n = Object.getOwnPropertyDescriptor(p, t);
return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value;
}
}, _get.apply(null, arguments);
}
export { _get as default };

View File

@@ -0,0 +1,128 @@
import type { $ZodStringFormats } from "../core/checks.js";
import type * as errors from "../core/errors.js";
import * as util from "../core/util.js";
const error: () => errors.$ZodErrorMap = () => {
const Sizable: Record<string, { unit: string; verb: string }> = {
string: { unit: "символа", verb: "да съдържа" },
file: { unit: "байта", verb: "да съдържа" },
array: { unit: "елемента", verb: "да съдържа" },
set: { unit: "елемента", verb: "да съдържа" },
};
function getSizing(origin: string): { unit: string; verb: string } | null {
return Sizable[origin] ?? null;
}
const FormatDictionary: {
[k in $ZodStringFormats | (string & {})]?: string;
} = {
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: {
[k in errors.$ZodInvalidTypeExpected | (string & {})]?: string;
} = {
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 as errors.$ZodStringFormatIssues;
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 (): { localeError: errors.$ZodErrorMap } {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1,705 @@
/**
* bls12-381 is pairing-friendly Barreto-Lynn-Scott elliptic curve construction allowing to:
* Construct zk-SNARKs at the ~120-bit security, as per [Barbulescu-Duquesne 2017](https://hal.science/hal-01534101/file/main.pdf)
* Efficiently verify N aggregate signatures with 1 pairing and N ec additions:
the Boneh-Lynn-Shacham signature scheme is orders of magnitude more efficient than Schnorr
BLS can mean 2 different things:
* Barreto-Lynn-Scott: BLS12, a Pairing Friendly Elliptic Curve
* Boneh-Lynn-Shacham: A Signature Scheme.
### Summary
1. BLS Relies on expensive bilinear pairing
2. Secret Keys: 32 bytes
3. Public Keys: 48 OR 96 bytes - big-endian x coordinate of point on G1 OR G2 curve
4. Signatures: 96 OR 48 bytes - big-endian x coordinate of point on G2 OR G1 curve
5. The 12 stands for the Embedding degree.
Modes of operation:
* Long signatures: 48-byte keys + 96-byte sigs (G1 keys + G2 sigs).
* Short signatures: 96-byte keys + 48-byte sigs (G2 keys + G1 sigs).
### Formulas
- `P = pk x G` - public keys
- `S = pk x H(m)` - signing, uses hash-to-curve on m
- `e(P, H(m)) == e(G, S)` - verification using pairings
- `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation
### Curves
G1 is ordinary elliptic curve. G2 is extension field curve, think "over complex numbers".
- G1: y² = x³ + 4
- G2: y² = x³ + 4(u + 1) where u = √1; r-order subgroup of E'(Fp²), M-type twist
### Towers
Pairing G1 + G2 produces element in Fp₁₂, 12-degree polynomial.
Fp₁₂ is usually implemented using tower of lower-degree polynomials for speed.
- Fp₁₂ = Fp₆² => Fp₂³
- Fp(u) / (u² - β) where β = -1
- Fp₂(v) / (v³ - ξ) where ξ = u + 1
- Fp₆(w) / (w² - γ) where γ = v
- Fp²[u] = Fp/u²+1
- Fp⁶[v] = Fp²/v³-1-u
- Fp¹²[w] = Fp⁶/w²-v
### Params
* Embedding degree (k): 12
* Seed is sometimes named x or t
* t = -15132376222941642752
* p = (t-1)² * (t⁴-t²+1)/3 + t
* r = t⁴-t²+1
* Ate loop size: X
To verify curve parameters, see
[pairing-friendly-curves spec](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11).
Basic math is done over finite fields over p.
More complicated math is done over polynominal extension fields.
### Compatibility and notes
1. It is compatible with Algorand, Chia, Dfinity, Ethereum, Filecoin, ZEC.
Filecoin uses little endian byte arrays for secret keys - make sure to reverse byte order.
2. Make sure to correctly select mode: "long signature" or "short signature".
3. Compatible with specs:
RFC 9380,
[cfrg-pairing-friendly-curves-11](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11),
[cfrg-bls-signature-05](https://datatracker.ietf.org/doc/draft-irtf-cfrg-bls-signature/).
*
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { sha256 } from '@noble/hashes/sha2.js';
import { bls } from "./abstract/bls.js";
import { Field } from "./abstract/modular.js";
import { abytes, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE, } from "./utils.js";
// Types
import { isogenyMap } from "./abstract/hash-to-curve.js";
import { psiFrobenius, tower12 } from "./abstract/tower.js";
import { mapToCurveSimpleSWU, } from "./abstract/weierstrass.js";
// Be friendly to bad ECMAScript parsers by not using bigint literals
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
// To verify math:
// https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11
// The BLS parameter x (seed) for BLS12-381. NOTE: it is negative!
// x = -2^63 - 2^62 - 2^60 - 2^57 - 2^48 - 2^16
const BLS_X = BigInt('0xd201000000010000');
// t = x (called differently in different places)
// const t = -BLS_X;
const BLS_X_LEN = bitLen(BLS_X);
// a=0, b=4
// P is characteristic of field Fp, in which curve calculations are done.
// p = (t-1)² * (t⁴-t²+1)/3 + t
// bls12_381_Fp = (t-1n)**2n * (t**4n - t**2n + 1n) / 3n + t
// r*h is curve order, amount of points on curve,
// where r is order of prime subgroup and h is cofactor.
// r = t⁴-t²+1
// r = (t**4n - t**2n + 1n)
// cofactor h of G1: (t - 1)²/3
// cofactorG1 = (t-1n)**2n/3n
// x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507
// y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569
const bls12_381_CURVE_G1 = {
p: BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'),
n: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001'),
h: BigInt('0x396c8c005555e1568c00aaab0000aaab'),
a: _0n,
b: _4n,
Gx: BigInt('0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb'),
Gy: BigInt('0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1'),
};
// CURVE FIELDS
export const bls12_381_Fr = Field(bls12_381_CURVE_G1.n, {
modFromBytes: true,
isLE: true,
});
const { Fp, Fp2, Fp6, Fp12 } = tower12({
ORDER: bls12_381_CURVE_G1.p,
X_LEN: BLS_X_LEN,
// Finite extension field over irreducible polynominal.
// Fp(u) / (u² - β) where β = -1
FP2_NONRESIDUE: [_1n, _1n],
Fp2mulByB: ({ c0, c1 }) => {
const t0 = Fp.mul(c0, _4n); // 4 * c0
const t1 = Fp.mul(c1, _4n); // 4 * c1
// (T0-T1) + (T0+T1)*i
return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) };
},
Fp12finalExponentiate: (num) => {
const x = BLS_X;
// this^(q⁶) / this
const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num);
// t0^(q²) * t0
const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0);
const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x));
const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2);
const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x));
const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x));
const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2));
const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x));
const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2);
const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3);
const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1);
const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1);
// (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1
return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1);
},
});
// GLV endomorphism Ψ(P), for fast cofactor clearing
const { G2psi, G2psi2 } = psiFrobenius(Fp, Fp2, Fp2.div(Fp2.ONE, Fp2.NONRESIDUE)); // 1/(u+1)
/**
* Default hash_to_field / hash-to-curve for BLS.
* m: 1 for G1, 2 for G2
* k: target security level in bits
* hash: any function, e.g. BBS+ uses BLAKE2: see [github](https://github.com/hyperledger/aries-framework-go/issues/2247).
* Parameter values come from [section 8.8.2 of RFC 9380](https://www.rfc-editor.org/rfc/rfc9380#section-8.8.2).
*/
const htfDefaults = Object.freeze({
DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_',
encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_',
p: Fp.ORDER,
m: 2,
k: 128,
expand: 'xmd',
hash: sha256,
});
// a=0, b=4
// cofactor h of G2
// (t^8 - 4t^7 + 5t^6 - 4t^4 + 6t^3 - 4t^2 - 4t + 13)/9
// cofactorG2 = (t**8n - 4n*t**7n + 5n*t**6n - 4n*t**4n + 6n*t**3n - 4n*t**2n - 4n*t+13n)/9n
// x = 3059144344244213709971259814753781636986470325476647558659373206291635324768958432433509563104347017837885763365758*u + 352701069587466618187139116011060144890029952792775240219908644239793785735715026873347600343865175952761926303160
// y = 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582*u + 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905
const bls12_381_CURVE_G2 = {
p: Fp2.ORDER,
n: bls12_381_CURVE_G1.n,
h: BigInt('0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5'),
a: Fp2.ZERO,
b: Fp2.fromBigTuple([_4n, _4n]),
Gx: Fp2.fromBigTuple([
BigInt('0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8'),
BigInt('0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e'),
]),
Gy: Fp2.fromBigTuple([
BigInt('0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801'),
BigInt('0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be'),
]),
};
// Encoding utils
// Compressed point of infinity
// Set compressed & point-at-infinity bits
const COMPZERO = setMask(Fp.toBytes(_0n), { infinity: true, compressed: true });
function parseMask(bytes) {
// Copy, so we can remove mask data. It will be removed also later, when Fp.create will call modulo.
bytes = bytes.slice();
const mask = bytes[0] & 224;
const compressed = !!((mask >> 7) & 1); // compression bit (0b1000_0000)
const infinity = !!((mask >> 6) & 1); // point at infinity bit (0b0100_0000)
const sort = !!((mask >> 5) & 1); // sort bit (0b0010_0000)
bytes[0] &= 31; // clear mask (zero first 3 bits)
return { compressed, infinity, sort, value: bytes };
}
function setMask(bytes, mask) {
if (bytes[0] & 224)
throw new Error('setMask: non-empty mask');
if (mask.compressed)
bytes[0] |= 128;
if (mask.infinity)
bytes[0] |= 64;
if (mask.sort)
bytes[0] |= 32;
return bytes;
}
function pointG1ToBytes(_c, point, isComp) {
const { BYTES: L, ORDER: P } = Fp;
const is0 = point.is0();
const { x, y } = point.toAffine();
if (isComp) {
if (is0)
return COMPZERO.slice();
const sort = Boolean((y * _2n) / P);
return setMask(numberToBytesBE(x, L), { compressed: true, sort });
}
else {
if (is0) {
return concatBytes(Uint8Array.of(0x40), new Uint8Array(2 * L - 1));
}
else {
return concatBytes(numberToBytesBE(x, L), numberToBytesBE(y, L));
}
}
}
function signatureG1ToBytes(point) {
point.assertValidity();
const { BYTES: L, ORDER: P } = Fp;
const { x, y } = point.toAffine();
if (point.is0())
return COMPZERO.slice();
const sort = Boolean((y * _2n) / P);
return setMask(numberToBytesBE(x, L), { compressed: true, sort });
}
function pointG1FromBytes(bytes) {
const { compressed, infinity, sort, value } = parseMask(bytes);
const { BYTES: L, ORDER: P } = Fp;
if (value.length === 48 && compressed) {
const compressedValue = bytesToNumberBE(value);
// Zero
const x = Fp.create(compressedValue & bitMask(Fp.BITS));
if (infinity) {
if (x !== _0n)
throw new Error('invalid G1 point: non-empty, at infinity, with compression');
return { x: _0n, y: _0n };
}
const right = Fp.add(Fp.pow(x, _3n), Fp.create(bls12_381_CURVE_G1.b)); // y² = x³ + b
let y = Fp.sqrt(right);
if (!y)
throw new Error('invalid G1 point: compressed point');
if ((y * _2n) / P !== BigInt(sort))
y = Fp.neg(y);
return { x: Fp.create(x), y: Fp.create(y) };
}
else if (value.length === 96 && !compressed) {
// Check if the infinity flag is set
const x = bytesToNumberBE(value.subarray(0, L));
const y = bytesToNumberBE(value.subarray(L));
if (infinity) {
if (x !== _0n || y !== _0n)
throw new Error('G1: non-empty point at infinity');
return bls12_381.G1.Point.ZERO.toAffine();
}
return { x: Fp.create(x), y: Fp.create(y) };
}
else {
throw new Error('invalid G1 point: expected 48/96 bytes');
}
}
function signatureG1FromBytes(hex) {
const { infinity, sort, value } = parseMask(ensureBytes('signatureHex', hex, 48));
const P = Fp.ORDER;
const Point = bls12_381.G1.Point;
const compressedValue = bytesToNumberBE(value);
// Zero
if (infinity)
return Point.ZERO;
const x = Fp.create(compressedValue & bitMask(Fp.BITS));
const right = Fp.add(Fp.pow(x, _3n), Fp.create(bls12_381_CURVE_G1.b)); // y² = x³ + b
let y = Fp.sqrt(right);
if (!y)
throw new Error('invalid G1 point: compressed');
const aflag = BigInt(sort);
if ((y * _2n) / P !== aflag)
y = Fp.neg(y);
const point = Point.fromAffine({ x, y });
point.assertValidity();
return point;
}
function pointG2ToBytes(_c, point, isComp) {
const { BYTES: L, ORDER: P } = Fp;
const is0 = point.is0();
const { x, y } = point.toAffine();
if (isComp) {
if (is0)
return concatBytes(COMPZERO, numberToBytesBE(_0n, L));
const flag = Boolean(y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P);
return concatBytes(setMask(numberToBytesBE(x.c1, L), { compressed: true, sort: flag }), numberToBytesBE(x.c0, L));
}
else {
if (is0)
return concatBytes(Uint8Array.of(0x40), new Uint8Array(4 * L - 1));
const { re: x0, im: x1 } = Fp2.reim(x);
const { re: y0, im: y1 } = Fp2.reim(y);
return concatBytes(numberToBytesBE(x1, L), numberToBytesBE(x0, L), numberToBytesBE(y1, L), numberToBytesBE(y0, L));
}
}
function signatureG2ToBytes(point) {
point.assertValidity();
const { BYTES: L } = Fp;
if (point.is0())
return concatBytes(COMPZERO, numberToBytesBE(_0n, L));
const { x, y } = point.toAffine();
const { re: x0, im: x1 } = Fp2.reim(x);
const { re: y0, im: y1 } = Fp2.reim(y);
const tmp = y1 > _0n ? y1 * _2n : y0 * _2n;
const sort = Boolean((tmp / Fp.ORDER) & _1n);
const z2 = x0;
return concatBytes(setMask(numberToBytesBE(x1, L), { sort, compressed: true }), numberToBytesBE(z2, L));
}
function pointG2FromBytes(bytes) {
const { BYTES: L, ORDER: P } = Fp;
const { compressed, infinity, sort, value } = parseMask(bytes);
if ((!compressed && !infinity && sort) || // 00100000
(!compressed && infinity && sort) || // 01100000
(sort && infinity && compressed) // 11100000
) {
throw new Error('invalid encoding flag: ' + (bytes[0] & 224));
}
const slc = (b, from, to) => bytesToNumberBE(b.slice(from, to));
if (value.length === 96 && compressed) {
if (infinity) {
// check that all bytes are 0
if (value.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) {
throw new Error('invalid G2 point: compressed');
}
return { x: Fp2.ZERO, y: Fp2.ZERO };
}
const x_1 = slc(value, 0, L);
const x_0 = slc(value, L, 2 * L);
const x = Fp2.create({ c0: Fp.create(x_0), c1: Fp.create(x_1) });
const right = Fp2.add(Fp2.pow(x, _3n), bls12_381_CURVE_G2.b); // y² = x³ + 4 * (u+1) = x³ + b
let y = Fp2.sqrt(right);
const Y_bit = y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P ? _1n : _0n;
y = sort && Y_bit > 0 ? y : Fp2.neg(y);
return { x, y };
}
else if (value.length === 192 && !compressed) {
if (infinity) {
if (value.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) {
throw new Error('invalid G2 point: uncompressed');
}
return { x: Fp2.ZERO, y: Fp2.ZERO };
}
const x1 = slc(value, 0 * L, 1 * L);
const x0 = slc(value, 1 * L, 2 * L);
const y1 = slc(value, 2 * L, 3 * L);
const y0 = slc(value, 3 * L, 4 * L);
return { x: Fp2.fromBigTuple([x0, x1]), y: Fp2.fromBigTuple([y0, y1]) };
}
else {
throw new Error('invalid G2 point: expected 96/192 bytes');
}
}
function signatureG2FromBytes(hex) {
const { ORDER: P } = Fp;
// TODO: Optimize, it's very slow because of sqrt.
const { infinity, sort, value } = parseMask(ensureBytes('signatureHex', hex));
const Point = bls12_381.G2.Point;
const half = value.length / 2;
if (half !== 48 && half !== 96)
throw new Error('invalid compressed signature length, expected 96/192 bytes');
const z1 = bytesToNumberBE(value.slice(0, half));
const z2 = bytesToNumberBE(value.slice(half));
// Indicates the infinity point
if (infinity)
return Point.ZERO;
const x1 = Fp.create(z1 & bitMask(Fp.BITS));
const x2 = Fp.create(z2);
const x = Fp2.create({ c0: x2, c1: x1 });
const y2 = Fp2.add(Fp2.pow(x, _3n), bls12_381_CURVE_G2.b); // y² = x³ + 4
// The slow part
let y = Fp2.sqrt(y2);
if (!y)
throw new Error('Failed to find a square root');
// Choose the y whose leftmost bit of the imaginary part is equal to the a_flag1
// If y1 happens to be zero, then use the bit of y0
const { re: y0, im: y1 } = Fp2.reim(y);
const aflag1 = BigInt(sort);
const isGreater = y1 > _0n && (y1 * _2n) / P !== aflag1;
const is0 = y1 === _0n && (y0 * _2n) / P !== aflag1;
if (isGreater || is0)
y = Fp2.neg(y);
const point = Point.fromAffine({ x, y });
point.assertValidity();
return point;
}
/**
* bls12-381 pairing-friendly curve.
* @example
* import { bls12_381 as bls } from '@noble/curves/bls12-381';
* // G1 keys, G2 signatures
* const privateKey = '67d53f170b908cabb9eb326c3c337762d59289a8fec79f7bc9254b584b73265c';
* const message = '64726e3da8';
* const publicKey = bls.getPublicKey(privateKey);
* const signature = bls.sign(message, privateKey);
* const isValid = bls.verify(signature, message, publicKey);
*/
export const bls12_381 = bls({
// Fields
fields: {
Fp,
Fp2,
Fp6,
Fp12,
Fr: bls12_381_Fr,
},
// G1: y² = x³ + 4
G1: {
...bls12_381_CURVE_G1,
Fp,
htfDefaults: { ...htfDefaults, m: 1, DST: 'BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_' },
wrapPrivateKey: true,
allowInfinityPoint: true,
// Checks is the point resides in prime-order subgroup.
// point.isTorsionFree() should return true for valid points
// It returns false for shitty points.
// https://eprint.iacr.org/2021/1130.pdf
isTorsionFree: (c, point) => {
// GLV endomorphism ψ(P)
const beta = BigInt('0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe');
const phi = new c(Fp.mul(point.X, beta), point.Y, point.Z);
// TODO: unroll
const xP = point.multiplyUnsafe(BLS_X).negate(); // [x]P
const u2P = xP.multiplyUnsafe(BLS_X); // [u2]P
return u2P.equals(phi);
},
// Clear cofactor of G1
// https://eprint.iacr.org/2019/403
clearCofactor: (_c, point) => {
// return this.multiplyUnsafe(CURVE.h);
return point.multiplyUnsafe(BLS_X).add(point); // x*P + P
},
mapToCurve: mapToG1,
fromBytes: pointG1FromBytes,
toBytes: pointG1ToBytes,
ShortSignature: {
fromBytes(bytes) {
abytes(bytes);
return signatureG1FromBytes(bytes);
},
fromHex(hex) {
return signatureG1FromBytes(hex);
},
toBytes(point) {
return signatureG1ToBytes(point);
},
toRawBytes(point) {
return signatureG1ToBytes(point);
},
toHex(point) {
return bytesToHex(signatureG1ToBytes(point));
},
},
},
G2: {
...bls12_381_CURVE_G2,
Fp: Fp2,
// https://datatracker.ietf.org/doc/html/rfc9380#name-clearing-the-cofactor
// https://datatracker.ietf.org/doc/html/rfc9380#name-cofactor-clearing-for-bls12
hEff: BigInt('0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551'),
htfDefaults: { ...htfDefaults },
wrapPrivateKey: true,
allowInfinityPoint: true,
mapToCurve: mapToG2,
// Checks is the point resides in prime-order subgroup.
// point.isTorsionFree() should return true for valid points
// It returns false for shitty points.
// https://eprint.iacr.org/2021/1130.pdf
// Older version: https://eprint.iacr.org/2019/814.pdf
isTorsionFree: (c, P) => {
return P.multiplyUnsafe(BLS_X).negate().equals(G2psi(c, P)); // ψ(P) == [u](P)
},
// Maps the point into the prime-order subgroup G2.
// clear_cofactor_bls12381_g2 from RFC 9380.
// https://eprint.iacr.org/2017/419.pdf
// prettier-ignore
clearCofactor: (c, P) => {
const x = BLS_X;
let t1 = P.multiplyUnsafe(x).negate(); // [-x]P
let t2 = G2psi(c, P); // Ψ(P)
let t3 = P.double(); // 2P
t3 = G2psi2(c, t3); // Ψ²(2P)
t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P)
t2 = t1.add(t2); // [-x]P + Ψ(P)
t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P)
t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P)
t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P
const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P
return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P)
},
fromBytes: pointG2FromBytes,
toBytes: pointG2ToBytes,
Signature: {
fromBytes(bytes) {
abytes(bytes);
return signatureG2FromBytes(bytes);
},
fromHex(hex) {
return signatureG2FromBytes(hex);
},
toBytes(point) {
return signatureG2ToBytes(point);
},
toRawBytes(point) {
return signatureG2ToBytes(point);
},
toHex(point) {
return bytesToHex(signatureG2ToBytes(point));
},
},
},
params: {
ateLoopSize: BLS_X, // The BLS parameter x for BLS12-381
r: bls12_381_CURVE_G1.n, // order; z⁴ z² + 1; CURVE.n from other curves
xNegative: true,
twistType: 'multiplicative',
},
htfDefaults,
hash: sha256,
});
// 3-isogeny map from E' to E https://www.rfc-editor.org/rfc/rfc9380#appendix-E.3
const isogenyMapG2 = isogenyMap(Fp2, [
// xNum
[
[
'0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6',
'0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6',
],
[
'0x0',
'0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a',
],
[
'0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e',
'0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d',
],
[
'0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1',
'0x0',
],
],
// xDen
[
[
'0x0',
'0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63',
],
[
'0xc',
'0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f',
],
['0x1', '0x0'], // LAST 1
],
// yNum
[
[
'0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706',
'0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706',
],
[
'0x0',
'0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be',
],
[
'0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c',
'0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f',
],
[
'0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10',
'0x0',
],
],
// yDen
[
[
'0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb',
'0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb',
],
[
'0x0',
'0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3',
],
[
'0x12',
'0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99',
],
['0x1', '0x0'], // LAST 1
],
].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt)))));
// 11-isogeny map from E' to E
const isogenyMapG1 = isogenyMap(Fp, [
// xNum
[
'0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7',
'0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb',
'0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0',
'0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861',
'0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9',
'0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983',
'0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84',
'0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e',
'0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317',
'0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e',
'0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b',
'0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229',
],
// xDen
[
'0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c',
'0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff',
'0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19',
'0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8',
'0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e',
'0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5',
'0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a',
'0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e',
'0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641',
'0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a',
'0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1
],
// yNum
[
'0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33',
'0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696',
'0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6',
'0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb',
'0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb',
'0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0',
'0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2',
'0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29',
'0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587',
'0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30',
'0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132',
'0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e',
'0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8',
'0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133',
'0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b',
'0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604',
],
// yDen
[
'0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1',
'0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d',
'0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2',
'0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416',
'0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d',
'0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac',
'0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c',
'0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9',
'0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a',
'0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55',
'0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8',
'0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092',
'0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc',
'0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7',
'0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f',
'0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1
],
].map((i) => i.map((j) => BigInt(j))));
// Optimized SWU Map - Fp to G1
const G1_SWU = mapToCurveSimpleSWU(Fp, {
A: Fp.create(BigInt('0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d')),
B: Fp.create(BigInt('0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0')),
Z: Fp.create(BigInt(11)),
});
// SWU Map - Fp2 to G2': y² = x³ + 240i * x + 1012 + 1012i
const G2_SWU = mapToCurveSimpleSWU(Fp2, {
A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), // A' = 240 * I
B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), // B' = 1012 * (1 + I)
Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I)
});
function mapToG1(scalars) {
const { x, y } = G1_SWU(Fp.create(scalars[0]));
return isogenyMapG1(x, y);
}
function mapToG2(scalars) {
const { x, y } = G2_SWU(Fp2.fromBigTuple(scalars));
return isogenyMapG2(x, y);
}
//# sourceMappingURL=bls12-381.js.map

View File

@@ -0,0 +1,15 @@
var test = require('tape');
var equal = require('../');
test('0 values', function (t) {
t.ok(equal( 0, 0), ' 0 === 0');
t.ok(equal( 0, +0), ' 0 === +0');
t.ok(equal(+0, +0), '+0 === +0');
t.ok(equal(-0, -0), '-0 === -0');
t.notOk(equal(-0, 0), '-0 !== 0');
t.notOk(equal(-0, +0), '-0 !== +0');
t.end();
});

View File

@@ -0,0 +1,4 @@
function _nullishReceiverError(r) {
throw new TypeError("Cannot set property of null or undefined.");
}
export { _nullishReceiverError as default };