WIP: bootstrap and partial real Solana watcher implementation
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
import type { TSESTree } from '@typescript-eslint/utils';
|
||||
import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util';
|
||||
declare const baseRule: import("@typescript-eslint/utils/ts-eslint").RuleModule<"useBrackets" | "useDot", [{
|
||||
allowIndexSignaturePropertyAccess?: boolean;
|
||||
allowKeywords?: boolean;
|
||||
allowPattern?: string;
|
||||
allowPrivateClassPropertyAccess?: boolean;
|
||||
allowProtectedClassPropertyAccess?: boolean;
|
||||
}], unknown, {
|
||||
MemberExpression(node: TSESTree.MemberExpression): void;
|
||||
}>;
|
||||
export type Options = InferOptionsTypeFromRule<typeof baseRule>;
|
||||
export type MessageIds = InferMessageIdsTypeFromRule<typeof baseRule>;
|
||||
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"useBrackets" | "useDot", [{
|
||||
allowIndexSignaturePropertyAccess?: boolean;
|
||||
allowKeywords?: boolean;
|
||||
allowPattern?: string;
|
||||
allowPrivateClassPropertyAccess?: boolean;
|
||||
allowProtectedClassPropertyAccess?: boolean;
|
||||
}], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
|
||||
name: string;
|
||||
};
|
||||
export default _default;
|
||||
@@ -0,0 +1,6 @@
|
||||
var id = 0;
|
||||
|
||||
function _class_private_field_loose_key(name) {
|
||||
return "__private_" + id++ + "_" + name;
|
||||
}
|
||||
export { _class_private_field_loose_key as _ };
|
||||
@@ -0,0 +1,13 @@
|
||||
"use strict";
|
||||
|
||||
var _class_apply_descriptor_update = require("./_class_apply_descriptor_update.cjs");
|
||||
var _class_check_private_static_access = require("./_class_check_private_static_access.cjs");
|
||||
var _class_check_private_static_field_descriptor = require("./_class_check_private_static_field_descriptor.cjs");
|
||||
|
||||
function _class_static_private_field_update(receiver, classConstructor, descriptor) {
|
||||
_class_check_private_static_access._(receiver, classConstructor);
|
||||
_class_check_private_static_field_descriptor._(descriptor, "update");
|
||||
|
||||
return _class_apply_descriptor_update._(receiver, descriptor);
|
||||
}
|
||||
exports._ = _class_static_private_field_update;
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"typePredicateKind.d.ts","sourceRoot":"","sources":["../../src/enums/typePredicateKind.ts"],"names":[],"mappings":"AACA,eAAO,IAAI,iBAAiB,EAAE,GAAG,CAAC"}
|
||||
@@ -0,0 +1,202 @@
|
||||
import { assertNever } from "../internal/utils.js";
|
||||
import { SyntaxKind, } from "./ast.js";
|
||||
import { isIdentifier, isJSDoc, isJSDocOverloadTag, isJSDocParameterTag, isJSDocSatisfiesTag, isJSDocTemplateTag, isJSDocTypeTag, isParenthesizedExpression, isPrivateIdentifier, } from "./is.generated.js";
|
||||
/** Get all JSDoc tags related to a node, including those on parent nodes. */
|
||||
export function getJSDocTags(node) {
|
||||
return getJSDocCommentsAndTags(node);
|
||||
}
|
||||
/** Gets all JSDoc tags that match a specified predicate */
|
||||
export function getAllJSDocTags(node, predicate) {
|
||||
return getJSDocTags(node).filter(predicate);
|
||||
}
|
||||
/** Gets all JSDoc tags of a specified kind */
|
||||
export function getAllJSDocTagsOfKind(node, kind) {
|
||||
return getJSDocTags(node).filter(doc => doc.kind === kind);
|
||||
}
|
||||
/** Gets the text of a jsdoc comment, flattening links to their text. */
|
||||
export function getTextOfJSDocComment(comment) {
|
||||
return typeof comment === "string" ? comment
|
||||
: comment?.map(c => c.kind === SyntaxKind.JSDocText ? c.text : formatJSDocLink(c)).join("");
|
||||
}
|
||||
function isVariableLike(node) {
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.BindingElement:
|
||||
case SyntaxKind.EnumMember:
|
||||
case SyntaxKind.Parameter:
|
||||
case SyntaxKind.PropertyAssignment:
|
||||
case SyntaxKind.PropertyDeclaration:
|
||||
case SyntaxKind.PropertySignature:
|
||||
case SyntaxKind.ShorthandPropertyAssignment:
|
||||
case SyntaxKind.VariableDeclaration:
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function getJSDocNodes(node) {
|
||||
const jsDoc = node.jsDoc;
|
||||
if (!jsDoc || jsDoc.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const result = [];
|
||||
for (const j of jsDoc) {
|
||||
if (isJSDoc(j)) {
|
||||
result.push(j);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Determines whether a host node owns a JSDoc tag. A `@type` / `@satisfies` tag
|
||||
* attached to a parenthesized expression belongs only to that expression.
|
||||
*/
|
||||
function ownsJSDocTag(hostNode, tag) {
|
||||
return !(isJSDocTypeTag(tag) || isJSDocSatisfiesTag(tag))
|
||||
|| !tag.parent
|
||||
|| !isJSDoc(tag.parent)
|
||||
|| !tag.parent.parent
|
||||
|| !isParenthesizedExpression(tag.parent.parent)
|
||||
|| tag.parent.parent === hostNode;
|
||||
}
|
||||
function filterOwnedJSDocTags(hostNode, comments) {
|
||||
const result = [];
|
||||
const lastJSDoc = comments[comments.length - 1];
|
||||
for (const jsDoc of comments) {
|
||||
if (!jsDoc.tags) {
|
||||
continue;
|
||||
}
|
||||
if (jsDoc === lastJSDoc) {
|
||||
for (const tag of jsDoc.tags) {
|
||||
if (ownsJSDocTag(hostNode, tag)) {
|
||||
result.push(tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Tags from earlier comments only contribute their `@overload` tags.
|
||||
for (const tag of jsDoc.tags) {
|
||||
if (isJSDocOverloadTag(tag)) {
|
||||
result.push(tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function getJSDocParameterTags(param) {
|
||||
const result = [];
|
||||
const name = param.name;
|
||||
const parentTags = getJSDocTags(param.parent);
|
||||
if (name && isIdentifier(name)) {
|
||||
for (const tag of parentTags) {
|
||||
if (isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.text === name.text) {
|
||||
result.push(tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (name) {
|
||||
// Binding patterns and JSDoc function syntax match parameter tags by position.
|
||||
const parameters = param.parent.parameters;
|
||||
const i = parameters ? [...parameters].indexOf(param) : -1;
|
||||
if (i > -1) {
|
||||
const paramTags = parentTags.filter(isJSDocParameterTag);
|
||||
if (i < paramTags.length) {
|
||||
result.push(paramTags[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function getJSDocTypeParameterTags(typeParam) {
|
||||
const result = [];
|
||||
const name = typeParam.name.text;
|
||||
for (const tag of getJSDocTags(typeParam.parent)) {
|
||||
if (isJSDocTemplateTag(tag) && [...tag.typeParameters].some(tp => tp.name.text === name)) {
|
||||
result.push(tag);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
// Keep in sync with ast.GetNextJSDocCommentLocation.
|
||||
function getNextJSDocCommentLocation(node) {
|
||||
const parent = node.parent;
|
||||
if (parent) {
|
||||
switch (parent.kind) {
|
||||
case SyntaxKind.PropertyAssignment:
|
||||
case SyntaxKind.ExportAssignment:
|
||||
case SyntaxKind.PropertyDeclaration:
|
||||
case SyntaxKind.VariableDeclaration:
|
||||
case SyntaxKind.SatisfiesExpression:
|
||||
case SyntaxKind.ReturnStatement:
|
||||
case SyntaxKind.VariableStatement:
|
||||
case SyntaxKind.ExpressionStatement:
|
||||
return parent;
|
||||
case SyntaxKind.VariableDeclarationList:
|
||||
if (parent.declarations[0] === node) {
|
||||
return parent;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
function getJSDocCommentsAndTags(hostNode) {
|
||||
const result = [];
|
||||
// Pull parameter comments from a declaring initializer (e.g. `var x = function () {}`).
|
||||
if (isVariableLike(hostNode)) {
|
||||
const initializer = hostNode.initializer;
|
||||
if (initializer) {
|
||||
const initJSDoc = getJSDocNodes(initializer);
|
||||
if (initJSDoc.length) {
|
||||
result.push(...filterOwnedJSDocTags(hostNode, initJSDoc));
|
||||
}
|
||||
}
|
||||
}
|
||||
let node = hostNode;
|
||||
while (node && node.parent) {
|
||||
const jsDocNodes = getJSDocNodes(node);
|
||||
if (jsDocNodes.length) {
|
||||
result.push(...filterOwnedJSDocTags(hostNode, jsDocNodes));
|
||||
}
|
||||
if (node.kind === SyntaxKind.Parameter) {
|
||||
result.push(...getJSDocParameterTags(node));
|
||||
break;
|
||||
}
|
||||
if (node.kind === SyntaxKind.TypeParameter) {
|
||||
result.push(...getJSDocTypeParameterTags(node));
|
||||
break;
|
||||
}
|
||||
node = getNextJSDocCommentLocation(node);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function formatJSDocLink(link) {
|
||||
const kind = link.kind === SyntaxKind.JSDocLink ? "link"
|
||||
: link.kind === SyntaxKind.JSDocLinkCode ? "linkcode"
|
||||
: "linkplain";
|
||||
const name = link.name ? entityNameToString(link.name) : "";
|
||||
const space = link.name && (link.text === "" || link.text.startsWith("://")) ? "" : " ";
|
||||
return `{@${kind} ${name}${space}${link.text}}`;
|
||||
}
|
||||
function entityNameToString(name) {
|
||||
switch (name.kind) {
|
||||
case SyntaxKind.ThisKeyword:
|
||||
return "this";
|
||||
case SyntaxKind.PrivateIdentifier:
|
||||
case SyntaxKind.Identifier:
|
||||
return name.getFullWidth() === 0 ? name.text : name.getText();
|
||||
case SyntaxKind.QualifiedName:
|
||||
return entityNameToString(name.left) + "." + entityNameToString(name.right);
|
||||
case SyntaxKind.PropertyAccessExpression:
|
||||
if (isIdentifier(name.name) || isPrivateIdentifier(name.name)) {
|
||||
return entityNameToString(name.expression) + "." + entityNameToString(name.name);
|
||||
}
|
||||
else {
|
||||
return assertNever(name.name);
|
||||
}
|
||||
case SyntaxKind.JsxNamespacedName:
|
||||
return entityNameToString(name.namespace) + ":" + entityNameToString(name.name);
|
||||
default:
|
||||
return assertNever(name);
|
||||
}
|
||||
}
|
||||
//# sourceMappingURL=jsdoc.js.map
|
||||
@@ -0,0 +1,109 @@
|
||||
import { PrettyFormatOptions } from '@vitest/pretty-format';
|
||||
import { D as DiffOptions } from './types.d-BCElaP-c.js';
|
||||
export { a as DiffOptionsColor, S as SerializedDiffOptions } from './types.d-BCElaP-c.js';
|
||||
|
||||
/**
|
||||
* Diff Match and Patch
|
||||
* Copyright 2018 The diff-match-patch Authors.
|
||||
* https://github.com/google/diff-match-patch
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
/**
|
||||
* @fileoverview Computes the difference between two texts to create a patch.
|
||||
* Applies the patch onto another text, allowing for errors.
|
||||
* @author fraser@google.com (Neil Fraser)
|
||||
*/
|
||||
/**
|
||||
* CHANGES by pedrottimark to diff_match_patch_uncompressed.ts file:
|
||||
*
|
||||
* 1. Delete anything not needed to use diff_cleanupSemantic method
|
||||
* 2. Convert from prototype properties to var declarations
|
||||
* 3. Convert Diff to class from constructor and prototype
|
||||
* 4. Add type annotations for arguments and return values
|
||||
* 5. Add exports
|
||||
*/
|
||||
/**
|
||||
* The data structure representing a diff is an array of tuples:
|
||||
* [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
|
||||
* which means: delete 'Hello', add 'Goodbye' and keep ' world.'
|
||||
*/
|
||||
declare const DIFF_DELETE = -1;
|
||||
declare const DIFF_INSERT = 1;
|
||||
declare const DIFF_EQUAL = 0;
|
||||
/**
|
||||
* Class representing one diff tuple.
|
||||
* Attempts to look like a two-element array (which is what this used to be).
|
||||
* @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL.
|
||||
* @param {string} text Text to be deleted, inserted, or retained.
|
||||
* @constructor
|
||||
*/
|
||||
declare class Diff {
|
||||
0: number;
|
||||
1: string;
|
||||
constructor(op: number, text: string);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
declare function diffLinesUnified(aLines: Array<string>, bLines: Array<string>, options?: DiffOptions): string;
|
||||
declare function diffLinesUnified2(aLinesDisplay: Array<string>, bLinesDisplay: Array<string>, aLinesCompare: Array<string>, bLinesCompare: Array<string>, options?: DiffOptions): string;
|
||||
declare function diffLinesRaw(aLines: Array<string>, bLines: Array<string>, options?: DiffOptions): [Array<Diff>, boolean];
|
||||
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
declare function diffStringsUnified(a: string, b: string, options?: DiffOptions): string;
|
||||
declare function diffStringsRaw(a: string, b: string, cleanup: boolean, options?: DiffOptions): [Array<Diff>, boolean];
|
||||
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
interface StringifiedMemory {
|
||||
expected?: string;
|
||||
actual?: string;
|
||||
}
|
||||
interface Memorize {
|
||||
(pointer: "expected" | "actual", stringifiedValue: string): string;
|
||||
}
|
||||
/**
|
||||
* @param a Expected value
|
||||
* @param b Received value
|
||||
* @param options Diff options
|
||||
* @returns {string | null} a string diff
|
||||
*/
|
||||
declare function diff(a: any, b: any, options?: DiffOptions, memorize?: Memorize): string | undefined;
|
||||
declare function getDefaultFormatOptions(options?: DiffOptions): PrettyFormatOptions;
|
||||
declare function printDiffOrStringify(received: unknown, expected: unknown, options?: DiffOptions, memory?: StringifiedMemory): string | undefined;
|
||||
declare function replaceAsymmetricMatcher(actual: any, expected: any, actualReplaced?: WeakSet<WeakKey>, expectedReplaced?: WeakSet<WeakKey>): {
|
||||
replacedActual: any;
|
||||
replacedExpected: any;
|
||||
};
|
||||
type PrintLabel = (string: string) => string;
|
||||
declare function getLabelPrinter(...strings: Array<string>): PrintLabel;
|
||||
|
||||
export { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, DiffOptions, diff, diffLinesRaw, diffLinesUnified, diffLinesUnified2, diffStringsRaw, diffStringsUnified, getDefaultFormatOptions, getLabelPrinter, printDiffOrStringify, replaceAsymmetricMatcher };
|
||||
export type { StringifiedMemory };
|
||||
@@ -0,0 +1,360 @@
|
||||
import { isBuiltin, createRequire } from 'node:module';
|
||||
import { pathToFileURL, fileURLToPath } from 'node:url';
|
||||
import vm from 'node:vm';
|
||||
import { ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey } from 'vite/module-runner';
|
||||
import { T as Traces } from './chunks/traces.DT5aQ62U.js';
|
||||
|
||||
const performanceNow = performance.now.bind(performance);
|
||||
class ModuleDebug {
|
||||
executionStack = [];
|
||||
startCalculateModuleExecutionInfo(filename, options) {
|
||||
const startTime = performanceNow();
|
||||
this.executionStack.push({
|
||||
filename,
|
||||
startTime,
|
||||
subImportTime: 0
|
||||
});
|
||||
return () => {
|
||||
const duration = performanceNow() - startTime;
|
||||
const currentExecution = this.executionStack.pop();
|
||||
if (currentExecution == null) throw new Error("Execution stack is empty, this should never happen");
|
||||
const selfTime = duration - currentExecution.subImportTime;
|
||||
if (this.executionStack.length > 0) this.executionStack.at(-1).subImportTime += duration;
|
||||
return {
|
||||
startOffset: options.startOffset,
|
||||
external: options.external,
|
||||
importer: options.importer,
|
||||
duration,
|
||||
selfTime
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const isWindows = process.platform === "win32";
|
||||
class VitestModuleEvaluator {
|
||||
stubs = {};
|
||||
env = createImportMetaEnvProxy();
|
||||
vm;
|
||||
compiledFunctionArgumentsNames;
|
||||
compiledFunctionArgumentsValues = [];
|
||||
primitives;
|
||||
debug = new ModuleDebug();
|
||||
_otel;
|
||||
_evaluatedModules;
|
||||
constructor(vmOptions, options = {}) {
|
||||
this.options = options;
|
||||
this._otel = options.traces || new Traces({ enabled: false });
|
||||
this.vm = vmOptions;
|
||||
this.stubs = getDefaultRequestStubs(vmOptions?.context);
|
||||
this._evaluatedModules = options.evaluatedModules;
|
||||
if (options.compiledFunctionArgumentsNames) this.compiledFunctionArgumentsNames = options.compiledFunctionArgumentsNames;
|
||||
if (options.compiledFunctionArgumentsValues) this.compiledFunctionArgumentsValues = options.compiledFunctionArgumentsValues;
|
||||
if (vmOptions) this.primitives = vm.runInContext("({ Object, Proxy, Reflect })", vmOptions.context);
|
||||
else this.primitives = {
|
||||
Object,
|
||||
Proxy,
|
||||
Reflect
|
||||
};
|
||||
}
|
||||
convertIdToImportUrl(id) {
|
||||
// TODO: vitest returns paths for external modules, but Vite returns file://
|
||||
// REMOVE WHEN VITE 6 SUPPORT IS OVER
|
||||
// unfortunately, there is a bug in Vite where ID is resolved incorrectly, so we can't return files until the fix is merged
|
||||
// https://github.com/vitejs/vite/pull/20449
|
||||
if (!isWindows || isBuiltin(id) || /^(?:node:|data:|http:|https:|file:)/.test(id)) return id;
|
||||
const [filepath, query] = id.split("?");
|
||||
if (query) return `${pathToFileURL(filepath).toString()}?${query}`;
|
||||
return pathToFileURL(filepath).toString();
|
||||
}
|
||||
async runExternalModule(id) {
|
||||
if (id in this.stubs) return this.stubs[id];
|
||||
const file = this.convertIdToImportUrl(id);
|
||||
const importer = (this._evaluatedModules?.getModuleById(id)?.importers)?.values().next().value;
|
||||
const filename = id.startsWith("file://") ? fileURLToPath(id) : id;
|
||||
const finishModuleExecutionInfo = this.debug.startCalculateModuleExecutionInfo(filename, {
|
||||
startOffset: 0,
|
||||
external: true,
|
||||
importer
|
||||
});
|
||||
const namespace = await this._otel.$("vitest.module.external", { attributes: { "code.file.path": file } }, () => this.vm ? this.vm.externalModulesExecutor.import(file) : import(file)).finally(() => {
|
||||
this.options.moduleExecutionInfo?.set(filename, finishModuleExecutionInfo());
|
||||
});
|
||||
if (!this.shouldInterop(file, namespace)) return namespace;
|
||||
const { mod, defaultExport } = interopModule(namespace);
|
||||
const { Proxy, Reflect } = this.primitives;
|
||||
return new Proxy(mod, {
|
||||
get(mod, prop) {
|
||||
if (prop === "default") return defaultExport;
|
||||
return mod[prop] ?? defaultExport?.[prop];
|
||||
},
|
||||
has(mod, prop) {
|
||||
if (prop === "default") return defaultExport !== void 0;
|
||||
return prop in mod || defaultExport && prop in defaultExport;
|
||||
},
|
||||
getOwnPropertyDescriptor(mod, prop) {
|
||||
const descriptor = Reflect.getOwnPropertyDescriptor(mod, prop);
|
||||
if (descriptor) return descriptor;
|
||||
if (prop === "default" && defaultExport !== void 0) return {
|
||||
value: defaultExport,
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
async runInlinedModule(context, code, module) {
|
||||
return this._otel.$("vitest.module.inline", (span) => this._runInlinedModule(context, code, module, span));
|
||||
}
|
||||
_createCJSGlobals(context, module, span) {
|
||||
const { Reflect, Proxy, Object } = this.primitives;
|
||||
const exportsObject = context[ssrModuleExportsKey];
|
||||
const SYMBOL_NOT_DEFINED = Symbol("not defined");
|
||||
let moduleExports = SYMBOL_NOT_DEFINED;
|
||||
// this proxy is triggered only on exports.{name} and module.exports access
|
||||
// inside the module itself. imported module is always "exports"
|
||||
const cjsExports = new Proxy(exportsObject, {
|
||||
get: (target, p, receiver) => {
|
||||
if (Reflect.has(target, p)) return Reflect.get(target, p, receiver);
|
||||
return Reflect.get(Object.prototype, p, receiver);
|
||||
},
|
||||
getPrototypeOf: () => Object.prototype,
|
||||
set: (_, p, value) => {
|
||||
span.addEvent(`cjs export proxy is triggered for ${String(p)}`);
|
||||
// treat "module.exports =" the same as "exports.default =" to not have nested "default.default",
|
||||
// so "exports.default" becomes the actual module
|
||||
if (p === "default" && this.shouldInterop(module.file, { default: value }) && cjsExports !== value) {
|
||||
span.addEvent("`exports.default` is assigned, copying values");
|
||||
exportAll(cjsExports, value);
|
||||
exportsObject.default = value;
|
||||
return true;
|
||||
}
|
||||
if (!Reflect.has(exportsObject, "default")) exportsObject.default = {};
|
||||
// returns undefined, when accessing named exports, if default is not an object
|
||||
// but is still present inside hasOwnKeys, this is Node behaviour for CJS
|
||||
if (moduleExports !== SYMBOL_NOT_DEFINED && isPrimitive(moduleExports)) {
|
||||
span.addEvent(`\`exports.${String(p)}\` is assigned, but module.exports is a primitive. assigning "undefined" values instead to comply with ESM`);
|
||||
defineExport(exportsObject, p, () => void 0);
|
||||
return true;
|
||||
}
|
||||
if (!isPrimitive(exportsObject.default)) exportsObject.default[p] = value;
|
||||
if (p !== "default") defineExport(exportsObject, p, () => value);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
return {
|
||||
exports: cjsExports,
|
||||
module: {
|
||||
set exports(value) {
|
||||
span.addEvent("`module.exports` is assigned directly, copying all properties to `exports`");
|
||||
exportAll(cjsExports, value);
|
||||
exportsObject.default = value;
|
||||
moduleExports = value;
|
||||
},
|
||||
get exports() {
|
||||
return cjsExports;
|
||||
}
|
||||
},
|
||||
require: this.createRequire(context[ssrImportMetaKey].url),
|
||||
__filename: context[ssrImportMetaKey].filename,
|
||||
__dirname: context[ssrImportMetaKey].dirname
|
||||
};
|
||||
}
|
||||
async _runInlinedModule(context, code, module, span) {
|
||||
const meta = context[ssrImportMetaKey];
|
||||
meta.env = this.env;
|
||||
if (this.options.getCurrentTestFilepath?.() === module.file) {
|
||||
const globalNamespace = this.vm?.context || globalThis;
|
||||
Object.defineProperty(meta, "vitest", { get: () => globalNamespace.__vitest_index__ });
|
||||
}
|
||||
span.setAttribute("code.file.path", meta.filename);
|
||||
const argumentsList = [
|
||||
ssrModuleExportsKey,
|
||||
ssrImportMetaKey,
|
||||
ssrImportKey,
|
||||
ssrDynamicImportKey,
|
||||
ssrExportAllKey,
|
||||
"__vite_ssr_exportName__"
|
||||
];
|
||||
const cjsGlobals = this._createCJSGlobals(context, module, span);
|
||||
argumentsList.push(
|
||||
// TODO@discuss deprecate in Vitest 5, remove in Vitest 6(?)
|
||||
// backwards compat for vite-node
|
||||
"__filename",
|
||||
"__dirname",
|
||||
"module",
|
||||
"exports",
|
||||
"require"
|
||||
);
|
||||
if (this.compiledFunctionArgumentsNames) argumentsList.push(...this.compiledFunctionArgumentsNames);
|
||||
span.setAttribute("vitest.module.arguments", argumentsList);
|
||||
// add 'use strict' since ESM enables it by default
|
||||
const codeDefinition = `'use strict';async (${argumentsList.join(",")})=>{{`;
|
||||
const wrappedCode = `${codeDefinition}${code}\n}}`;
|
||||
const options = {
|
||||
filename: module.id.startsWith("mock:") ? module.id.slice(5) : module.id,
|
||||
lineOffset: 0,
|
||||
columnOffset: -codeDefinition.length
|
||||
};
|
||||
// this will always be 1 element because it's cached after load
|
||||
const importer = module.importers.values().next().value;
|
||||
const finishModuleExecutionInfo = this.debug.startCalculateModuleExecutionInfo(options.filename, {
|
||||
startOffset: codeDefinition.length,
|
||||
importer
|
||||
});
|
||||
try {
|
||||
await (this.vm ? vm.runInContext(wrappedCode, this.vm.context, options) : vm.runInThisContext(wrappedCode, options))(
|
||||
context[ssrModuleExportsKey],
|
||||
context[ssrImportMetaKey],
|
||||
context[ssrImportKey],
|
||||
context[ssrDynamicImportKey],
|
||||
context[ssrExportAllKey],
|
||||
// vite 7 support, remove when vite 7+ is supported
|
||||
context.__vite_ssr_exportName__ || ((name, getter) => Object.defineProperty(context[ssrModuleExportsKey], name, {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
get: getter
|
||||
})),
|
||||
cjsGlobals.__filename,
|
||||
cjsGlobals.__dirname,
|
||||
cjsGlobals.module,
|
||||
cjsGlobals.exports,
|
||||
cjsGlobals.require,
|
||||
...this.compiledFunctionArgumentsValues
|
||||
);
|
||||
} finally {
|
||||
// moduleExecutionInfo needs to use Node filename instead of the normalized one
|
||||
// because we rely on this behaviour in coverage-v8, for example
|
||||
this.options.moduleExecutionInfo?.set(options.filename, finishModuleExecutionInfo());
|
||||
}
|
||||
}
|
||||
createRequire(url) {
|
||||
if (url.startsWith("data:")) {
|
||||
const _require = (id) => {
|
||||
throw new SyntaxError(`require() is not supported in virtual modules. Trying to call require("${id}") in ${url}`);
|
||||
};
|
||||
_require.resolve = _require;
|
||||
return _require;
|
||||
}
|
||||
return this.vm ? this.vm.externalModulesExecutor.createRequire(url) : createRequire(url);
|
||||
}
|
||||
shouldInterop(path, mod) {
|
||||
if (this.options.interopDefault === false) return false;
|
||||
// never interop ESM modules
|
||||
// TODO: should also skip for `.js` with `type="module"`
|
||||
return !path.endsWith(".mjs") && "default" in mod;
|
||||
}
|
||||
}
|
||||
function createImportMetaEnvProxy() {
|
||||
// packages/vitest/src/node/plugins/index.ts:146
|
||||
const booleanKeys = [
|
||||
"DEV",
|
||||
"PROD",
|
||||
"SSR"
|
||||
];
|
||||
return new Proxy(process.env, {
|
||||
get(_, key) {
|
||||
if (typeof key !== "string") return;
|
||||
if (booleanKeys.includes(key)) return !!process.env[key];
|
||||
return process.env[key];
|
||||
},
|
||||
set(_, key, value) {
|
||||
if (typeof key !== "string") return true;
|
||||
if (booleanKeys.includes(key)) process.env[key] = value ? "1" : "";
|
||||
else process.env[key] = value;
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
function updateStyle(id, css) {
|
||||
if (typeof document === "undefined") return;
|
||||
const element = document.querySelector(`[data-vite-dev-id="${id}"]`);
|
||||
if (element) {
|
||||
element.textContent = css;
|
||||
return;
|
||||
}
|
||||
const head = document.querySelector("head");
|
||||
const style = document.createElement("style");
|
||||
style.setAttribute("type", "text/css");
|
||||
style.setAttribute("data-vite-dev-id", id);
|
||||
style.textContent = css;
|
||||
head?.appendChild(style);
|
||||
}
|
||||
function removeStyle(id) {
|
||||
if (typeof document === "undefined") return;
|
||||
const sheet = document.querySelector(`[data-vite-dev-id="${id}"]`);
|
||||
if (sheet) document.head.removeChild(sheet);
|
||||
}
|
||||
const defaultClientStub = {
|
||||
injectQuery: (id) => id,
|
||||
createHotContext: () => {
|
||||
return {
|
||||
accept: () => {},
|
||||
prune: () => {},
|
||||
dispose: () => {},
|
||||
decline: () => {},
|
||||
invalidate: () => {},
|
||||
on: () => {},
|
||||
send: () => {}
|
||||
};
|
||||
},
|
||||
updateStyle: () => {},
|
||||
removeStyle: () => {}
|
||||
};
|
||||
function getDefaultRequestStubs(context) {
|
||||
if (!context) {
|
||||
const clientStub = {
|
||||
...defaultClientStub,
|
||||
updateStyle,
|
||||
removeStyle
|
||||
};
|
||||
return { "/@vite/client": clientStub };
|
||||
}
|
||||
const clientStub = vm.runInContext(`(defaultClient) => ({ ...defaultClient, updateStyle: ${updateStyle.toString()}, removeStyle: ${removeStyle.toString()} })`, context)(defaultClientStub);
|
||||
return { "/@vite/client": clientStub };
|
||||
}
|
||||
function exportAll(exports$1, sourceModule) {
|
||||
// #1120 when a module exports itself it causes
|
||||
// call stack error
|
||||
if (exports$1 === sourceModule) return;
|
||||
if (isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise) return;
|
||||
for (const key in sourceModule) if (key !== "default" && !(key in exports$1)) try {
|
||||
defineExport(exports$1, key, () => sourceModule[key]);
|
||||
} catch {}
|
||||
}
|
||||
// keep consistency with Vite on how exports are defined
|
||||
function defineExport(exports$1, key, value) {
|
||||
Object.defineProperty(exports$1, key, {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
get: value
|
||||
});
|
||||
}
|
||||
function isPrimitive(v) {
|
||||
return !(typeof v === "object" || typeof v === "function") || v == null;
|
||||
}
|
||||
function interopModule(mod) {
|
||||
if (isPrimitive(mod)) return {
|
||||
mod: { default: mod },
|
||||
defaultExport: mod
|
||||
};
|
||||
let defaultExport = "default" in mod ? mod.default : mod;
|
||||
if (!isPrimitive(defaultExport) && "__esModule" in defaultExport) {
|
||||
mod = defaultExport;
|
||||
if ("default" in defaultExport) defaultExport = defaultExport.default;
|
||||
}
|
||||
return {
|
||||
mod,
|
||||
defaultExport
|
||||
};
|
||||
}
|
||||
const VALID_ID_PREFIX = `/@id/`;
|
||||
const NULL_BYTE_PLACEHOLDER = `__x00__`;
|
||||
function wrapId(id) {
|
||||
return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
|
||||
}
|
||||
function unwrapId(id) {
|
||||
return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id;
|
||||
}
|
||||
|
||||
export { VitestModuleEvaluator, createImportMetaEnvProxy, getDefaultRequestStubs, isPrimitive, unwrapId, wrapId };
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* @fileoverview ESLint Processor Service
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
/* eslint class-methods-use-this: off -- Anticipate future constructor arguments. */
|
||||
|
||||
"use strict";
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
const path = require("node:path");
|
||||
const { VFile } = require("../linter/vfile.js");
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Types
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/** @typedef {import("../types").Linter.LintMessage} LintMessage */
|
||||
/** @typedef {import("../linter/vfile.js").VFile} VFile */
|
||||
/** @typedef {import("@eslint/core").Language} Language */
|
||||
/** @typedef {import("eslint").Linter.Processor} Processor */
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Exports
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The service that applies processors to files.
|
||||
*/
|
||||
class ProcessorService {
|
||||
/**
|
||||
* Preprocesses the given file synchronously.
|
||||
* @param {VFile} file The file to preprocess.
|
||||
* @param {{processor:Processor}} config The configuration to use.
|
||||
* @returns {{ok:boolean, files?: Array<VFile>, errors?: Array<LintMessage>}} An array of preprocessed files or errors.
|
||||
* @throws {Error} If the preprocessor returns a promise.
|
||||
*/
|
||||
preprocessSync(file, config) {
|
||||
const { processor } = config;
|
||||
let blocks;
|
||||
|
||||
try {
|
||||
blocks = processor.preprocess(file.rawBody, file.path);
|
||||
} catch (ex) {
|
||||
// If the message includes a leading line number, strip it:
|
||||
const message = `Preprocessing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`;
|
||||
|
||||
return {
|
||||
ok: false,
|
||||
errors: [
|
||||
{
|
||||
ruleId: null,
|
||||
fatal: true,
|
||||
severity: 2,
|
||||
message,
|
||||
line: ex.lineNumber,
|
||||
column: ex.column,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof blocks.then === "function") {
|
||||
throw new Error("Unsupported: Preprocessor returned a promise.");
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
files: blocks.map((block, i) => {
|
||||
// Legacy behavior: return the block as a string
|
||||
if (typeof block === "string") {
|
||||
return block;
|
||||
}
|
||||
|
||||
const filePath = path.join(file.path, `${i}_${block.filename}`);
|
||||
|
||||
return new VFile(filePath, block.text, {
|
||||
physicalPath: file.physicalPath,
|
||||
});
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Postprocesses the given messages synchronously.
|
||||
* @param {VFile} file The file to postprocess.
|
||||
* @param {LintMessage[][]} messages The messages to postprocess.
|
||||
* @param {{processor:Processor}} config The configuration to use.
|
||||
* @returns {LintMessage[]} The postprocessed messages.
|
||||
*/
|
||||
postprocessSync(file, messages, config) {
|
||||
const { processor } = config;
|
||||
|
||||
return processor.postprocess(messages, file.path);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { ProcessorService };
|
||||
@@ -0,0 +1,44 @@
|
||||
'use strict';
|
||||
|
||||
var test = require('tape');
|
||||
var stringify = require('../');
|
||||
|
||||
test('nested', function (t) {
|
||||
t.plan(1);
|
||||
var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 };
|
||||
t.equal(stringify(obj), '{"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8}');
|
||||
});
|
||||
|
||||
test('cyclic (default)', function (t) {
|
||||
t.plan(1);
|
||||
var one = { a: 1 };
|
||||
var two = { a: 2, one: one };
|
||||
one.two = two;
|
||||
try {
|
||||
stringify(one);
|
||||
} catch (ex) {
|
||||
t.equal(ex.toString(), 'TypeError: Converting circular structure to JSON');
|
||||
}
|
||||
});
|
||||
|
||||
test('cyclic (specifically allowed)', function (t) {
|
||||
t.plan(1);
|
||||
var one = { a: 1 };
|
||||
var two = { a: 2, one: one };
|
||||
one.two = two;
|
||||
t.equal(stringify(one, {cycles:true}), '{"a":1,"two":{"a":2,"one":"__cycle__"}}');
|
||||
});
|
||||
|
||||
test('repeated non-cyclic value', function(t) {
|
||||
t.plan(1);
|
||||
var one = { x: 1 };
|
||||
var two = { a: one, b: one };
|
||||
t.equal(stringify(two), '{"a":{"x":1},"b":{"x":1}}');
|
||||
});
|
||||
|
||||
test('acyclic but with reused obj-property pointers', function (t) {
|
||||
t.plan(1);
|
||||
var x = { a: 1 };
|
||||
var y = { b: x, c: x };
|
||||
t.equal(stringify(y), '{"b":{"a":1},"c":{"a":1}}');
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: [ljharb]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: npm/minimist
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
otechie: # Replace with a single Otechie username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
@@ -0,0 +1,33 @@
|
||||
declare const _default: {
|
||||
extends: string[];
|
||||
rules: {
|
||||
'@typescript-eslint/await-thenable': "error";
|
||||
'@typescript-eslint/no-array-delete': "error";
|
||||
'@typescript-eslint/no-base-to-string': "error";
|
||||
'@typescript-eslint/no-duplicate-type-constituents': "error";
|
||||
'@typescript-eslint/no-floating-promises': "error";
|
||||
'@typescript-eslint/no-for-in-array': "error";
|
||||
'no-implied-eval': "off";
|
||||
'@typescript-eslint/no-implied-eval': "error";
|
||||
'@typescript-eslint/no-misused-promises': "error";
|
||||
'@typescript-eslint/no-redundant-type-constituents': "error";
|
||||
'@typescript-eslint/no-unnecessary-type-assertion': "error";
|
||||
'@typescript-eslint/no-unsafe-argument': "error";
|
||||
'@typescript-eslint/no-unsafe-assignment': "error";
|
||||
'@typescript-eslint/no-unsafe-call': "error";
|
||||
'@typescript-eslint/no-unsafe-enum-comparison': "error";
|
||||
'@typescript-eslint/no-unsafe-member-access': "error";
|
||||
'@typescript-eslint/no-unsafe-return': "error";
|
||||
'@typescript-eslint/no-unsafe-unary-minus': "error";
|
||||
'no-throw-literal': "off";
|
||||
'@typescript-eslint/only-throw-error': "error";
|
||||
'prefer-promise-reject-errors': "off";
|
||||
'@typescript-eslint/prefer-promise-reject-errors': "error";
|
||||
'require-await': "off";
|
||||
'@typescript-eslint/require-await': "error";
|
||||
'@typescript-eslint/restrict-plus-operands': "error";
|
||||
'@typescript-eslint/restrict-template-expressions': "error";
|
||||
'@typescript-eslint/unbound-method': "error";
|
||||
};
|
||||
};
|
||||
export = _default;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,463 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.edwardsToMontgomery = exports.hash_to_decaf448 = exports.hashToDecaf448 = exports.encodeToCurve = exports.hashToCurve = exports.DecafPoint = exports.ED448_TORSION_SUBGROUP = exports.decaf448_hasher = exports.decaf448 = exports.ed448_hasher = exports.x448 = exports.E448 = exports.ed448ph = exports.ed448 = void 0;
|
||||
exports.edwardsToMontgomeryPub = edwardsToMontgomeryPub;
|
||||
/**
|
||||
* Edwards448 (not Ed448-Goldilocks) curve with following addons:
|
||||
* - X448 ECDH
|
||||
* - Decaf cofactor elimination
|
||||
* - Elligator hash-to-group / point indistinguishability
|
||||
* Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
const sha3_js_1 = require("@noble/hashes/sha3.js");
|
||||
const utils_js_1 = require("@noble/hashes/utils.js");
|
||||
const curve_ts_1 = require("./abstract/curve.js");
|
||||
const edwards_ts_1 = require("./abstract/edwards.js");
|
||||
const hash_to_curve_ts_1 = require("./abstract/hash-to-curve.js");
|
||||
const modular_ts_1 = require("./abstract/modular.js");
|
||||
const montgomery_ts_1 = require("./abstract/montgomery.js");
|
||||
const utils_ts_1 = require("./utils.js");
|
||||
// edwards448 curve
|
||||
// a = 1n
|
||||
// d = Fp.neg(39081n)
|
||||
// Finite field 2n**448n - 2n**224n - 1n
|
||||
// Subgroup order
|
||||
// 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n
|
||||
const ed448_CURVE = {
|
||||
p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffff'),
|
||||
n: BigInt('0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffff7cca23e9c44edb49aed63690216cc2728dc58f552378c292ab5844f3'),
|
||||
h: BigInt(4),
|
||||
a: BigInt(1),
|
||||
d: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffff6756'),
|
||||
Gx: BigInt('0x4f1970c66bed0ded221d15a622bf36da9e146570470f1767ea6de324a3d3a46412ae1af72ab66511433b80e18b00938e2626a82bc70cc05e'),
|
||||
Gy: BigInt('0x693f46716eb6bc248876203756c9c7624bea73736ca3984087789c1e05a0c2d73ad3ff1ce67c39c4fdbd132c4ed7c8ad9808795bf230fa14'),
|
||||
};
|
||||
// E448 NIST curve is identical to edwards448, except for:
|
||||
// d = 39082/39081
|
||||
// Gx = 3/2
|
||||
const E448_CURVE = Object.assign({}, ed448_CURVE, {
|
||||
d: BigInt('0xd78b4bdc7f0daf19f24f38c29373a2ccad46157242a50f37809b1da3412a12e79ccc9c81264cfe9ad080997058fb61c4243cc32dbaa156b9'),
|
||||
Gx: BigInt('0x79a70b2b70400553ae7c9df416c792c61128751ac92969240c25a07d728bdc93e21f7787ed6972249de732f38496cd11698713093e9c04fc'),
|
||||
Gy: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffff80000000000000000000000000000000000000000000000000000001'),
|
||||
});
|
||||
const shake256_114 = /* @__PURE__ */ (0, utils_js_1.createHasher)(() => sha3_js_1.shake256.create({ dkLen: 114 }));
|
||||
const shake256_64 = /* @__PURE__ */ (0, utils_js_1.createHasher)(() => sha3_js_1.shake256.create({ dkLen: 64 }));
|
||||
// prettier-ignore
|
||||
const _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4), _11n = BigInt(11);
|
||||
// prettier-ignore
|
||||
const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223);
|
||||
// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4.
|
||||
// Used for efficient square root calculation.
|
||||
// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1]
|
||||
function ed448_pow_Pminus3div4(x) {
|
||||
const P = ed448_CURVE.p;
|
||||
const b2 = (x * x * x) % P;
|
||||
const b3 = (b2 * b2 * x) % P;
|
||||
const b6 = ((0, modular_ts_1.pow2)(b3, _3n, P) * b3) % P;
|
||||
const b9 = ((0, modular_ts_1.pow2)(b6, _3n, P) * b3) % P;
|
||||
const b11 = ((0, modular_ts_1.pow2)(b9, _2n, P) * b2) % P;
|
||||
const b22 = ((0, modular_ts_1.pow2)(b11, _11n, P) * b11) % P;
|
||||
const b44 = ((0, modular_ts_1.pow2)(b22, _22n, P) * b22) % P;
|
||||
const b88 = ((0, modular_ts_1.pow2)(b44, _44n, P) * b44) % P;
|
||||
const b176 = ((0, modular_ts_1.pow2)(b88, _88n, P) * b88) % P;
|
||||
const b220 = ((0, modular_ts_1.pow2)(b176, _44n, P) * b44) % P;
|
||||
const b222 = ((0, modular_ts_1.pow2)(b220, _2n, P) * b2) % P;
|
||||
const b223 = ((0, modular_ts_1.pow2)(b222, _1n, P) * x) % P;
|
||||
return ((0, modular_ts_1.pow2)(b223, _223n, P) * b222) % P;
|
||||
}
|
||||
function adjustScalarBytes(bytes) {
|
||||
// Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0,
|
||||
bytes[0] &= 252; // 0b11111100
|
||||
// and the most significant bit of the last byte to 1.
|
||||
bytes[55] |= 128; // 0b10000000
|
||||
// NOTE: is NOOP for 56 bytes scalars (X25519/X448)
|
||||
bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits)
|
||||
return bytes;
|
||||
}
|
||||
// Constant-time ratio of u to v. Allows to combine inversion and square root u/√v.
|
||||
// Uses algo from RFC8032 5.1.3.
|
||||
function uvRatio(u, v) {
|
||||
const P = ed448_CURVE.p;
|
||||
// https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3
|
||||
// To compute the square root of (u/v), the first step is to compute the
|
||||
// candidate root x = (u/v)^((p+1)/4). This can be done using the
|
||||
// following trick, to use a single modular powering for both the
|
||||
// inversion of v and the square root:
|
||||
// x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p)
|
||||
const u2v = (0, modular_ts_1.mod)(u * u * v, P); // u²v
|
||||
const u3v = (0, modular_ts_1.mod)(u2v * u, P); // u³v
|
||||
const u5v3 = (0, modular_ts_1.mod)(u3v * u2v * v, P); // u⁵v³
|
||||
const root = ed448_pow_Pminus3div4(u5v3);
|
||||
const x = (0, modular_ts_1.mod)(u3v * root, P);
|
||||
// Verify that root is exists
|
||||
const x2 = (0, modular_ts_1.mod)(x * x, P); // x²
|
||||
// If vx² = u, the recovered x-coordinate is x. Otherwise, no
|
||||
// square root exists, and the decoding fails.
|
||||
return { isValid: (0, modular_ts_1.mod)(x2 * v, P) === u, value: x };
|
||||
}
|
||||
// Finite field 2n**448n - 2n**224n - 1n
|
||||
// The value fits in 448 bits, but we use 456-bit (57-byte) elements because of bitflags.
|
||||
// - ed25519 fits in 255 bits, allowing using last 1 byte for specifying bit flag of point negation.
|
||||
// - ed448 fits in 448 bits. We can't use last 1 byte: we can only use a bit 224 in the middle.
|
||||
const Fp = /* @__PURE__ */ (() => (0, modular_ts_1.Field)(ed448_CURVE.p, { BITS: 456, isLE: true }))();
|
||||
const Fn = /* @__PURE__ */ (() => (0, modular_ts_1.Field)(ed448_CURVE.n, { BITS: 456, isLE: true }))();
|
||||
// decaf448 uses 448-bit (56-byte) keys
|
||||
const Fp448 = /* @__PURE__ */ (() => (0, modular_ts_1.Field)(ed448_CURVE.p, { BITS: 448, isLE: true }))();
|
||||
const Fn448 = /* @__PURE__ */ (() => (0, modular_ts_1.Field)(ed448_CURVE.n, { BITS: 448, isLE: true }))();
|
||||
// SHAKE256(dom4(phflag,context)||x, 114)
|
||||
function dom4(data, ctx, phflag) {
|
||||
if (ctx.length > 255)
|
||||
throw new Error('context must be smaller than 255, got: ' + ctx.length);
|
||||
return (0, utils_js_1.concatBytes)((0, utils_ts_1.asciiToBytes)('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);
|
||||
}
|
||||
// const ed448_eddsa_opts = { adjustScalarBytes, domain: dom4 };
|
||||
// const ed448_Point = edwards(ed448_CURVE, { Fp, Fn, uvRatio });
|
||||
const ED448_DEF = /* @__PURE__ */ (() => ({
|
||||
...ed448_CURVE,
|
||||
Fp,
|
||||
Fn,
|
||||
nBitLength: Fn.BITS,
|
||||
hash: shake256_114,
|
||||
adjustScalarBytes,
|
||||
domain: dom4,
|
||||
uvRatio,
|
||||
}))();
|
||||
/**
|
||||
* ed448 EdDSA curve and methods.
|
||||
* @example
|
||||
* import { ed448 } from '@noble/curves/ed448';
|
||||
* const { secretKey, publicKey } = ed448.keygen();
|
||||
* const msg = new TextEncoder().encode('hello');
|
||||
* const sig = ed448.sign(msg, secretKey);
|
||||
* const isValid = ed448.verify(sig, msg, publicKey);
|
||||
*/
|
||||
exports.ed448 = (0, edwards_ts_1.twistedEdwards)(ED448_DEF);
|
||||
// There is no ed448ctx, since ed448 supports ctx by default
|
||||
/** Prehashed version of ed448. Accepts already-hashed messages in sign() and verify(). */
|
||||
exports.ed448ph = (() => (0, edwards_ts_1.twistedEdwards)({
|
||||
...ED448_DEF,
|
||||
prehash: shake256_64,
|
||||
}))();
|
||||
/**
|
||||
* E448 curve, defined by NIST.
|
||||
* E448 != edwards448 used in ed448.
|
||||
* E448 is birationally equivalent to edwards448.
|
||||
*/
|
||||
exports.E448 = (0, edwards_ts_1.edwards)(E448_CURVE);
|
||||
/**
|
||||
* ECDH using curve448 aka x448.
|
||||
* x448 has 56-byte keys as per RFC 7748, while
|
||||
* ed448 has 57-byte keys as per RFC 8032.
|
||||
*/
|
||||
exports.x448 = (() => {
|
||||
const P = ed448_CURVE.p;
|
||||
return (0, montgomery_ts_1.montgomery)({
|
||||
P,
|
||||
type: 'x448',
|
||||
powPminus2: (x) => {
|
||||
const Pminus3div4 = ed448_pow_Pminus3div4(x);
|
||||
const Pminus3 = (0, modular_ts_1.pow2)(Pminus3div4, _2n, P);
|
||||
return (0, modular_ts_1.mod)(Pminus3 * x, P); // Pminus3 * x = Pminus2
|
||||
},
|
||||
adjustScalarBytes,
|
||||
});
|
||||
})();
|
||||
// Hash To Curve Elligator2 Map
|
||||
const ELL2_C1 = /* @__PURE__ */ (() => (Fp.ORDER - BigInt(3)) / BigInt(4))(); // 1. c1 = (q - 3) / 4 # Integer arithmetic
|
||||
const ELL2_J = /* @__PURE__ */ BigInt(156326);
|
||||
function map_to_curve_elligator2_curve448(u) {
|
||||
let tv1 = Fp.sqr(u); // 1. tv1 = u^2
|
||||
let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1
|
||||
tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0
|
||||
let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1
|
||||
let x1n = Fp.neg(ELL2_J); // 5. x1n = -J
|
||||
let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2
|
||||
let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3
|
||||
let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd
|
||||
gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd
|
||||
gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2
|
||||
gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2
|
||||
let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2
|
||||
tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd
|
||||
tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3
|
||||
let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4)
|
||||
y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4)
|
||||
let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd
|
||||
let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u
|
||||
y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1)
|
||||
tv2 = Fp.sqr(y1); // 20. tv2 = y1^2
|
||||
tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd
|
||||
let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1
|
||||
let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2
|
||||
let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2
|
||||
let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y
|
||||
y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3)
|
||||
return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1)
|
||||
}
|
||||
function map_to_curve_elligator2_edwards448(u) {
|
||||
let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u)
|
||||
let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2
|
||||
let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2
|
||||
let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2
|
||||
let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2
|
||||
let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2
|
||||
let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2
|
||||
let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2
|
||||
xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2
|
||||
xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd
|
||||
xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn
|
||||
xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4
|
||||
tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2
|
||||
tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2
|
||||
let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2
|
||||
let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2
|
||||
tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4
|
||||
let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2
|
||||
tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn
|
||||
let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4
|
||||
let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2
|
||||
yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4
|
||||
yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2
|
||||
tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2
|
||||
tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2
|
||||
tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd
|
||||
tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2
|
||||
tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1
|
||||
let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1
|
||||
tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2
|
||||
yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4
|
||||
tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd
|
||||
let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0
|
||||
xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e)
|
||||
xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e)
|
||||
yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e)
|
||||
yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e)
|
||||
const inv = (0, modular_ts_1.FpInvertBatch)(Fp, [xEd, yEd], true); // batch division
|
||||
return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd)
|
||||
}
|
||||
/** Hashing / encoding to ed448 points / field. RFC 9380 methods. */
|
||||
exports.ed448_hasher = (() => (0, hash_to_curve_ts_1.createHasher)(exports.ed448.Point, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), {
|
||||
DST: 'edwards448_XOF:SHAKE256_ELL2_RO_',
|
||||
encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_',
|
||||
p: Fp.ORDER,
|
||||
m: 1,
|
||||
k: 224,
|
||||
expand: 'xof',
|
||||
hash: sha3_js_1.shake256,
|
||||
}))();
|
||||
// 1-d
|
||||
const ONE_MINUS_D = /* @__PURE__ */ BigInt('39082');
|
||||
// 1-2d
|
||||
const ONE_MINUS_TWO_D = /* @__PURE__ */ BigInt('78163');
|
||||
// √(-d)
|
||||
const SQRT_MINUS_D = /* @__PURE__ */ BigInt('98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214');
|
||||
// 1 / √(-d)
|
||||
const INVSQRT_MINUS_D = /* @__PURE__ */ BigInt('315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716');
|
||||
// Calculates 1/√(number)
|
||||
const invertSqrt = (number) => uvRatio(_1n, number);
|
||||
/**
|
||||
* Elligator map for hash-to-curve of decaf448.
|
||||
* Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-C)
|
||||
* and [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-element-derivation-2).
|
||||
*/
|
||||
function calcElligatorDecafMap(r0) {
|
||||
const { d } = ed448_CURVE;
|
||||
const P = Fp.ORDER;
|
||||
const mod = (n) => Fp.create(n);
|
||||
const r = mod(-(r0 * r0)); // 1
|
||||
const u0 = mod(d * (r - _1n)); // 2
|
||||
const u1 = mod((u0 + _1n) * (u0 - r)); // 3
|
||||
const { isValid: was_square, value: v } = uvRatio(ONE_MINUS_TWO_D, mod((r + _1n) * u1)); // 4
|
||||
let v_prime = v; // 5
|
||||
if (!was_square)
|
||||
v_prime = mod(r0 * v);
|
||||
let sgn = _1n; // 6
|
||||
if (!was_square)
|
||||
sgn = mod(-_1n);
|
||||
const s = mod(v_prime * (r + _1n)); // 7
|
||||
let s_abs = s;
|
||||
if ((0, modular_ts_1.isNegativeLE)(s, P))
|
||||
s_abs = mod(-s);
|
||||
const s2 = s * s;
|
||||
const W0 = mod(s_abs * _2n); // 8
|
||||
const W1 = mod(s2 + _1n); // 9
|
||||
const W2 = mod(s2 - _1n); // 10
|
||||
const W3 = mod(v_prime * s * (r - _1n) * ONE_MINUS_TWO_D + sgn); // 11
|
||||
return new exports.ed448.Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));
|
||||
}
|
||||
function decaf448_map(bytes) {
|
||||
(0, utils_js_1.abytes)(bytes, 112);
|
||||
const skipValidation = true;
|
||||
// Note: Similar to the field element decoding described in
|
||||
// [RFC7748], and unlike the field element decoding described in
|
||||
// Section 5.3.1, non-canonical values are accepted.
|
||||
const r1 = Fp448.create(Fp448.fromBytes(bytes.subarray(0, 56), skipValidation));
|
||||
const R1 = calcElligatorDecafMap(r1);
|
||||
const r2 = Fp448.create(Fp448.fromBytes(bytes.subarray(56, 112), skipValidation));
|
||||
const R2 = calcElligatorDecafMap(r2);
|
||||
return new _DecafPoint(R1.add(R2));
|
||||
}
|
||||
/**
|
||||
* Each ed448/EdwardsPoint has 4 different equivalent points. This can be
|
||||
* a source of bugs for protocols like ring signatures. Decaf was created to solve this.
|
||||
* Decaf point operates in X:Y:Z:T extended coordinates like EdwardsPoint,
|
||||
* but it should work in its own namespace: do not combine those two.
|
||||
* See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).
|
||||
*/
|
||||
class _DecafPoint extends edwards_ts_1.PrimeEdwardsPoint {
|
||||
constructor(ep) {
|
||||
super(ep);
|
||||
}
|
||||
static fromAffine(ap) {
|
||||
return new _DecafPoint(exports.ed448.Point.fromAffine(ap));
|
||||
}
|
||||
assertSame(other) {
|
||||
if (!(other instanceof _DecafPoint))
|
||||
throw new Error('DecafPoint expected');
|
||||
}
|
||||
init(ep) {
|
||||
return new _DecafPoint(ep);
|
||||
}
|
||||
/** @deprecated use `import { decaf448_hasher } from '@noble/curves/ed448.js';` */
|
||||
static hashToCurve(hex) {
|
||||
return decaf448_map((0, utils_ts_1.ensureBytes)('decafHash', hex, 112));
|
||||
}
|
||||
static fromBytes(bytes) {
|
||||
(0, utils_js_1.abytes)(bytes, 56);
|
||||
const { d } = ed448_CURVE;
|
||||
const P = Fp.ORDER;
|
||||
const mod = (n) => Fp448.create(n);
|
||||
const s = Fp448.fromBytes(bytes);
|
||||
// 1. Check that s_bytes is the canonical encoding of a field element, or else abort.
|
||||
// 2. Check that s is non-negative, or else abort
|
||||
if (!(0, utils_ts_1.equalBytes)(Fn448.toBytes(s), bytes) || (0, modular_ts_1.isNegativeLE)(s, P))
|
||||
throw new Error('invalid decaf448 encoding 1');
|
||||
const s2 = mod(s * s); // 1
|
||||
const u1 = mod(_1n + s2); // 2
|
||||
const u1sq = mod(u1 * u1);
|
||||
const u2 = mod(u1sq - _4n * d * s2); // 3
|
||||
const { isValid, value: invsqrt } = invertSqrt(mod(u2 * u1sq)); // 4
|
||||
let u3 = mod((s + s) * invsqrt * u1 * SQRT_MINUS_D); // 5
|
||||
if ((0, modular_ts_1.isNegativeLE)(u3, P))
|
||||
u3 = mod(-u3);
|
||||
const x = mod(u3 * invsqrt * u2 * INVSQRT_MINUS_D); // 6
|
||||
const y = mod((_1n - s2) * invsqrt * u1); // 7
|
||||
const t = mod(x * y); // 8
|
||||
if (!isValid)
|
||||
throw new Error('invalid decaf448 encoding 2');
|
||||
return new _DecafPoint(new exports.ed448.Point(x, y, _1n, t));
|
||||
}
|
||||
/**
|
||||
* Converts decaf-encoded string to decaf point.
|
||||
* Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode-2).
|
||||
* @param hex Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding
|
||||
*/
|
||||
static fromHex(hex) {
|
||||
return _DecafPoint.fromBytes((0, utils_ts_1.ensureBytes)('decafHex', hex, 56));
|
||||
}
|
||||
/** @deprecated use `import { pippenger } from '@noble/curves/abstract/curve.js';` */
|
||||
static msm(points, scalars) {
|
||||
return (0, curve_ts_1.pippenger)(_DecafPoint, Fn, points, scalars);
|
||||
}
|
||||
/**
|
||||
* Encodes decaf point to Uint8Array.
|
||||
* Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode-2).
|
||||
*/
|
||||
toBytes() {
|
||||
const { X, Z, T } = this.ep;
|
||||
const P = Fp.ORDER;
|
||||
const mod = (n) => Fp.create(n);
|
||||
const u1 = mod(mod(X + T) * mod(X - T)); // 1
|
||||
const x2 = mod(X * X);
|
||||
const { value: invsqrt } = invertSqrt(mod(u1 * ONE_MINUS_D * x2)); // 2
|
||||
let ratio = mod(invsqrt * u1 * SQRT_MINUS_D); // 3
|
||||
if ((0, modular_ts_1.isNegativeLE)(ratio, P))
|
||||
ratio = mod(-ratio);
|
||||
const u2 = mod(INVSQRT_MINUS_D * ratio * Z - T); // 4
|
||||
let s = mod(ONE_MINUS_D * invsqrt * X * u2); // 5
|
||||
if ((0, modular_ts_1.isNegativeLE)(s, P))
|
||||
s = mod(-s);
|
||||
return Fn448.toBytes(s);
|
||||
}
|
||||
/**
|
||||
* Compare one point to another.
|
||||
* Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals-2).
|
||||
*/
|
||||
equals(other) {
|
||||
this.assertSame(other);
|
||||
const { X: X1, Y: Y1 } = this.ep;
|
||||
const { X: X2, Y: Y2 } = other.ep;
|
||||
// (x1 * y2 == y1 * x2)
|
||||
return Fp.create(X1 * Y2) === Fp.create(Y1 * X2);
|
||||
}
|
||||
is0() {
|
||||
return this.equals(_DecafPoint.ZERO);
|
||||
}
|
||||
}
|
||||
// The following gymnastics is done because typescript strips comments otherwise
|
||||
// prettier-ignore
|
||||
_DecafPoint.BASE =
|
||||
/* @__PURE__ */ (() => new _DecafPoint(exports.ed448.Point.BASE).multiplyUnsafe(_2n))();
|
||||
// prettier-ignore
|
||||
_DecafPoint.ZERO =
|
||||
/* @__PURE__ */ (() => new _DecafPoint(exports.ed448.Point.ZERO))();
|
||||
// prettier-ignore
|
||||
_DecafPoint.Fp =
|
||||
/* @__PURE__ */ (() => Fp448)();
|
||||
// prettier-ignore
|
||||
_DecafPoint.Fn =
|
||||
/* @__PURE__ */ (() => Fn448)();
|
||||
exports.decaf448 = { Point: _DecafPoint };
|
||||
/** Hashing to decaf448 points / field. RFC 9380 methods. */
|
||||
exports.decaf448_hasher = {
|
||||
hashToCurve(msg, options) {
|
||||
const DST = options?.DST || 'decaf448_XOF:SHAKE256_D448MAP_RO_';
|
||||
return decaf448_map((0, hash_to_curve_ts_1.expand_message_xof)(msg, DST, 112, 224, sha3_js_1.shake256));
|
||||
},
|
||||
// Warning: has big modulo bias of 2^-64.
|
||||
// RFC is invalid. RFC says "use 64-byte xof", while for 2^-112 bias
|
||||
// it must use 84-byte xof (56+56/2), not 64.
|
||||
hashToScalar(msg, options = { DST: hash_to_curve_ts_1._DST_scalar }) {
|
||||
// Can't use `Fn448.fromBytes()`. 64-byte input => 56-byte field element
|
||||
const xof = (0, hash_to_curve_ts_1.expand_message_xof)(msg, options.DST, 64, 256, sha3_js_1.shake256);
|
||||
return Fn448.create((0, utils_ts_1.bytesToNumberLE)(xof));
|
||||
},
|
||||
};
|
||||
// export const decaf448_oprf: OPRF = createORPF({
|
||||
// name: 'decaf448-SHAKE256',
|
||||
// Point: DecafPoint,
|
||||
// hash: (msg: Uint8Array) => shake256(msg, { dkLen: 64 }),
|
||||
// hashToGroup: decaf448_hasher.hashToCurve,
|
||||
// hashToScalar: decaf448_hasher.hashToScalar,
|
||||
// });
|
||||
/**
|
||||
* Weird / bogus points, useful for debugging.
|
||||
* Unlike ed25519, there is no ed448 generator point which can produce full T subgroup.
|
||||
* Instead, there is a Klein four-group, which spans over 2 independent 2-torsion points:
|
||||
* (0, 1), (0, -1), (-1, 0), (1, 0).
|
||||
*/
|
||||
exports.ED448_TORSION_SUBGROUP = [
|
||||
'010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
|
||||
'fefffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffff00',
|
||||
'000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
|
||||
'000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080',
|
||||
];
|
||||
/** @deprecated use `decaf448.Point` */
|
||||
exports.DecafPoint = _DecafPoint;
|
||||
/** @deprecated use `import { ed448_hasher } from '@noble/curves/ed448.js';` */
|
||||
exports.hashToCurve = (() => exports.ed448_hasher.hashToCurve)();
|
||||
/** @deprecated use `import { ed448_hasher } from '@noble/curves/ed448.js';` */
|
||||
exports.encodeToCurve = (() => exports.ed448_hasher.encodeToCurve)();
|
||||
/** @deprecated use `import { decaf448_hasher } from '@noble/curves/ed448.js';` */
|
||||
exports.hashToDecaf448 = (() => exports.decaf448_hasher.hashToCurve)();
|
||||
/** @deprecated use `import { decaf448_hasher } from '@noble/curves/ed448.js';` */
|
||||
exports.hash_to_decaf448 = (() => exports.decaf448_hasher.hashToCurve)();
|
||||
/** @deprecated use `ed448.utils.toMontgomery` */
|
||||
function edwardsToMontgomeryPub(edwardsPub) {
|
||||
return exports.ed448.utils.toMontgomery((0, utils_ts_1.ensureBytes)('pub', edwardsPub));
|
||||
}
|
||||
/** @deprecated use `ed448.utils.toMontgomery` */
|
||||
exports.edwardsToMontgomery = edwardsToMontgomeryPub;
|
||||
//# sourceMappingURL=ed448.js.map
|
||||
@@ -0,0 +1,63 @@
|
||||
'use strict';
|
||||
|
||||
const uuid = require('uuid').v4;
|
||||
|
||||
/**
|
||||
* Generates a JSON-RPC 1.0 or 2.0 request
|
||||
* @param {String} method Name of method to call
|
||||
* @param {Array|Object} params Array of parameters passed to the method as specified, or an object of parameter names and corresponding value
|
||||
* @param {String|Number|null} [id] Request ID can be a string, number, null for explicit notification or left out for automatic generation
|
||||
* @param {Object} [options]
|
||||
* @param {Number} [options.version=2] JSON-RPC version to use (1 or 2)
|
||||
* @param {Boolean} [options.notificationIdNull=false] When true, version 2 requests will set id to null instead of omitting it
|
||||
* @param {Function} [options.generator] Passed the request, and the options object and is expected to return a request ID
|
||||
* @throws {TypeError} If any of the parameters are invalid
|
||||
* @return {Object} A JSON-RPC 1.0 or 2.0 request
|
||||
* @memberOf Utils
|
||||
*/
|
||||
const generateRequest = function(method, params, id, options) {
|
||||
if(typeof method !== 'string') {
|
||||
throw new TypeError(method + ' must be a string');
|
||||
}
|
||||
|
||||
options = options || {};
|
||||
|
||||
// check valid version provided
|
||||
const version = typeof options.version === 'number' ? options.version : 2;
|
||||
if (version !== 1 && version !== 2) {
|
||||
throw new TypeError(version + ' must be 1 or 2');
|
||||
}
|
||||
|
||||
const request = {
|
||||
method: method
|
||||
};
|
||||
|
||||
if(version === 2) {
|
||||
request.jsonrpc = '2.0';
|
||||
}
|
||||
|
||||
if(params) {
|
||||
// params given, but invalid?
|
||||
if(typeof params !== 'object' && !Array.isArray(params)) {
|
||||
throw new TypeError(params + ' must be an object, array or omitted');
|
||||
}
|
||||
request.params = params;
|
||||
}
|
||||
|
||||
// if id was left out, generate one (null means explicit notification)
|
||||
if(typeof(id) === 'undefined') {
|
||||
const generator = typeof options.generator === 'function' ? options.generator : function() { return uuid(); };
|
||||
request.id = generator(request, options);
|
||||
} else if (version === 2 && id === null) {
|
||||
// we have a version 2 notification
|
||||
if (options.notificationIdNull) {
|
||||
request.id = null; // id will not be set at all unless option provided
|
||||
}
|
||||
} else {
|
||||
request.id = id;
|
||||
}
|
||||
|
||||
return request;
|
||||
};
|
||||
|
||||
module.exports = generateRequest;
|
||||
@@ -0,0 +1,983 @@
|
||||
import type * as checks from "./checks.js";
|
||||
import { globalConfig } from "./core.js";
|
||||
import type { $ZodConfig } from "./core.js";
|
||||
import type * as errors from "./errors.js";
|
||||
import type * as schemas from "./schemas.js";
|
||||
|
||||
// json
|
||||
export type JSONType = string | number | boolean | null | JSONType[] | { [key: string]: JSONType };
|
||||
export type JWTAlgorithm =
|
||||
| "HS256"
|
||||
| "HS384"
|
||||
| "HS512"
|
||||
| "RS256"
|
||||
| "RS384"
|
||||
| "RS512"
|
||||
| "ES256"
|
||||
| "ES384"
|
||||
| "ES512"
|
||||
| "PS256"
|
||||
| "PS384"
|
||||
| "PS512"
|
||||
| "EdDSA"
|
||||
| (string & {});
|
||||
|
||||
export type HashAlgorithm = "md5" | "sha1" | "sha256" | "sha384" | "sha512";
|
||||
export type HashEncoding = "hex" | "base64" | "base64url";
|
||||
export type HashFormat = `${HashAlgorithm}_${HashEncoding}`;
|
||||
export type IPVersion = "v4" | "v6";
|
||||
export type MimeTypes =
|
||||
| "application/json"
|
||||
| "application/xml"
|
||||
| "application/x-www-form-urlencoded"
|
||||
| "application/javascript"
|
||||
| "application/pdf"
|
||||
| "application/zip"
|
||||
| "application/vnd.ms-excel"
|
||||
| "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
| "application/msword"
|
||||
| "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||
| "application/vnd.ms-powerpoint"
|
||||
| "application/vnd.openxmlformats-officedocument.presentationml.presentation"
|
||||
| "application/octet-stream"
|
||||
| "application/graphql"
|
||||
| "text/html"
|
||||
| "text/plain"
|
||||
| "text/css"
|
||||
| "text/javascript"
|
||||
| "text/csv"
|
||||
| "image/png"
|
||||
| "image/jpeg"
|
||||
| "image/gif"
|
||||
| "image/svg+xml"
|
||||
| "image/webp"
|
||||
| "audio/mpeg"
|
||||
| "audio/ogg"
|
||||
| "audio/wav"
|
||||
| "audio/webm"
|
||||
| "video/mp4"
|
||||
| "video/webm"
|
||||
| "video/ogg"
|
||||
| "font/woff"
|
||||
| "font/woff2"
|
||||
| "font/ttf"
|
||||
| "font/otf"
|
||||
| "multipart/form-data"
|
||||
| (string & {});
|
||||
export type ParsedTypes =
|
||||
| "string"
|
||||
| "number"
|
||||
| "bigint"
|
||||
| "boolean"
|
||||
| "symbol"
|
||||
| "undefined"
|
||||
| "object"
|
||||
| "function"
|
||||
| "file"
|
||||
| "date"
|
||||
| "array"
|
||||
| "map"
|
||||
| "set"
|
||||
| "nan"
|
||||
| "null"
|
||||
| "promise";
|
||||
|
||||
// utils
|
||||
export type AssertEqual<T, U> = (<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2 ? true : false;
|
||||
export type AssertNotEqual<T, U> = (<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2 ? false : true;
|
||||
export type AssertExtends<T, U> = T extends U ? T : never;
|
||||
export type IsAny<T> = 0 extends 1 & T ? true : false;
|
||||
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
|
||||
export type OmitKeys<T, K extends string> = Pick<T, Exclude<keyof T, K>>;
|
||||
export type MakePartial<T, K extends keyof T> = Omit<T, K> & InexactPartial<Pick<T, K>>;
|
||||
export type MakeRequired<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
|
||||
|
||||
export type Exactly<T, X> = T & Record<Exclude<keyof X, keyof T>, never>;
|
||||
export type NoUndefined<T> = T extends undefined ? never : T;
|
||||
export type Whatever = {} | undefined | null;
|
||||
export type LoosePartial<T extends object> = InexactPartial<T> & {
|
||||
[k: string]: unknown;
|
||||
};
|
||||
export type Mask<Keys extends PropertyKey> = { [K in Keys]?: true };
|
||||
export type Writeable<T> = { -readonly [P in keyof T]: T[P] } & {};
|
||||
export type InexactPartial<T> = {
|
||||
[P in keyof T]?: T[P] | undefined;
|
||||
};
|
||||
export type EmptyObject = Record<string, never>;
|
||||
export type BuiltIn =
|
||||
| (((...args: any[]) => any) | (new (...args: any[]) => any))
|
||||
| { readonly [Symbol.toStringTag]: string }
|
||||
| Date
|
||||
| Error
|
||||
| Generator
|
||||
| Promise<unknown>
|
||||
| RegExp;
|
||||
export type MakeReadonly<T> = T extends Map<infer K, infer V>
|
||||
? ReadonlyMap<K, V>
|
||||
: T extends Set<infer V>
|
||||
? ReadonlySet<V>
|
||||
: T extends [infer Head, ...infer Tail]
|
||||
? readonly [Head, ...Tail]
|
||||
: T extends Array<infer V>
|
||||
? ReadonlyArray<V>
|
||||
: T extends BuiltIn
|
||||
? T
|
||||
: Readonly<T>;
|
||||
export type SomeObject = Record<PropertyKey, any>;
|
||||
export type Identity<T> = T;
|
||||
export type Flatten<T> = Identity<{ [k in keyof T]: T[k] }>;
|
||||
export type Mapped<T> = { [k in keyof T]: T[k] };
|
||||
export type Prettify<T> = {
|
||||
// @ts-ignore
|
||||
[K in keyof T]: T[K];
|
||||
} & {};
|
||||
|
||||
export type NoNeverKeys<T> = {
|
||||
[k in keyof T]: [T[k]] extends [never] ? never : k;
|
||||
}[keyof T];
|
||||
export type NoNever<T> = Identity<{
|
||||
[k in NoNeverKeys<T>]: k extends keyof T ? T[k] : never;
|
||||
}>;
|
||||
export type Extend<A extends SomeObject, B extends SomeObject> = Flatten<
|
||||
// fast path when there is no keys overlap
|
||||
keyof A & keyof B extends never
|
||||
? A & B
|
||||
: {
|
||||
[K in keyof A as K extends keyof B ? never : K]: A[K];
|
||||
} & {
|
||||
[K in keyof B]: B[K];
|
||||
}
|
||||
>;
|
||||
|
||||
export type TupleItems = ReadonlyArray<schemas.SomeType>;
|
||||
export type AnyFunc = (...args: any[]) => any;
|
||||
export type IsProp<T, K extends keyof T> = T[K] extends AnyFunc ? never : K;
|
||||
export type MaybeAsync<T> = T | Promise<T>;
|
||||
export type KeyOf<T> = keyof OmitIndexSignature<T>;
|
||||
export type OmitIndexSignature<T> = {
|
||||
[K in keyof T as string extends K ? never : K extends string ? K : never]: T[K];
|
||||
};
|
||||
export type ExtractIndexSignature<T> = {
|
||||
[K in keyof T as string extends K ? K : K extends string ? never : K]: T[K];
|
||||
};
|
||||
export type Keys<T extends object> = keyof OmitIndexSignature<T>;
|
||||
|
||||
export type SchemaClass<T extends schemas.SomeType> = {
|
||||
new (def: T["_zod"]["def"]): T;
|
||||
};
|
||||
export type EnumValue = string | number; // | bigint | boolean | symbol;
|
||||
export type EnumLike = Readonly<Record<string, EnumValue>>;
|
||||
export type ToEnum<T extends EnumValue> = Flatten<{ [k in T]: k }>;
|
||||
export type KeysEnum<T extends object> = ToEnum<Exclude<keyof T, symbol>>;
|
||||
export type KeysArray<T extends object> = Flatten<(keyof T & string)[]>;
|
||||
export type Literal = string | number | bigint | boolean | null | undefined;
|
||||
export type LiteralArray = Array<Literal>;
|
||||
export type Primitive = string | number | symbol | bigint | boolean | null | undefined;
|
||||
export type PrimitiveArray = Array<Primitive>;
|
||||
export type HasSize = { size: number };
|
||||
export type HasLength = { length: number }; // string | Array<unknown> | Set<unknown> | File;
|
||||
export type Numeric = number | bigint | Date;
|
||||
export type SafeParseResult<T> = SafeParseSuccess<T> | SafeParseError<T>;
|
||||
export type SafeParseSuccess<T> = { success: true; data: T; error?: never };
|
||||
export type SafeParseError<T> = {
|
||||
success: false;
|
||||
data?: never;
|
||||
error: errors.$ZodError<T>;
|
||||
};
|
||||
|
||||
export type PropValues = Record<string, Set<Primitive>>;
|
||||
export type PrimitiveSet = Set<Primitive>;
|
||||
|
||||
// functions
|
||||
export function assertEqual<A, B>(val: AssertEqual<A, B>): AssertEqual<A, B> {
|
||||
return val;
|
||||
}
|
||||
|
||||
export function assertNotEqual<A, B>(val: AssertNotEqual<A, B>): AssertNotEqual<A, B> {
|
||||
return val;
|
||||
}
|
||||
|
||||
export function assertIs<T>(_arg: T): void {}
|
||||
|
||||
export function assertNever(_x: never): never {
|
||||
throw new Error("Unexpected value in exhaustive check");
|
||||
}
|
||||
export function assert<T>(_: any): asserts _ is T {}
|
||||
|
||||
export function getEnumValues(entries: EnumLike): EnumValue[] {
|
||||
const numericValues = Object.values(entries).filter((v) => typeof v === "number");
|
||||
const values = Object.entries(entries)
|
||||
.filter(([k, _]) => numericValues.indexOf(+k) === -1)
|
||||
.map(([_, v]) => v);
|
||||
return values;
|
||||
}
|
||||
|
||||
export function joinValues<T extends Primitive[]>(array: T, separator = "|"): string {
|
||||
return array.map((val) => stringifyPrimitive(val)).join(separator);
|
||||
}
|
||||
|
||||
export function jsonStringifyReplacer(_: string, value: any): any {
|
||||
if (typeof value === "bigint") return value.toString();
|
||||
return value;
|
||||
}
|
||||
|
||||
export function cached<T>(getter: () => T): { value: T } {
|
||||
const set = false;
|
||||
return {
|
||||
get value() {
|
||||
if (!set) {
|
||||
const value = getter();
|
||||
Object.defineProperty(this, "value", { value });
|
||||
return value;
|
||||
}
|
||||
throw new Error("cached value already set");
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function nullish(input: any): boolean {
|
||||
return input === null || input === undefined;
|
||||
}
|
||||
|
||||
export function cleanRegex(source: string): string {
|
||||
const start = source.startsWith("^") ? 1 : 0;
|
||||
const end = source.endsWith("$") ? source.length - 1 : source.length;
|
||||
return source.slice(start, end);
|
||||
}
|
||||
|
||||
export function floatSafeRemainder(val: number, step: number): number {
|
||||
const ratio = val / step;
|
||||
const roundedRatio = Math.round(ratio);
|
||||
// Use a relative epsilon scaled to the magnitude of the result
|
||||
const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);
|
||||
if (Math.abs(ratio - roundedRatio) < tolerance) return 0;
|
||||
return ratio - roundedRatio;
|
||||
}
|
||||
|
||||
const EVALUATING = /* @__PURE__*/ Symbol("evaluating");
|
||||
|
||||
export function defineLazy<T, K extends keyof T>(object: T, key: K, getter: () => T[K]): void {
|
||||
let value: T[K] | typeof EVALUATING | undefined = undefined;
|
||||
Object.defineProperty(object, key, {
|
||||
get() {
|
||||
if (value === EVALUATING) {
|
||||
// Circular reference detected, return undefined to break the cycle
|
||||
return undefined as T[K];
|
||||
}
|
||||
if (value === undefined) {
|
||||
value = EVALUATING;
|
||||
value = getter();
|
||||
}
|
||||
return value;
|
||||
},
|
||||
set(v) {
|
||||
Object.defineProperty(object, key, {
|
||||
value: v,
|
||||
// configurable: true,
|
||||
});
|
||||
// object[key] = v;
|
||||
},
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
|
||||
export function objectClone(obj: object) {
|
||||
return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
|
||||
}
|
||||
|
||||
export function assignProp<T extends object, K extends PropertyKey>(
|
||||
target: T,
|
||||
prop: K,
|
||||
value: K extends keyof T ? T[K] : any
|
||||
): void {
|
||||
Object.defineProperty(target, prop, {
|
||||
value,
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
|
||||
export function mergeDefs(...defs: Record<string, any>[]): any {
|
||||
const mergedDescriptors: Record<string, PropertyDescriptor> = {};
|
||||
|
||||
for (const def of defs) {
|
||||
const descriptors = Object.getOwnPropertyDescriptors(def);
|
||||
Object.assign(mergedDescriptors, descriptors);
|
||||
}
|
||||
|
||||
return Object.defineProperties({}, mergedDescriptors);
|
||||
}
|
||||
|
||||
export function cloneDef(schema: schemas.$ZodType): any {
|
||||
return mergeDefs(schema._zod.def);
|
||||
}
|
||||
|
||||
export function getElementAtPath(obj: any, path: (string | number)[] | null | undefined): any {
|
||||
if (!path) return obj;
|
||||
return path.reduce((acc, key) => acc?.[key], obj);
|
||||
}
|
||||
|
||||
export function promiseAllObject<T extends object>(promisesObj: T): Promise<{ [k in keyof T]: Awaited<T[k]> }> {
|
||||
const keys = Object.keys(promisesObj);
|
||||
const promises = keys.map((key) => (promisesObj as any)[key]);
|
||||
|
||||
return Promise.all(promises).then((results) => {
|
||||
const resolvedObj: any = {};
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
resolvedObj[keys[i]!] = results[i];
|
||||
}
|
||||
return resolvedObj;
|
||||
});
|
||||
}
|
||||
|
||||
export function randomString(length = 10): string {
|
||||
const chars = "abcdefghijklmnopqrstuvwxyz";
|
||||
let str = "";
|
||||
for (let i = 0; i < length; i++) {
|
||||
str += chars[Math.floor(Math.random() * chars.length)];
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
export function esc(str: string): string {
|
||||
return JSON.stringify(str);
|
||||
}
|
||||
|
||||
export function slugify(input: string): string {
|
||||
return input
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/[^\w\s-]/g, "")
|
||||
.replace(/[\s_-]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
}
|
||||
|
||||
export const captureStackTrace: (targetObject: object, constructorOpt?: Function) => void = (
|
||||
"captureStackTrace" in Error ? Error.captureStackTrace : (..._args: any[]) => {}
|
||||
) as any;
|
||||
|
||||
export function isObject(data: any): data is Record<PropertyKey, unknown> {
|
||||
return typeof data === "object" && data !== null && !Array.isArray(data);
|
||||
}
|
||||
|
||||
export const allowsEval: { value: boolean } = /* @__PURE__*/ cached(() => {
|
||||
// Skip the probe under `jitless`: strict CSPs report the caught `new Function`
|
||||
// as a `securitypolicyviolation` even though the throw is swallowed.
|
||||
if (globalConfig.jitless) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const F = Function;
|
||||
new F("");
|
||||
return true;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
export function isPlainObject(o: any): o is Record<PropertyKey, unknown> {
|
||||
if (isObject(o) === false) return false;
|
||||
|
||||
// modified constructor
|
||||
const ctor = o.constructor;
|
||||
if (ctor === undefined) return true;
|
||||
|
||||
if (typeof ctor !== "function") return true;
|
||||
|
||||
// modified prototype
|
||||
const prot = ctor.prototype;
|
||||
if (isObject(prot) === false) return false;
|
||||
|
||||
// ctor doesn't have static `isPrototypeOf`
|
||||
if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export function shallowClone(o: any): any {
|
||||
if (isPlainObject(o)) return { ...o };
|
||||
if (Array.isArray(o)) return [...o];
|
||||
if (o instanceof Map) return new Map(o);
|
||||
if (o instanceof Set) return new Set(o);
|
||||
return o;
|
||||
}
|
||||
|
||||
export function numKeys(data: any): number {
|
||||
let keyCount = 0;
|
||||
for (const key in data) {
|
||||
if (Object.prototype.hasOwnProperty.call(data, key)) {
|
||||
keyCount++;
|
||||
}
|
||||
}
|
||||
return keyCount;
|
||||
}
|
||||
|
||||
export const getParsedType = (data: any): ParsedTypes => {
|
||||
const t = typeof data;
|
||||
|
||||
switch (t) {
|
||||
case "undefined":
|
||||
return "undefined";
|
||||
|
||||
case "string":
|
||||
return "string";
|
||||
|
||||
case "number":
|
||||
return Number.isNaN(data) ? "nan" : "number";
|
||||
|
||||
case "boolean":
|
||||
return "boolean";
|
||||
|
||||
case "function":
|
||||
return "function";
|
||||
|
||||
case "bigint":
|
||||
return "bigint";
|
||||
|
||||
case "symbol":
|
||||
return "symbol";
|
||||
|
||||
case "object":
|
||||
if (Array.isArray(data)) {
|
||||
return "array";
|
||||
}
|
||||
if (data === null) {
|
||||
return "null";
|
||||
}
|
||||
if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
|
||||
return "promise";
|
||||
}
|
||||
if (typeof Map !== "undefined" && data instanceof Map) {
|
||||
return "map";
|
||||
}
|
||||
if (typeof Set !== "undefined" && data instanceof Set) {
|
||||
return "set";
|
||||
}
|
||||
if (typeof Date !== "undefined" && data instanceof Date) {
|
||||
return "date";
|
||||
}
|
||||
// @ts-ignore
|
||||
if (typeof File !== "undefined" && data instanceof File) {
|
||||
return "file";
|
||||
}
|
||||
return "object";
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown data type: ${t}`);
|
||||
}
|
||||
};
|
||||
|
||||
export const propertyKeyTypes: Set<string> = /* @__PURE__*/ new Set(["string", "number", "symbol"]);
|
||||
export const primitiveTypes: Set<string> = /* @__PURE__*/ new Set([
|
||||
"string",
|
||||
"number",
|
||||
"bigint",
|
||||
"boolean",
|
||||
"symbol",
|
||||
"undefined",
|
||||
]);
|
||||
export function escapeRegex(str: string): string {
|
||||
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
// zod-specific utils
|
||||
export function clone<T extends schemas.$ZodType>(inst: T, def?: T["_zod"]["def"], params?: { parent: boolean }): T {
|
||||
const cl = new inst._zod.constr(def ?? inst._zod.def);
|
||||
if (!def || params?.parent) cl._zod.parent = inst;
|
||||
return cl as any;
|
||||
}
|
||||
|
||||
export type EmptyToNever<T> = keyof T extends never ? never : T;
|
||||
|
||||
export type Normalize<T> = T extends undefined
|
||||
? never
|
||||
: T extends Record<any, any>
|
||||
? Flatten<
|
||||
{
|
||||
[k in keyof Omit<T, "error" | "message">]: T[k];
|
||||
} & ("error" extends keyof T
|
||||
? {
|
||||
error?: Exclude<T["error"], string>;
|
||||
// path?: PropertyKey[] | undefined;
|
||||
// message?: string | undefined;
|
||||
}
|
||||
: unknown)
|
||||
>
|
||||
: never;
|
||||
|
||||
export function normalizeParams<T>(_params: T): Normalize<T> {
|
||||
const params: any = _params;
|
||||
|
||||
if (!params) return {} as any;
|
||||
if (typeof params === "string") return { error: () => params } as any;
|
||||
if (params?.message !== undefined) {
|
||||
if (params?.error !== undefined) throw new Error("Cannot specify both `message` and `error` params");
|
||||
params.error = params.message;
|
||||
}
|
||||
delete params.message;
|
||||
if (typeof params.error === "string") return { ...params, error: () => params.error } as any;
|
||||
return params;
|
||||
}
|
||||
|
||||
export function createTransparentProxy<T extends object>(getter: () => T): T {
|
||||
let target: T;
|
||||
return new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_, prop, receiver) {
|
||||
target ??= getter();
|
||||
return Reflect.get(target, prop, receiver);
|
||||
},
|
||||
set(_, prop, value, receiver) {
|
||||
target ??= getter();
|
||||
return Reflect.set(target, prop, value, receiver);
|
||||
},
|
||||
has(_, prop) {
|
||||
target ??= getter();
|
||||
return Reflect.has(target, prop);
|
||||
},
|
||||
deleteProperty(_, prop) {
|
||||
target ??= getter();
|
||||
return Reflect.deleteProperty(target, prop);
|
||||
},
|
||||
ownKeys(_) {
|
||||
target ??= getter();
|
||||
return Reflect.ownKeys(target);
|
||||
},
|
||||
getOwnPropertyDescriptor(_, prop) {
|
||||
target ??= getter();
|
||||
return Reflect.getOwnPropertyDescriptor(target, prop);
|
||||
},
|
||||
defineProperty(_, prop, descriptor) {
|
||||
target ??= getter();
|
||||
return Reflect.defineProperty(target, prop, descriptor);
|
||||
},
|
||||
}
|
||||
) as T;
|
||||
}
|
||||
|
||||
export function stringifyPrimitive(value: any): string {
|
||||
if (typeof value === "bigint") return value.toString() + "n";
|
||||
if (typeof value === "string") return `"${value}"`;
|
||||
return `${value}`;
|
||||
}
|
||||
|
||||
export function optionalKeys(shape: schemas.$ZodShape): string[] {
|
||||
return Object.keys(shape).filter((k) => {
|
||||
return shape[k]!._zod.optin === "optional" && shape[k]!._zod.optout === "optional";
|
||||
});
|
||||
}
|
||||
|
||||
export type CleanKey<T extends PropertyKey> = T extends `?${infer K}` ? K : T extends `${infer K}?` ? K : T;
|
||||
export type ToCleanMap<T extends schemas.$ZodLooseShape> = {
|
||||
[k in keyof T]: k extends `?${infer K}` ? K : k extends `${infer K}?` ? K : k;
|
||||
};
|
||||
export type FromCleanMap<T extends schemas.$ZodLooseShape> = {
|
||||
[k in keyof T as k extends `?${infer K}` ? K : k extends `${infer K}?` ? K : k]: k;
|
||||
};
|
||||
|
||||
export const NUMBER_FORMAT_RANGES: Record<checks.$ZodNumberFormats, [number, number]> = {
|
||||
safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
|
||||
int32: [-2147483648, 2147483647],
|
||||
uint32: [0, 4294967295],
|
||||
float32: [-3.4028234663852886e38, 3.4028234663852886e38],
|
||||
float64: [-Number.MAX_VALUE, Number.MAX_VALUE],
|
||||
};
|
||||
|
||||
export const BIGINT_FORMAT_RANGES: Record<checks.$ZodBigIntFormats, [bigint, bigint]> = {
|
||||
int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")],
|
||||
uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")],
|
||||
};
|
||||
|
||||
export function pick(schema: schemas.$ZodObject, mask: Record<string, unknown>): any {
|
||||
const currDef = schema._zod.def;
|
||||
|
||||
const checks = currDef.checks;
|
||||
const hasChecks = checks && checks.length > 0;
|
||||
if (hasChecks) {
|
||||
throw new Error(".pick() cannot be used on object schemas containing refinements");
|
||||
}
|
||||
|
||||
const def = mergeDefs(schema._zod.def, {
|
||||
get shape() {
|
||||
const newShape: Writeable<schemas.$ZodShape> = {};
|
||||
for (const key in mask) {
|
||||
if (!(key in currDef.shape)) {
|
||||
throw new Error(`Unrecognized key: "${key}"`);
|
||||
}
|
||||
if (!mask[key]) continue;
|
||||
newShape[key] = currDef.shape[key]!;
|
||||
}
|
||||
|
||||
assignProp(this, "shape", newShape); // self-caching
|
||||
return newShape;
|
||||
},
|
||||
checks: [],
|
||||
});
|
||||
|
||||
return clone(schema, def) as any;
|
||||
}
|
||||
|
||||
export function omit(schema: schemas.$ZodObject, mask: object): any {
|
||||
const currDef = schema._zod.def;
|
||||
|
||||
const checks = currDef.checks;
|
||||
const hasChecks = checks && checks.length > 0;
|
||||
if (hasChecks) {
|
||||
throw new Error(".omit() cannot be used on object schemas containing refinements");
|
||||
}
|
||||
|
||||
const def = mergeDefs(schema._zod.def, {
|
||||
get shape() {
|
||||
const newShape: Writeable<schemas.$ZodShape> = { ...schema._zod.def.shape };
|
||||
for (const key in mask) {
|
||||
if (!(key in currDef.shape)) {
|
||||
throw new Error(`Unrecognized key: "${key}"`);
|
||||
}
|
||||
if (!(mask as any)[key]) continue;
|
||||
|
||||
delete newShape[key];
|
||||
}
|
||||
assignProp(this, "shape", newShape); // self-caching
|
||||
return newShape;
|
||||
},
|
||||
checks: [],
|
||||
});
|
||||
|
||||
return clone(schema, def);
|
||||
}
|
||||
|
||||
export function extend(schema: schemas.$ZodObject, shape: schemas.$ZodShape): any {
|
||||
if (!isPlainObject(shape)) {
|
||||
throw new Error("Invalid input to extend: expected a plain object");
|
||||
}
|
||||
|
||||
const checks = schema._zod.def.checks;
|
||||
const hasChecks = checks && checks.length > 0;
|
||||
if (hasChecks) {
|
||||
// Only throw if new shape overlaps with existing shape
|
||||
// Use getOwnPropertyDescriptor to check key existence without accessing values
|
||||
const existingShape = schema._zod.def.shape;
|
||||
for (const key in shape) {
|
||||
if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {
|
||||
throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const def = mergeDefs(schema._zod.def, {
|
||||
get shape() {
|
||||
const _shape = { ...schema._zod.def.shape, ...shape };
|
||||
assignProp(this, "shape", _shape); // self-caching
|
||||
return _shape;
|
||||
},
|
||||
});
|
||||
return clone(schema, def) as any;
|
||||
}
|
||||
|
||||
export function safeExtend(schema: schemas.$ZodObject, shape: schemas.$ZodShape): any {
|
||||
if (!isPlainObject(shape)) {
|
||||
throw new Error("Invalid input to safeExtend: expected a plain object");
|
||||
}
|
||||
const def = mergeDefs(schema._zod.def, {
|
||||
get shape() {
|
||||
const _shape = { ...schema._zod.def.shape, ...shape };
|
||||
assignProp(this, "shape", _shape); // self-caching
|
||||
return _shape;
|
||||
},
|
||||
});
|
||||
return clone(schema, def) as any;
|
||||
}
|
||||
|
||||
export function merge(a: schemas.$ZodObject, b: schemas.$ZodObject): any {
|
||||
if (a._zod.def.checks?.length) {
|
||||
throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
|
||||
}
|
||||
const def = mergeDefs(a._zod.def, {
|
||||
get shape() {
|
||||
const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
|
||||
assignProp(this, "shape", _shape); // self-caching
|
||||
return _shape;
|
||||
},
|
||||
get catchall() {
|
||||
return b._zod.def.catchall;
|
||||
},
|
||||
checks: b._zod.def.checks ?? [],
|
||||
});
|
||||
|
||||
return clone(a, def) as any;
|
||||
}
|
||||
|
||||
export function partial(
|
||||
Class: SchemaClass<schemas.$ZodOptional> | null,
|
||||
schema: schemas.$ZodObject,
|
||||
mask: object | undefined
|
||||
): any {
|
||||
const currDef = schema._zod.def;
|
||||
const checks = currDef.checks;
|
||||
const hasChecks = checks && checks.length > 0;
|
||||
if (hasChecks) {
|
||||
throw new Error(".partial() cannot be used on object schemas containing refinements");
|
||||
}
|
||||
|
||||
const def = mergeDefs(schema._zod.def, {
|
||||
get shape() {
|
||||
const oldShape = schema._zod.def.shape;
|
||||
const shape: Writeable<schemas.$ZodShape> = { ...oldShape };
|
||||
|
||||
if (mask) {
|
||||
for (const key in mask) {
|
||||
if (!(key in oldShape)) {
|
||||
throw new Error(`Unrecognized key: "${key}"`);
|
||||
}
|
||||
if (!(mask as any)[key]) continue;
|
||||
// if (oldShape[key]!._zod.optin === "optional") continue;
|
||||
shape[key] = Class
|
||||
? new Class({
|
||||
type: "optional",
|
||||
innerType: oldShape[key]!,
|
||||
})
|
||||
: oldShape[key]!;
|
||||
}
|
||||
} else {
|
||||
for (const key in oldShape) {
|
||||
// if (oldShape[key]!._zod.optin === "optional") continue;
|
||||
shape[key] = Class
|
||||
? new Class({
|
||||
type: "optional",
|
||||
innerType: oldShape[key]!,
|
||||
})
|
||||
: oldShape[key]!;
|
||||
}
|
||||
}
|
||||
|
||||
assignProp(this, "shape", shape); // self-caching
|
||||
return shape;
|
||||
},
|
||||
checks: [],
|
||||
});
|
||||
|
||||
return clone(schema, def) as any;
|
||||
}
|
||||
|
||||
export function required(
|
||||
Class: SchemaClass<schemas.$ZodNonOptional>,
|
||||
schema: schemas.$ZodObject,
|
||||
mask: object | undefined
|
||||
): any {
|
||||
const def = mergeDefs(schema._zod.def, {
|
||||
get shape() {
|
||||
const oldShape = schema._zod.def.shape;
|
||||
const shape: Writeable<schemas.$ZodShape> = { ...oldShape };
|
||||
|
||||
if (mask) {
|
||||
for (const key in mask) {
|
||||
if (!(key in shape)) {
|
||||
throw new Error(`Unrecognized key: "${key}"`);
|
||||
}
|
||||
if (!(mask as any)[key]) continue;
|
||||
// overwrite with non-optional
|
||||
shape[key] = new Class({
|
||||
type: "nonoptional",
|
||||
innerType: oldShape[key]!,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
for (const key in oldShape) {
|
||||
// overwrite with non-optional
|
||||
shape[key] = new Class({
|
||||
type: "nonoptional",
|
||||
innerType: oldShape[key]!,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
assignProp(this, "shape", shape); // self-caching
|
||||
return shape;
|
||||
},
|
||||
});
|
||||
|
||||
return clone(schema, def) as any;
|
||||
}
|
||||
|
||||
export type Constructor<T, Def extends any[] = any[]> = new (...args: Def) => T;
|
||||
|
||||
// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom
|
||||
export function aborted(x: schemas.ParsePayload, startIndex = 0): boolean {
|
||||
if (x.aborted === true) return true;
|
||||
for (let i = startIndex; i < x.issues.length; i++) {
|
||||
if (x.issues[i]?.continue !== true) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined).
|
||||
// Used to respect `abort: true` in .refine() even for checks that have a `when` function.
|
||||
export function explicitlyAborted(x: schemas.ParsePayload, startIndex = 0): boolean {
|
||||
if (x.aborted === true) return true;
|
||||
for (let i = startIndex; i < x.issues.length; i++) {
|
||||
if (x.issues[i]?.continue === false) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function prefixIssues(path: PropertyKey, issues: errors.$ZodRawIssue[]): errors.$ZodRawIssue[] {
|
||||
return issues.map((iss) => {
|
||||
(iss as any).path ??= [];
|
||||
(iss as any).path.unshift(path);
|
||||
return iss;
|
||||
});
|
||||
}
|
||||
|
||||
export function unwrapMessage(message: string | { message: string } | undefined | null): string | undefined {
|
||||
return typeof message === "string" ? message : message?.message;
|
||||
}
|
||||
|
||||
export function finalizeIssue(
|
||||
iss: errors.$ZodRawIssue,
|
||||
ctx: schemas.ParseContextInternal | undefined,
|
||||
config: $ZodConfig
|
||||
): errors.$ZodIssue {
|
||||
const message = iss.message
|
||||
? iss.message
|
||||
: (unwrapMessage(iss.inst?._zod.def?.error?.(iss as never)) ??
|
||||
unwrapMessage(ctx?.error?.(iss as never)) ??
|
||||
unwrapMessage(config.customError?.(iss)) ??
|
||||
unwrapMessage(config.localeError?.(iss)) ??
|
||||
"Invalid input");
|
||||
|
||||
const { inst: _inst, continue: _continue, input: _input, ...rest } = iss as any;
|
||||
rest.path ??= [];
|
||||
rest.message = message;
|
||||
if (ctx?.reportInput) {
|
||||
rest.input = _input;
|
||||
}
|
||||
return rest;
|
||||
}
|
||||
|
||||
export function getSizableOrigin(input: any): "set" | "map" | "file" | "unknown" {
|
||||
if (input instanceof Set) return "set";
|
||||
if (input instanceof Map) return "map";
|
||||
// @ts-ignore
|
||||
if (input instanceof File) return "file";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export function getLengthableOrigin(input: any): "array" | "string" | "unknown" {
|
||||
if (Array.isArray(input)) return "array";
|
||||
if (typeof input === "string") return "string";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export function parsedType(data: unknown): errors.$ZodInvalidTypeExpected {
|
||||
const t = typeof data;
|
||||
switch (t) {
|
||||
case "number": {
|
||||
return Number.isNaN(data) ? "nan" : "number";
|
||||
}
|
||||
case "object": {
|
||||
if (data === null) {
|
||||
return "null";
|
||||
}
|
||||
if (Array.isArray(data)) {
|
||||
return "array";
|
||||
}
|
||||
|
||||
const obj = data as object;
|
||||
if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) {
|
||||
return (obj.constructor as { name: string }).name;
|
||||
}
|
||||
}
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
////////// REFINES //////////
|
||||
export function issue(_iss: string, input: any, inst: any): errors.$ZodRawIssue;
|
||||
export function issue(_iss: errors.$ZodRawIssue): errors.$ZodRawIssue;
|
||||
export function issue(...args: [string | errors.$ZodRawIssue, any?, any?]): errors.$ZodRawIssue {
|
||||
const [iss, input, inst] = args;
|
||||
if (typeof iss === "string") {
|
||||
return {
|
||||
message: iss,
|
||||
code: "custom",
|
||||
input,
|
||||
inst,
|
||||
};
|
||||
}
|
||||
|
||||
return { ...iss };
|
||||
}
|
||||
|
||||
export function cleanEnum(obj: Record<string, EnumValue>): EnumValue[] {
|
||||
return Object.entries(obj)
|
||||
.filter(([k, _]) => {
|
||||
// return true if NaN, meaning it's not a number, thus a string key
|
||||
return Number.isNaN(Number.parseInt(k, 10));
|
||||
})
|
||||
.map((el) => el[1]);
|
||||
}
|
||||
|
||||
// Codec utility functions
|
||||
export function base64ToUint8Array(base64: string): InstanceType<typeof Uint8Array> {
|
||||
const binaryString = atob(base64);
|
||||
const bytes = new Uint8Array(binaryString.length);
|
||||
for (let i = 0; i < binaryString.length; i++) {
|
||||
bytes[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
export function uint8ArrayToBase64(bytes: Uint8Array): string {
|
||||
let binaryString = "";
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
binaryString += String.fromCharCode(bytes[i]);
|
||||
}
|
||||
return btoa(binaryString);
|
||||
}
|
||||
|
||||
export function base64urlToUint8Array(base64url: string): InstanceType<typeof Uint8Array> {
|
||||
const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/");
|
||||
const padding = "=".repeat((4 - (base64.length % 4)) % 4);
|
||||
return base64ToUint8Array(base64 + padding);
|
||||
}
|
||||
|
||||
export function uint8ArrayToBase64url(bytes: Uint8Array): string {
|
||||
return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
||||
}
|
||||
|
||||
export function hexToUint8Array(hex: string): InstanceType<typeof Uint8Array> {
|
||||
const cleanHex = hex.replace(/^0x/, "");
|
||||
if (cleanHex.length % 2 !== 0) {
|
||||
throw new Error("Invalid hex string length");
|
||||
}
|
||||
const bytes = new Uint8Array(cleanHex.length / 2);
|
||||
for (let i = 0; i < cleanHex.length; i += 2) {
|
||||
bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
export function uint8ArrayToHex(bytes: Uint8Array): string {
|
||||
return Array.from(bytes)
|
||||
.map((b) => b.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
}
|
||||
|
||||
// instanceof
|
||||
export abstract class Class {
|
||||
constructor(..._args: any[]) {}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* @fileoverview enforce a maximum file length
|
||||
* @author Alberto Rodríguez
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Creates an array of numbers from `start` up to, but not including, `end`
|
||||
* @param {number} start The start of the range
|
||||
* @param {number} end The end of the range
|
||||
* @returns {number[]} The range of numbers
|
||||
*/
|
||||
function range(start, end) {
|
||||
return [...Array(end - start).keys()].map(x => x + start);
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "suggestion",
|
||||
|
||||
docs: {
|
||||
description: "Enforce a maximum number of lines per file",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/latest/rules/max-lines",
|
||||
},
|
||||
|
||||
schema: [
|
||||
{
|
||||
oneOf: [
|
||||
{
|
||||
type: "integer",
|
||||
minimum: 0,
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
max: {
|
||||
type: "integer",
|
||||
minimum: 0,
|
||||
},
|
||||
skipComments: {
|
||||
type: "boolean",
|
||||
},
|
||||
skipBlankLines: {
|
||||
type: "boolean",
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
defaultOptions: [300],
|
||||
|
||||
messages: {
|
||||
exceed: "File has too many lines ({{actual}}). Maximum allowed is {{max}}.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const option = context.options[0];
|
||||
let max = 300;
|
||||
|
||||
if (typeof option === "object" && Object.hasOwn(option, "max")) {
|
||||
max = option.max;
|
||||
} else if (typeof option === "number") {
|
||||
max = option;
|
||||
}
|
||||
|
||||
const skipComments = option && option.skipComments;
|
||||
const skipBlankLines = option && option.skipBlankLines;
|
||||
|
||||
const sourceCode = context.sourceCode;
|
||||
|
||||
/**
|
||||
* Returns whether or not a token is a comment node type
|
||||
* @param {Token} token The token to check
|
||||
* @returns {boolean} True if the token is a comment node
|
||||
*/
|
||||
function isCommentNodeType(token) {
|
||||
return token && (token.type === "Block" || token.type === "Line");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the line numbers of a comment that don't have any code on the same line
|
||||
* @param {Node} comment The comment node to check
|
||||
* @returns {number[]} The line numbers
|
||||
*/
|
||||
function getLinesWithoutCode(comment) {
|
||||
let start = comment.loc.start.line;
|
||||
let end = comment.loc.end.line;
|
||||
|
||||
let token;
|
||||
|
||||
token = comment;
|
||||
do {
|
||||
token = sourceCode.getTokenBefore(token, {
|
||||
includeComments: true,
|
||||
});
|
||||
} while (isCommentNodeType(token));
|
||||
|
||||
if (token && astUtils.isTokenOnSameLine(token, comment)) {
|
||||
start += 1;
|
||||
}
|
||||
|
||||
token = comment;
|
||||
do {
|
||||
token = sourceCode.getTokenAfter(token, {
|
||||
includeComments: true,
|
||||
});
|
||||
} while (isCommentNodeType(token));
|
||||
|
||||
if (token && astUtils.isTokenOnSameLine(comment, token)) {
|
||||
end -= 1;
|
||||
}
|
||||
|
||||
if (start <= end) {
|
||||
return range(start, end + 1);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
return {
|
||||
"Program:exit"() {
|
||||
let lines = sourceCode.lines.map((text, i) => ({
|
||||
lineNumber: i + 1,
|
||||
text,
|
||||
}));
|
||||
|
||||
/*
|
||||
* If file ends with a linebreak, `sourceCode.lines` will have one extra empty line at the end.
|
||||
* That isn't a real line, so we shouldn't count it.
|
||||
*/
|
||||
if (lines.length > 1 && lines.at(-1).text === "") {
|
||||
lines.pop();
|
||||
}
|
||||
|
||||
if (skipBlankLines) {
|
||||
lines = lines.filter(l => l.text.trim() !== "");
|
||||
}
|
||||
|
||||
if (skipComments) {
|
||||
const comments = sourceCode.getAllComments();
|
||||
|
||||
const commentLines = new Set(
|
||||
comments.flatMap(getLinesWithoutCode),
|
||||
);
|
||||
|
||||
lines = lines.filter(l => !commentLines.has(l.lineNumber));
|
||||
}
|
||||
|
||||
if (lines.length > max) {
|
||||
const loc = {
|
||||
start: {
|
||||
line: lines[max].lineNumber,
|
||||
column: 0,
|
||||
},
|
||||
end: {
|
||||
line: sourceCode.lines.length,
|
||||
column: sourceCode.lines.at(-1).length,
|
||||
},
|
||||
};
|
||||
|
||||
context.report({
|
||||
loc,
|
||||
messageId: "exceed",
|
||||
data: {
|
||||
max,
|
||||
actual: lines.length,
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"for + if": {
|
||||
"name": "for + if",
|
||||
"browser": "IE 11.0.0 (Windows 7 0.0.0)",
|
||||
"suite": "itar-long",
|
||||
"hz": 23299.253985498104,
|
||||
"success": true,
|
||||
"fastest": false,
|
||||
"rme": 0.012604441829821445,
|
||||
"rhz": 0.7612665520486154,
|
||||
"sampleSize": 213
|
||||
},
|
||||
"while + if": {
|
||||
"name": "while + if",
|
||||
"browser": "IE 11.0.0 (Windows 7 0.0.0)",
|
||||
"suite": "itar-long",
|
||||
"hz": 21471.605639232734,
|
||||
"success": true,
|
||||
"fastest": false,
|
||||
"rme": 0.016078837449727854,
|
||||
"rhz": 0.7015510111225076,
|
||||
"sampleSize": 211
|
||||
},
|
||||
"array join": {
|
||||
"name": "array join",
|
||||
"browser": "IE 11.0.0 (Windows 7 0.0.0)",
|
||||
"suite": "itar-long",
|
||||
"hz": 30605.907908075522,
|
||||
"success": true,
|
||||
"fastest": true,
|
||||
"rme": 0.01788399233872233,
|
||||
"rhz": 1,
|
||||
"sampleSize": 215
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
/**
|
||||
* Check whether a given character is an emoji modifier.
|
||||
* @param {number} code The character code to check.
|
||||
* @returns {boolean} `true` if the character is an emoji modifier.
|
||||
*/
|
||||
module.exports = function isEmojiModifier(code) {
|
||||
return code >= 0x1f3fb && code <= 0x1f3ff;
|
||||
};
|
||||
@@ -0,0 +1,276 @@
|
||||
/*! *****************************************************************************
|
||||
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,
|
||||
MERCHANTABLITY OR NON-INFRINGEMENT.
|
||||
|
||||
See the Apache Version 2.0 License for specific language governing permissions
|
||||
and limitations under the License.
|
||||
***************************************************************************** */
|
||||
|
||||
|
||||
/// <reference no-default-lib="true"/>
|
||||
|
||||
/////////////////////////////
|
||||
/// Worker Iterable APIs
|
||||
/////////////////////////////
|
||||
|
||||
interface AbortSignal {
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) */
|
||||
any(signals: Iterable<AbortSignal>): AbortSignal;
|
||||
}
|
||||
|
||||
interface CSSNumericArray {
|
||||
[Symbol.iterator](): IterableIterator<CSSNumericValue>;
|
||||
entries(): IterableIterator<[number, CSSNumericValue]>;
|
||||
keys(): IterableIterator<number>;
|
||||
values(): IterableIterator<CSSNumericValue>;
|
||||
}
|
||||
|
||||
interface CSSTransformValue {
|
||||
[Symbol.iterator](): IterableIterator<CSSTransformComponent>;
|
||||
entries(): IterableIterator<[number, CSSTransformComponent]>;
|
||||
keys(): IterableIterator<number>;
|
||||
values(): IterableIterator<CSSTransformComponent>;
|
||||
}
|
||||
|
||||
interface CSSUnparsedValue {
|
||||
[Symbol.iterator](): IterableIterator<CSSUnparsedSegment>;
|
||||
entries(): IterableIterator<[number, CSSUnparsedSegment]>;
|
||||
keys(): IterableIterator<number>;
|
||||
values(): IterableIterator<CSSUnparsedSegment>;
|
||||
}
|
||||
|
||||
interface Cache {
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Cache/addAll) */
|
||||
addAll(requests: Iterable<RequestInfo>): Promise<void>;
|
||||
}
|
||||
|
||||
interface CanvasPath {
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/roundRect) */
|
||||
roundRect(x: number, y: number, w: number, h: number, radii?: number | DOMPointInit | Iterable<number | DOMPointInit>): void;
|
||||
}
|
||||
|
||||
interface CanvasPathDrawingStyles {
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash) */
|
||||
setLineDash(segments: Iterable<number>): void;
|
||||
}
|
||||
|
||||
interface DOMStringList {
|
||||
[Symbol.iterator](): IterableIterator<string>;
|
||||
}
|
||||
|
||||
interface FileList {
|
||||
[Symbol.iterator](): IterableIterator<File>;
|
||||
}
|
||||
|
||||
interface FontFaceSet extends Set<FontFace> {
|
||||
}
|
||||
|
||||
interface FormData {
|
||||
[Symbol.iterator](): IterableIterator<[string, FormDataEntryValue]>;
|
||||
/** Returns an array of key, value pairs for every entry in the list. */
|
||||
entries(): IterableIterator<[string, FormDataEntryValue]>;
|
||||
/** Returns a list of keys in the list. */
|
||||
keys(): IterableIterator<string>;
|
||||
/** Returns a list of values in the list. */
|
||||
values(): IterableIterator<FormDataEntryValue>;
|
||||
}
|
||||
|
||||
interface Headers {
|
||||
[Symbol.iterator](): IterableIterator<[string, string]>;
|
||||
/** Returns an iterator allowing to go through all key/value pairs contained in this object. */
|
||||
entries(): IterableIterator<[string, string]>;
|
||||
/** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */
|
||||
keys(): IterableIterator<string>;
|
||||
/** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */
|
||||
values(): IterableIterator<string>;
|
||||
}
|
||||
|
||||
interface IDBDatabase {
|
||||
/**
|
||||
* Returns a new transaction with the given mode ("readonly" or "readwrite") and scope which can be a single object store name or an array of names.
|
||||
*
|
||||
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBDatabase/transaction)
|
||||
*/
|
||||
transaction(storeNames: string | Iterable<string>, mode?: IDBTransactionMode, options?: IDBTransactionOptions): IDBTransaction;
|
||||
}
|
||||
|
||||
interface IDBObjectStore {
|
||||
/**
|
||||
* Creates a new index in store with the given name, keyPath and options and returns a new IDBIndex. If the keyPath and options define constraints that cannot be satisfied with the data already in store the upgrade transaction will abort with a "ConstraintError" DOMException.
|
||||
*
|
||||
* Throws an "InvalidStateError" DOMException if not called within an upgrade transaction.
|
||||
*
|
||||
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBObjectStore/createIndex)
|
||||
*/
|
||||
createIndex(name: string, keyPath: string | Iterable<string>, options?: IDBIndexParameters): IDBIndex;
|
||||
}
|
||||
|
||||
interface MessageEvent<T = any> {
|
||||
/**
|
||||
* @deprecated
|
||||
*
|
||||
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/initMessageEvent)
|
||||
*/
|
||||
initMessageEvent(type: string, bubbles?: boolean, cancelable?: boolean, data?: any, origin?: string, lastEventId?: string, source?: MessageEventSource | null, ports?: Iterable<MessagePort>): void;
|
||||
}
|
||||
|
||||
interface StylePropertyMapReadOnly {
|
||||
[Symbol.iterator](): IterableIterator<[string, Iterable<CSSStyleValue>]>;
|
||||
entries(): IterableIterator<[string, Iterable<CSSStyleValue>]>;
|
||||
keys(): IterableIterator<string>;
|
||||
values(): IterableIterator<Iterable<CSSStyleValue>>;
|
||||
}
|
||||
|
||||
interface SubtleCrypto {
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */
|
||||
deriveKey(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | HkdfParams | Pbkdf2Params, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKey>;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */
|
||||
generateKey(algorithm: "Ed25519", extractable: boolean, keyUsages: ReadonlyArray<"sign" | "verify">): Promise<CryptoKeyPair>;
|
||||
generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: ReadonlyArray<KeyUsage>): Promise<CryptoKeyPair>;
|
||||
generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: ReadonlyArray<KeyUsage>): Promise<CryptoKey>;
|
||||
generateKey(algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKeyPair | CryptoKey>;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */
|
||||
importKey(format: "jwk", keyData: JsonWebKey, algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: ReadonlyArray<KeyUsage>): Promise<CryptoKey>;
|
||||
importKey(format: Exclude<KeyFormat, "jwk">, keyData: BufferSource, algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKey>;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */
|
||||
unwrapKey(format: KeyFormat, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, unwrappedKeyAlgorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKey>;
|
||||
}
|
||||
|
||||
interface URLSearchParams {
|
||||
[Symbol.iterator](): IterableIterator<[string, string]>;
|
||||
/** Returns an array of key, value pairs for every entry in the search params. */
|
||||
entries(): IterableIterator<[string, string]>;
|
||||
/** Returns a list of keys in the search params. */
|
||||
keys(): IterableIterator<string>;
|
||||
/** Returns a list of values in the search params. */
|
||||
values(): IterableIterator<string>;
|
||||
}
|
||||
|
||||
interface WEBGL_draw_buffers {
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WEBGL_draw_buffers/drawBuffersWEBGL) */
|
||||
drawBuffersWEBGL(buffers: Iterable<GLenum>): void;
|
||||
}
|
||||
|
||||
interface WEBGL_multi_draw {
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WEBGL_multi_draw/multiDrawArraysInstancedWEBGL) */
|
||||
multiDrawArraysInstancedWEBGL(mode: GLenum, firstsList: Int32Array | Iterable<GLint>, firstsOffset: number, countsList: Int32Array | Iterable<GLsizei>, countsOffset: number, instanceCountsList: Int32Array | Iterable<GLsizei>, instanceCountsOffset: number, drawcount: GLsizei): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WEBGL_multi_draw/multiDrawArraysWEBGL) */
|
||||
multiDrawArraysWEBGL(mode: GLenum, firstsList: Int32Array | Iterable<GLint>, firstsOffset: number, countsList: Int32Array | Iterable<GLsizei>, countsOffset: number, drawcount: GLsizei): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WEBGL_multi_draw/multiDrawElementsInstancedWEBGL) */
|
||||
multiDrawElementsInstancedWEBGL(mode: GLenum, countsList: Int32Array | Iterable<GLsizei>, countsOffset: number, type: GLenum, offsetsList: Int32Array | Iterable<GLsizei>, offsetsOffset: number, instanceCountsList: Int32Array | Iterable<GLsizei>, instanceCountsOffset: number, drawcount: GLsizei): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WEBGL_multi_draw/multiDrawElementsWEBGL) */
|
||||
multiDrawElementsWEBGL(mode: GLenum, countsList: Int32Array | Iterable<GLsizei>, countsOffset: number, type: GLenum, offsetsList: Int32Array | Iterable<GLsizei>, offsetsOffset: number, drawcount: GLsizei): void;
|
||||
}
|
||||
|
||||
interface WebGL2RenderingContextBase {
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/clearBuffer) */
|
||||
clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLfloat>, srcOffset?: number): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/clearBuffer) */
|
||||
clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLint>, srcOffset?: number): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/clearBuffer) */
|
||||
clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLuint>, srcOffset?: number): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/drawBuffers) */
|
||||
drawBuffers(buffers: Iterable<GLenum>): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/getActiveUniforms) */
|
||||
getActiveUniforms(program: WebGLProgram, uniformIndices: Iterable<GLuint>, pname: GLenum): any;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/getUniformIndices) */
|
||||
getUniformIndices(program: WebGLProgram, uniformNames: Iterable<string>): Iterable<GLuint> | null;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/invalidateFramebuffer) */
|
||||
invalidateFramebuffer(target: GLenum, attachments: Iterable<GLenum>): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/invalidateSubFramebuffer) */
|
||||
invalidateSubFramebuffer(target: GLenum, attachments: Iterable<GLenum>, x: GLint, y: GLint, width: GLsizei, height: GLsizei): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/transformFeedbackVaryings) */
|
||||
transformFeedbackVaryings(program: WebGLProgram, varyings: Iterable<string>, bufferMode: GLenum): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniform) */
|
||||
uniform1uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniform) */
|
||||
uniform2uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniform) */
|
||||
uniform3uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniform) */
|
||||
uniform4uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniformMatrix) */
|
||||
uniformMatrix2x3fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniformMatrix) */
|
||||
uniformMatrix2x4fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniformMatrix) */
|
||||
uniformMatrix3x2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniformMatrix) */
|
||||
uniformMatrix3x4fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniformMatrix) */
|
||||
uniformMatrix4x2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniformMatrix) */
|
||||
uniformMatrix4x3fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/vertexAttribI) */
|
||||
vertexAttribI4iv(index: GLuint, values: Iterable<GLint>): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/vertexAttribI) */
|
||||
vertexAttribI4uiv(index: GLuint, values: Iterable<GLuint>): void;
|
||||
}
|
||||
|
||||
interface WebGL2RenderingContextOverloads {
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
|
||||
uniform1fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
|
||||
uniform1iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
|
||||
uniform2fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
|
||||
uniform2iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
|
||||
uniform3fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
|
||||
uniform3iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
|
||||
uniform4fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
|
||||
uniform4iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniformMatrix) */
|
||||
uniformMatrix2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniformMatrix) */
|
||||
uniformMatrix3fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniformMatrix) */
|
||||
uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
|
||||
}
|
||||
|
||||
interface WebGLRenderingContextBase {
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/vertexAttrib) */
|
||||
vertexAttrib1fv(index: GLuint, values: Iterable<GLfloat>): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/vertexAttrib) */
|
||||
vertexAttrib2fv(index: GLuint, values: Iterable<GLfloat>): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/vertexAttrib) */
|
||||
vertexAttrib3fv(index: GLuint, values: Iterable<GLfloat>): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/vertexAttrib) */
|
||||
vertexAttrib4fv(index: GLuint, values: Iterable<GLfloat>): void;
|
||||
}
|
||||
|
||||
interface WebGLRenderingContextOverloads {
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
|
||||
uniform1fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
|
||||
uniform1iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
|
||||
uniform2fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
|
||||
uniform2iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
|
||||
uniform3fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
|
||||
uniform3iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
|
||||
uniform4fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
|
||||
uniform4iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniformMatrix) */
|
||||
uniformMatrix2fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Iterable<GLfloat>): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniformMatrix) */
|
||||
uniformMatrix3fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Iterable<GLfloat>): void;
|
||||
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniformMatrix) */
|
||||
uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Iterable<GLfloat>): void;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { _ as default } from "../esm/_call_super.js";
|
||||
@@ -0,0 +1,238 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.doesImmediatelyReturnFunctionExpression = doesImmediatelyReturnFunctionExpression;
|
||||
exports.isTypedFunctionExpression = isTypedFunctionExpression;
|
||||
exports.isValidFunctionExpressionReturnType = isValidFunctionExpressionReturnType;
|
||||
exports.checkFunctionReturnType = checkFunctionReturnType;
|
||||
exports.checkFunctionExpressionReturnType = checkFunctionExpressionReturnType;
|
||||
exports.ancestorHasReturnType = ancestorHasReturnType;
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
const astUtils_1 = require("./astUtils");
|
||||
const getFunctionHeadLoc_1 = require("./getFunctionHeadLoc");
|
||||
/**
|
||||
* Checks if a node is a variable declarator with a type annotation.
|
||||
* ```
|
||||
* const x: Foo = ...
|
||||
* ```
|
||||
*/
|
||||
function isVariableDeclaratorWithTypeAnnotation(node) {
|
||||
return (node.type === utils_1.AST_NODE_TYPES.VariableDeclarator && !!node.id.typeAnnotation);
|
||||
}
|
||||
/**
|
||||
* Checks if a node is a class property with a type annotation.
|
||||
* ```
|
||||
* public x: Foo = ...
|
||||
* ```
|
||||
*/
|
||||
function isPropertyDefinitionWithTypeAnnotation(node) {
|
||||
return (node.type === utils_1.AST_NODE_TYPES.PropertyDefinition && !!node.typeAnnotation);
|
||||
}
|
||||
/**
|
||||
* Checks if a node belongs to:
|
||||
* ```
|
||||
* foo(() => 1)
|
||||
* ```
|
||||
*/
|
||||
function isFunctionArgument(parent, callee) {
|
||||
return (parent.type === utils_1.AST_NODE_TYPES.CallExpression &&
|
||||
// make sure this isn't an IIFE
|
||||
parent.callee !== callee);
|
||||
}
|
||||
/**
|
||||
* Checks if a node is type-constrained in JSX
|
||||
* ```
|
||||
* <Foo x={() => {}} />
|
||||
* <Bar>{() => {}}</Bar>
|
||||
* <Baz {...props} />
|
||||
* ```
|
||||
*/
|
||||
function isTypedJSX(node) {
|
||||
return (node.type === utils_1.AST_NODE_TYPES.JSXExpressionContainer ||
|
||||
node.type === utils_1.AST_NODE_TYPES.JSXSpreadAttribute);
|
||||
}
|
||||
function isTypedParent(parent, callee) {
|
||||
return ((0, astUtils_1.isTypeAssertion)(parent) ||
|
||||
isVariableDeclaratorWithTypeAnnotation(parent) ||
|
||||
isDefaultFunctionParameterWithTypeAnnotation(parent) ||
|
||||
isPropertyDefinitionWithTypeAnnotation(parent) ||
|
||||
isFunctionArgument(parent, callee) ||
|
||||
isTypedJSX(parent));
|
||||
}
|
||||
function isDefaultFunctionParameterWithTypeAnnotation(node) {
|
||||
return (node.type === utils_1.AST_NODE_TYPES.AssignmentPattern &&
|
||||
node.left.typeAnnotation != null);
|
||||
}
|
||||
/**
|
||||
* Checks if a node belongs to:
|
||||
* ```
|
||||
* new Foo(() => {})
|
||||
* ^^^^^^^^
|
||||
* ```
|
||||
*/
|
||||
function isConstructorArgument(node) {
|
||||
return node.type === utils_1.AST_NODE_TYPES.NewExpression;
|
||||
}
|
||||
/**
|
||||
* Checks if a node is a property or a nested property of a typed object:
|
||||
* ```
|
||||
* const x: Foo = { prop: () => {} }
|
||||
* const x = { prop: () => {} } as Foo
|
||||
* const x = <Foo>{ prop: () => {} }
|
||||
* const x: Foo = { bar: { prop: () => {} } }
|
||||
* ```
|
||||
*/
|
||||
function isPropertyOfObjectWithType(property) {
|
||||
if (property?.type !== utils_1.AST_NODE_TYPES.Property) {
|
||||
return false;
|
||||
}
|
||||
const objectExpr = property.parent;
|
||||
if (objectExpr.type !== utils_1.AST_NODE_TYPES.ObjectExpression) {
|
||||
return false;
|
||||
}
|
||||
const parent = objectExpr.parent;
|
||||
return isTypedParent(parent) || isPropertyOfObjectWithType(parent);
|
||||
}
|
||||
/**
|
||||
* Checks if a function belongs to:
|
||||
* ```
|
||||
* () => () => ...
|
||||
* () => function () { ... }
|
||||
* () => { return () => ... }
|
||||
* () => { return function () { ... } }
|
||||
* function fn() { return () => ... }
|
||||
* function fn() { return function() { ... } }
|
||||
* ```
|
||||
*/
|
||||
function doesImmediatelyReturnFunctionExpression({ node, returns, }) {
|
||||
if (node.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression &&
|
||||
utils_1.ASTUtils.isFunction(node.body)) {
|
||||
return true;
|
||||
}
|
||||
if (returns.length === 0) {
|
||||
return false;
|
||||
}
|
||||
return returns.every(node => node.argument && utils_1.ASTUtils.isFunction(node.argument));
|
||||
}
|
||||
/**
|
||||
* Checks if a function belongs to:
|
||||
* ```
|
||||
* ({ action: 'xxx' } as const)
|
||||
* ```
|
||||
*/
|
||||
function isConstAssertion(node) {
|
||||
if ((0, astUtils_1.isTypeAssertion)(node)) {
|
||||
const { typeAnnotation } = node;
|
||||
if (typeAnnotation.type === utils_1.AST_NODE_TYPES.TSTypeReference) {
|
||||
const { typeName } = typeAnnotation;
|
||||
if (typeName.type === utils_1.AST_NODE_TYPES.Identifier &&
|
||||
typeName.name === 'const') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* True when the provided function expression is typed.
|
||||
*/
|
||||
function isTypedFunctionExpression(node, options) {
|
||||
if (!options.allowTypedFunctionExpressions) {
|
||||
return false;
|
||||
}
|
||||
return (isTypedParent(node.parent, node) ||
|
||||
isPropertyOfObjectWithType(node.parent) ||
|
||||
isConstructorArgument(node.parent));
|
||||
}
|
||||
/**
|
||||
* Check whether the function expression return type is either typed or valid
|
||||
* with the provided options.
|
||||
*/
|
||||
function isValidFunctionExpressionReturnType(node, options) {
|
||||
if (isTypedFunctionExpression(node, options)) {
|
||||
return true;
|
||||
}
|
||||
if (options.allowExpressions &&
|
||||
node.parent.type !== utils_1.AST_NODE_TYPES.VariableDeclarator &&
|
||||
node.parent.type !== utils_1.AST_NODE_TYPES.MethodDefinition &&
|
||||
node.parent.type !== utils_1.AST_NODE_TYPES.ExportDefaultDeclaration &&
|
||||
node.parent.type !== utils_1.AST_NODE_TYPES.PropertyDefinition) {
|
||||
return true;
|
||||
}
|
||||
// https://github.com/typescript-eslint/typescript-eslint/issues/653
|
||||
if (!options.allowDirectConstAssertionInArrowFunctions ||
|
||||
node.type !== utils_1.AST_NODE_TYPES.ArrowFunctionExpression) {
|
||||
return false;
|
||||
}
|
||||
let body = node.body;
|
||||
while (body.type === utils_1.AST_NODE_TYPES.TSSatisfiesExpression) {
|
||||
body = body.expression;
|
||||
}
|
||||
return isConstAssertion(body);
|
||||
}
|
||||
/**
|
||||
* Check that the function expression or declaration is valid.
|
||||
*/
|
||||
function isValidFunctionReturnType({ node, returns }, options) {
|
||||
if (options.allowHigherOrderFunctions &&
|
||||
doesImmediatelyReturnFunctionExpression({ node, returns })) {
|
||||
return true;
|
||||
}
|
||||
return (node.returnType != null ||
|
||||
(0, astUtils_1.isConstructor)(node.parent) ||
|
||||
(0, astUtils_1.isSetter)(node.parent));
|
||||
}
|
||||
/**
|
||||
* Checks if a function declaration/expression has a return type.
|
||||
*/
|
||||
function checkFunctionReturnType({ node, returns }, options, sourceCode, report) {
|
||||
if (isValidFunctionReturnType({ node, returns }, options)) {
|
||||
return;
|
||||
}
|
||||
report((0, getFunctionHeadLoc_1.getFunctionHeadLoc)(node, sourceCode));
|
||||
}
|
||||
/**
|
||||
* Checks if a function declaration/expression has a return type.
|
||||
*/
|
||||
function checkFunctionExpressionReturnType(info, options, sourceCode, report) {
|
||||
if (isValidFunctionExpressionReturnType(info.node, options)) {
|
||||
return;
|
||||
}
|
||||
checkFunctionReturnType(info, options, sourceCode, report);
|
||||
}
|
||||
/**
|
||||
* Check whether any ancestor of the provided function has a valid return type.
|
||||
*/
|
||||
function ancestorHasReturnType(node) {
|
||||
let ancestor = node.parent;
|
||||
if (ancestor.type === utils_1.AST_NODE_TYPES.Property) {
|
||||
ancestor = ancestor.value;
|
||||
}
|
||||
// if the ancestor is not a return, then this function was not returned at all, so we can exit early
|
||||
const isReturnStatement = ancestor.type === utils_1.AST_NODE_TYPES.ReturnStatement;
|
||||
const isBodylessArrow = ancestor.type === utils_1.AST_NODE_TYPES.ArrowFunctionExpression &&
|
||||
ancestor.body.type !== utils_1.AST_NODE_TYPES.BlockStatement;
|
||||
if (!isReturnStatement && !isBodylessArrow) {
|
||||
return false;
|
||||
}
|
||||
while (ancestor) {
|
||||
switch (ancestor.type) {
|
||||
case utils_1.AST_NODE_TYPES.ArrowFunctionExpression:
|
||||
case utils_1.AST_NODE_TYPES.FunctionExpression:
|
||||
case utils_1.AST_NODE_TYPES.FunctionDeclaration:
|
||||
if (ancestor.returnType) {
|
||||
return true;
|
||||
}
|
||||
break;
|
||||
// const x: Foo = () => {};
|
||||
// Assume that a typed variable types the function expression
|
||||
case utils_1.AST_NODE_TYPES.VariableDeclarator:
|
||||
return !!ancestor.id.typeAnnotation;
|
||||
case utils_1.AST_NODE_TYPES.PropertyDefinition:
|
||||
return !!ancestor.typeAnnotation;
|
||||
case utils_1.AST_NODE_TYPES.ExpressionStatement:
|
||||
return false;
|
||||
}
|
||||
ancestor = ancestor.parent;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
Reference in New Issue
Block a user