WIP: bootstrap and partial real Solana watcher implementation

This commit is contained in:
2026-08-16 09:17:45 +00:00
commit dc23412c3f
7232 changed files with 1687637 additions and 0 deletions

View File

@@ -0,0 +1,80 @@
import CacheHandler from './cache-interceptor'
import Dispatcher from './dispatcher'
import RetryHandler from './retry-handler'
import { LookupOptions } from 'node:dns'
export default Interceptors
declare namespace Interceptors {
export type DumpInterceptorOpts = { maxSize?: number }
export type RetryInterceptorOpts = RetryHandler.RetryOptions
export type RedirectInterceptorOpts = { maxRedirections?: number, throwOnMaxRedirect?: boolean }
export type DecompressInterceptorOpts = {
skipErrorResponses?: boolean
skipStatusCodes?: number[]
}
export type ResponseErrorInterceptorOpts = { throwOnError: boolean }
export type CacheInterceptorOpts = CacheHandler.CacheOptions
// DNS interceptor
export type DNSInterceptorRecord = { address: string, ttl: number, family: 4 | 6 }
export type DNSInterceptorOriginRecords = { records: { 4: { ips: DNSInterceptorRecord[] } | null, 6: { ips: DNSInterceptorRecord[] } | null } }
export type DNSStorage = {
size: number
get(origin: string): DNSInterceptorOriginRecords | null
set(origin: string, records: DNSInterceptorOriginRecords | null, options: { ttl: number }): void
delete(origin: string): void
full(): boolean
}
export type DNSInterceptorOpts = {
maxTTL?: number
maxItems?: number
lookup?: (origin: URL, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, addresses: DNSInterceptorRecord[]) => void) => void
pick?: (origin: URL, records: DNSInterceptorOriginRecords, affinity: 4 | 6) => DNSInterceptorRecord
dualStack?: boolean
affinity?: 4 | 6
storage?: DNSStorage
}
// Deduplicate interceptor
export type DeduplicateMethods = 'GET' | 'HEAD' | 'OPTIONS' | 'TRACE'
export type DeduplicateInterceptorOpts = {
/**
* The HTTP methods to deduplicate.
* Note: Only safe HTTP methods can be deduplicated.
* @default ['GET']
*/
methods?: DeduplicateMethods[]
/**
* Header names that, if present in a request, will cause the request to skip deduplication.
* Header name matching is case-insensitive.
* @default []
*/
skipHeaderNames?: string[]
/**
* Header names to exclude from the deduplication key.
* Requests with different values for these headers will still be deduplicated together.
* Useful for headers like `x-request-id` that vary per request but shouldn't affect deduplication.
* Header name matching is case-insensitive.
* @default []
*/
excludeHeaderNames?: string[]
/**
* Maximum bytes buffered per paused waiting deduplicated handler.
* If a waiting handler remains paused and exceeds this threshold,
* it is failed with an abort error to prevent unbounded memory growth.
* @default 5 * 1024 * 1024
*/
maxBufferSize?: number
}
export function dump (opts?: DumpInterceptorOpts): Dispatcher.DispatcherComposeInterceptor
export function retry (opts?: RetryInterceptorOpts): Dispatcher.DispatcherComposeInterceptor
export function redirect (opts?: RedirectInterceptorOpts): Dispatcher.DispatcherComposeInterceptor
export function decompress (opts?: DecompressInterceptorOpts): Dispatcher.DispatcherComposeInterceptor
export function responseError (opts?: ResponseErrorInterceptorOpts): Dispatcher.DispatcherComposeInterceptor
export function dns (opts?: DNSInterceptorOpts): Dispatcher.DispatcherComposeInterceptor
export function cache (opts?: CacheInterceptorOpts): Dispatcher.DispatcherComposeInterceptor
export function deduplicate (opts?: DeduplicateInterceptorOpts): Dispatcher.DispatcherComposeInterceptor
}

View File

@@ -0,0 +1,361 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const tsutils = __importStar(require("ts-api-utils"));
const ts = __importStar(require("typescript"));
const util_1 = require("../util");
const rangeToLoc_1 = require("../util/rangeToLoc");
const evenNumOfBackslashesRegExp = /(?<!(?:[^\\]|^)(?:\\\\)*\\)/;
// '\\$' <- false
// '\\\\$' <- true
// '\\\\\\$' <- false
function endsWithUnescapedDollarSign(str) {
return new RegExp(`${evenNumOfBackslashesRegExp.source}\\$$`).test(str);
}
exports.default = (0, util_1.createRule)({
name: 'no-unnecessary-template-expression',
meta: {
type: 'suggestion',
docs: {
description: 'Disallow unnecessary template expressions',
recommended: 'strict',
requiresTypeChecking: true,
},
fixable: 'code',
messages: {
noUnnecessaryTemplateExpression: 'Template literal expression is unnecessary and can be simplified.',
},
schema: [],
},
defaultOptions: [],
create(context) {
const services = (0, util_1.getParserServices)(context);
const checker = services.program.getTypeChecker();
function isStringLike(type) {
return (0, util_1.isTypeFlagSet)(type, ts.TypeFlags.StringLike);
}
function isUnderlyingTypeString(type) {
if (type.isUnion()) {
return type.types.every(isStringLike);
}
if (type.isIntersection()) {
return type.types.some(isStringLike);
}
return isStringLike(type);
}
function isEnumMemberType(type) {
return tsutils.typeConstituents(type).some(t => {
const symbol = t.getSymbol();
return !!(symbol?.valueDeclaration && ts.isEnumMember(symbol.valueDeclaration));
});
}
const isLiteral = (0, util_1.isNodeOfType)(utils_1.TSESTree.AST_NODE_TYPES.Literal);
function isTemplateLiteral(node) {
return node.type === utils_1.AST_NODE_TYPES.TemplateLiteral;
}
function isInfinityIdentifier(node) {
return (node.type === utils_1.AST_NODE_TYPES.Identifier && node.name === 'Infinity');
}
function isNaNIdentifier(node) {
return node.type === utils_1.AST_NODE_TYPES.Identifier && node.name === 'NaN';
}
function isFixableIdentifier(node) {
return ((0, util_1.isUndefinedIdentifier)(node) ||
isInfinityIdentifier(node) ||
isNaNIdentifier(node));
}
function hasCommentsBetweenQuasi(startQuasi, endQuasi) {
const startToken = (0, util_1.nullThrows)(context.sourceCode.getTokenByRangeStart(startQuasi.range[0]), util_1.NullThrowsReasons.MissingToken('`${', 'opening template literal'));
const endToken = (0, util_1.nullThrows)(context.sourceCode.getTokenByRangeStart(endQuasi.range[0]), util_1.NullThrowsReasons.MissingToken('}', 'closing template literal'));
return context.sourceCode.commentsExistBetween(startToken, endToken);
}
function isTrivialInterpolation(node) {
return (node.quasis.length === 2 &&
node.quasis[0].value.raw === '' &&
node.quasis[1].value.raw === '');
}
function getInterpolations(node) {
if (node.type === utils_1.AST_NODE_TYPES.TemplateLiteral) {
return node.expressions;
}
return node.types;
}
function getInterpolationInfos(node) {
return getInterpolations(node).map((interpolation, index) => ({
interpolation,
nextQuasi: node.quasis[index + 1],
prevQuasi: node.quasis[index],
}));
}
function getLiteral(node) {
const maybeLiteral = node.type === utils_1.AST_NODE_TYPES.TSLiteralType ? node.literal : node;
return isLiteral(maybeLiteral) ? maybeLiteral : null;
}
function getTemplateLiteral(node) {
const maybeTemplateLiteral = node.type === utils_1.AST_NODE_TYPES.TSLiteralType ? node.literal : node;
return isTemplateLiteral(maybeTemplateLiteral)
? maybeTemplateLiteral
: null;
}
function reportSingleInterpolation(node) {
const interpolations = getInterpolations(node);
context.report({
loc: (0, rangeToLoc_1.rangeToLoc)(context.sourceCode, [
interpolations[0].range[0] - 2,
interpolations[0].range[1] + 1,
]),
messageId: 'noUnnecessaryTemplateExpression',
fix(fixer) {
const wrappingCode = (0, util_1.getMovedNodeCode)({
destinationNode: node,
nodeToMove: interpolations[0],
sourceCode: context.sourceCode,
});
return fixer.replaceText(node, wrappingCode);
},
});
}
function isUnnecessaryValueInterpolation({ interpolation, nextQuasi, prevQuasi, }) {
if (hasCommentsBetweenQuasi(prevQuasi, nextQuasi)) {
return false;
}
if (isFixableIdentifier(interpolation)) {
return true;
}
if (isLiteral(interpolation)) {
// allow trailing whitespace literal
if (startsWithNewLine(nextQuasi.value.raw)) {
return !(typeof interpolation.value === 'string' &&
isWhitespace(interpolation.value));
}
return true;
}
if (isTemplateLiteral(interpolation)) {
// allow trailing whitespace literal
if (startsWithNewLine(nextQuasi.value.raw)) {
return !(interpolation.quasis.length === 1 &&
isWhitespace(interpolation.quasis[0].value.raw));
}
return true;
}
return false;
}
function isUnnecessaryTypeInterpolation({ interpolation, nextQuasi, prevQuasi, }) {
if (hasCommentsBetweenQuasi(prevQuasi, nextQuasi)) {
return false;
}
const literal = getLiteral(interpolation);
if (literal) {
// allow trailing whitespace literal
if (startsWithNewLine(nextQuasi.value.raw)) {
return !(typeof literal.value === 'string' && isWhitespace(literal.value));
}
return true;
}
if (interpolation.type === utils_1.AST_NODE_TYPES.TSNullKeyword ||
interpolation.type === utils_1.AST_NODE_TYPES.TSUndefinedKeyword) {
return true;
}
const templateLiteral = getTemplateLiteral(interpolation);
if (templateLiteral) {
// allow trailing whitespace literal
if (startsWithNewLine(nextQuasi.value.raw)) {
return !(templateLiteral.quasis.length === 1 &&
isWhitespace(templateLiteral.quasis[0].value.raw));
}
return true;
}
return false;
}
function getReportDescriptors(infos) {
let nextCharacterIsOpeningCurlyBrace = false;
const reportDescriptors = [];
const reversedInfos = [...infos].reverse();
for (const { interpolation, nextQuasi, prevQuasi } of reversedInfos) {
const fixers = [];
if (nextQuasi.value.raw !== '') {
nextCharacterIsOpeningCurlyBrace =
nextQuasi.value.raw.startsWith('{');
}
const literal = getLiteral(interpolation);
const templateLiteral = getTemplateLiteral(interpolation);
if (literal) {
let escapedValue = (typeof literal.value === 'string'
? // The value is already a string, so we're removing quotes:
// "'va`lue'" -> "va`lue"
literal.raw.slice(1, -1)
: // The value may be one of number | bigint | boolean | RegExp | null.
// In regular expressions, we escape every backslash
String(literal.value).replaceAll('\\', '\\\\'))
// The string or RegExp may contain ` or ${.
// We want both of these to be escaped in the final template expression.
//
// A pair of backslashes means "escaped backslash", so backslashes
// from this pair won't escape ` or ${. Therefore, to escape these
// sequences in the resulting template expression, we need to escape
// all sequences that are preceded by an even number of backslashes.
//
// This RegExp does the following transformations:
// \` -> \`
// \\` -> \\\`
// \${ -> \${
// \\${ -> \\\${
.replaceAll(new RegExp(`${evenNumOfBackslashesRegExp.source}(\`|\\\${)`, 'g'), '\\$1');
// `...${'...$'}{...`
// ^^^^
if (nextCharacterIsOpeningCurlyBrace &&
endsWithUnescapedDollarSign(escapedValue)) {
escapedValue = escapedValue.replaceAll(/\$$/g, '\\$');
}
if (escapedValue.length !== 0) {
nextCharacterIsOpeningCurlyBrace = escapedValue.startsWith('{');
}
fixers.push(fixer => [fixer.replaceText(literal, escapedValue)]);
}
else if (templateLiteral) {
// Since we iterate from the last expression to the first,
// a subsequent expression can tell the current expression
// that it starts with {.
//
// `... ${`... $`}${'{...'} ...`
// ^ ^ subsequent expression starts with {
// current expression ends with a dollar sign,
// so '$' + '{' === '${' (bad news for us).
// Let's escape the dollar sign at the end.
if (nextCharacterIsOpeningCurlyBrace &&
endsWithUnescapedDollarSign(templateLiteral.quasis[templateLiteral.quasis.length - 1].value
.raw)) {
fixers.push(fixer => [
fixer.replaceTextRange([templateLiteral.range[1] - 2, templateLiteral.range[1] - 2], '\\'),
]);
}
if (templateLiteral.quasis.length === 1 &&
templateLiteral.quasis[0].value.raw.length !== 0) {
nextCharacterIsOpeningCurlyBrace =
templateLiteral.quasis[0].value.raw.startsWith('{');
}
// Remove the beginning and trailing backtick characters.
fixers.push(fixer => [
fixer.removeRange([
templateLiteral.range[0],
templateLiteral.range[0] + 1,
]),
fixer.removeRange([
templateLiteral.range[1] - 1,
templateLiteral.range[1],
]),
]);
}
else {
nextCharacterIsOpeningCurlyBrace = false;
}
// `... $${'{...'} ...`
// ^^^^^
if (nextCharacterIsOpeningCurlyBrace &&
endsWithUnescapedDollarSign(prevQuasi.value.raw)) {
fixers.push(fixer => [
fixer.replaceTextRange([prevQuasi.range[1] - 3, prevQuasi.range[1] - 2], '\\$'),
]);
}
const warnLocStart = prevQuasi.range[1] - 2;
const warnLocEnd = nextQuasi.range[0] + 1;
reportDescriptors.push({
loc: (0, rangeToLoc_1.rangeToLoc)(context.sourceCode, [warnLocStart, warnLocEnd]),
messageId: 'noUnnecessaryTemplateExpression',
fix(fixer) {
return [
// Remove the quasis' parts that are related to the current expression.
fixer.removeRange([warnLocStart, interpolation.range[0]]),
fixer.removeRange([interpolation.range[1], warnLocEnd]),
...fixers.flatMap(cb => cb(fixer)),
];
},
});
}
return reportDescriptors;
}
return {
TemplateLiteral(node) {
if (node.parent.type === utils_1.AST_NODE_TYPES.TaggedTemplateExpression) {
return;
}
if (isTrivialInterpolation(node) &&
!hasCommentsBetweenQuasi(node.quasis[0], node.quasis[1])) {
const { constraintType } = (0, util_1.getConstraintInfo)(checker, services.getTypeAtLocation(node.expressions[0]));
if (constraintType && isUnderlyingTypeString(constraintType)) {
reportSingleInterpolation(node);
return;
}
}
const infos = getInterpolationInfos(node).filter(isUnnecessaryValueInterpolation);
for (const reportDescriptor of getReportDescriptors(infos)) {
context.report(reportDescriptor);
}
},
TSTemplateLiteralType(node) {
if (isTrivialInterpolation(node) &&
!hasCommentsBetweenQuasi(node.quasis[0], node.quasis[1])) {
const { constraintType, isTypeParameter } = (0, util_1.getConstraintInfo)(checker, services.getTypeAtLocation(node.types[0]));
if (constraintType &&
!isTypeParameter &&
isUnderlyingTypeString(constraintType) &&
!isEnumMemberType(constraintType)) {
reportSingleInterpolation(node);
return;
}
}
const infos = getInterpolationInfos(node).filter(isUnnecessaryTypeInterpolation);
for (const reportDescriptor of getReportDescriptors(infos)) {
context.report(reportDescriptor);
}
},
};
},
});
function isWhitespace(x) {
// allow empty string too since we went to allow
// ` ${''}
// `;
//
// in addition to
// `${' '}
// `;
//
return /^\s*$/.test(x);
}
function startsWithNewLine(x) {
return utils_1.ASTUtils.LINEBREAK_MATCHER.exec(x)?.index === 0;
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"jubjub.d.ts","sourceRoot":"","sources":["src/jubjub.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,IAAI,OAAO,EAAE,MAAM,WAAW,CAAC;AAEtF,wEAAwE;AACxE,eAAO,MAAM,MAAM,EAAE,OAAO,OAAiB,CAAC;AAC9C,sFAAsF;AACtF,eAAO,MAAM,aAAa,EAAE,OAAO,oBAA2C,CAAC;AAC/E,kFAAkF;AAClF,eAAO,MAAM,SAAS,EAAE,OAAO,gBAAmC,CAAC"}

View File

@@ -0,0 +1,472 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hash_to_ristretto255 = exports.hashToRistretto255 = exports.encodeToCurve = exports.hashToCurve = exports.RistrettoPoint = exports.edwardsToMontgomery = exports.ED25519_TORSION_SUBGROUP = exports.ristretto255_hasher = exports.ristretto255 = exports.ed25519_hasher = exports.x25519 = exports.ed25519ph = exports.ed25519ctx = exports.ed25519 = void 0;
exports.edwardsToMontgomeryPub = edwardsToMontgomeryPub;
exports.edwardsToMontgomeryPriv = edwardsToMontgomeryPriv;
/**
* ed25519 Twisted Edwards curve with following addons:
* - X25519 ECDH
* - Ristretto cofactor elimination
* - Elligator hash-to-group / point indistinguishability
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const sha2_js_1 = require("@noble/hashes/sha2.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");
// prettier-ignore
const _0n = /* @__PURE__ */ BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);
// prettier-ignore
const _5n = BigInt(5), _8n = BigInt(8);
// P = 2n**255n-19n
const ed25519_CURVE_p = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed');
// N = 2n**252n + 27742317777372353535851937790883648493n
// a = Fp.create(BigInt(-1))
// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))
const ed25519_CURVE = /* @__PURE__ */ (() => ({
p: ed25519_CURVE_p,
n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),
h: _8n,
a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),
d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),
Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),
Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),
}))();
function ed25519_pow_2_252_3(x) {
// prettier-ignore
const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
const P = ed25519_CURVE_p;
const x2 = (x * x) % P;
const b2 = (x2 * x) % P; // x^3, 11
const b4 = ((0, modular_ts_1.pow2)(b2, _2n, P) * b2) % P; // x^15, 1111
const b5 = ((0, modular_ts_1.pow2)(b4, _1n, P) * x) % P; // x^31
const b10 = ((0, modular_ts_1.pow2)(b5, _5n, P) * b5) % P;
const b20 = ((0, modular_ts_1.pow2)(b10, _10n, P) * b10) % P;
const b40 = ((0, modular_ts_1.pow2)(b20, _20n, P) * b20) % P;
const b80 = ((0, modular_ts_1.pow2)(b40, _40n, P) * b40) % P;
const b160 = ((0, modular_ts_1.pow2)(b80, _80n, P) * b80) % P;
const b240 = ((0, modular_ts_1.pow2)(b160, _80n, P) * b80) % P;
const b250 = ((0, modular_ts_1.pow2)(b240, _10n, P) * b10) % P;
const pow_p_5_8 = ((0, modular_ts_1.pow2)(b250, _2n, P) * x) % P;
// ^ To pow to (p+3)/8, multiply it by x.
return { pow_p_5_8, b2 };
}
function adjustScalarBytes(bytes) {
// Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,
// set the three least significant bits of the first byte
bytes[0] &= 248; // 0b1111_1000
// and the most significant bit of the last to zero,
bytes[31] &= 127; // 0b0111_1111
// set the second most significant bit of the last byte to 1
bytes[31] |= 64; // 0b0100_0000
return bytes;
}
// √(-1) aka √(a) aka 2^((p-1)/4)
// Fp.sqrt(Fp.neg(1))
const ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
// sqrt(u/v)
function uvRatio(u, v) {
const P = ed25519_CURVE_p;
const v3 = (0, modular_ts_1.mod)(v * v * v, P); // v³
const v7 = (0, modular_ts_1.mod)(v3 * v3 * v, P); // v⁷
// (p+3)/8 and (p-5)/8
const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
let x = (0, modular_ts_1.mod)(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8
const vx2 = (0, modular_ts_1.mod)(v * x * x, P); // vx²
const root1 = x; // First root candidate
const root2 = (0, modular_ts_1.mod)(x * ED25519_SQRT_M1, P); // Second root candidate
const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root
const useRoot2 = vx2 === (0, modular_ts_1.mod)(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)
const noRoot = vx2 === (0, modular_ts_1.mod)(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)
if (useRoot1)
x = root1;
if (useRoot2 || noRoot)
x = root2; // We return root2 anyway, for const-time
if ((0, modular_ts_1.isNegativeLE)(x, P))
x = (0, modular_ts_1.mod)(-x, P);
return { isValid: useRoot1 || useRoot2, value: x };
}
const Fp = /* @__PURE__ */ (() => (0, modular_ts_1.Field)(ed25519_CURVE.p, { isLE: true }))();
const Fn = /* @__PURE__ */ (() => (0, modular_ts_1.Field)(ed25519_CURVE.n, { isLE: true }))();
const ed25519Defaults = /* @__PURE__ */ (() => ({
...ed25519_CURVE,
Fp,
hash: sha2_js_1.sha512,
adjustScalarBytes,
// dom2
// Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
// Constant-time, u/√v
uvRatio,
}))();
/**
* ed25519 curve with EdDSA signatures.
* @example
* import { ed25519 } from '@noble/curves/ed25519';
* const { secretKey, publicKey } = ed25519.keygen();
* const msg = new TextEncoder().encode('hello');
* const sig = ed25519.sign(msg, priv);
* ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215
* ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5
*/
exports.ed25519 = (() => (0, edwards_ts_1.twistedEdwards)(ed25519Defaults))();
function ed25519_domain(data, ctx, phflag) {
if (ctx.length > 255)
throw new Error('Context is too big');
return (0, utils_js_1.concatBytes)((0, utils_js_1.utf8ToBytes)('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);
}
/** Context of ed25519. Uses context for domain separation. */
exports.ed25519ctx = (() => (0, edwards_ts_1.twistedEdwards)({
...ed25519Defaults,
domain: ed25519_domain,
}))();
/** Prehashed version of ed25519. Accepts already-hashed messages in sign() and verify(). */
exports.ed25519ph = (() => (0, edwards_ts_1.twistedEdwards)(Object.assign({}, ed25519Defaults, {
domain: ed25519_domain,
prehash: sha2_js_1.sha512,
})))();
/**
* ECDH using curve25519 aka x25519.
* @example
* import { x25519 } from '@noble/curves/ed25519';
* const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4';
* const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';
* x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases
* x25519.getPublicKey(priv) === x25519.scalarMultBase(priv);
* x25519.getPublicKey(x25519.utils.randomSecretKey());
*/
exports.x25519 = (() => {
const P = Fp.ORDER;
return (0, montgomery_ts_1.montgomery)({
P,
type: 'x25519',
powPminus2: (x) => {
// x^(p-2) aka x^(2^255-21)
const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
return (0, modular_ts_1.mod)((0, modular_ts_1.pow2)(pow_p_5_8, _3n, P) * b2, P);
},
adjustScalarBytes,
});
})();
// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)
// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since
// SageMath returns different root first and everything falls apart
const ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic
const ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1
const ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)
// prettier-ignore
function map_to_curve_elligator2_curve25519(u) {
const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic
const ELL2_J = BigInt(486662);
let tv1 = Fp.sqr(u); // 1. tv1 = u^2
tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1
let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not
let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)
let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2
let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3
let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd
gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd
gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2
gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2
let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2
tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4
tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3
tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3
tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7
let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)
y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)
let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3
tv2 = Fp.sqr(y11); // 19. tv2 = y11^2
tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd
let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1
let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt
let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd
let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u
y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2
let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3
let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)
tv2 = Fp.sqr(y21); // 28. tv2 = y21^2
tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd
let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2
let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt
tv2 = Fp.sqr(y1); // 32. tv2 = y1^2
tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd
let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1
let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2
let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2
let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y
y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)
return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)
}
const ELL2_C1_EDWARDS = /* @__PURE__ */ (() => (0, modular_ts_1.FpSqrtEven)(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0
function map_to_curve_elligator2_edwards25519(u) {
const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =
// map_to_curve_elligator2_curve25519(u)
let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd
xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1
let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM
let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd
let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)
let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd
let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0
xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)
xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)
yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)
yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)
const [xd_inv, yd_inv] = (0, modular_ts_1.FpInvertBatch)(Fp, [xd, yd], true); // batch division
return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)
}
/** Hashing to ed25519 points / field. RFC 9380 methods. */
exports.ed25519_hasher = (() => (0, hash_to_curve_ts_1.createHasher)(exports.ed25519.Point, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {
DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',
encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',
p: ed25519_CURVE_p,
m: 1,
k: 128,
expand: 'xmd',
hash: sha2_js_1.sha512,
}))();
// √(-1) aka √(a) aka 2^((p-1)/4)
const SQRT_M1 = ED25519_SQRT_M1;
// √(ad - 1)
const SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');
// 1 / √(a-d)
const INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');
// 1-d²
const ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');
// (d-1)²
const D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');
// Calculates 1/√(number)
const invertSqrt = (number) => uvRatio(_1n, number);
const MAX_255B = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
const bytes255ToNumberLE = (bytes) => exports.ed25519.Point.Fp.create((0, utils_ts_1.bytesToNumberLE)(bytes) & MAX_255B);
/**
* Computes Elligator map for Ristretto255.
* Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-B) and on
* the [website](https://ristretto.group/formulas/elligator.html).
*/
function calcElligatorRistrettoMap(r0) {
const { d } = ed25519_CURVE;
const P = ed25519_CURVE_p;
const mod = (n) => Fp.create(n);
const r = mod(SQRT_M1 * r0 * r0); // 1
const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2
let c = BigInt(-1); // 3
const D = mod((c - d * r) * mod(r + d)); // 4
let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5
let s_ = mod(s * r0); // 6
if (!(0, modular_ts_1.isNegativeLE)(s_, P))
s_ = mod(-s_);
if (!Ns_D_is_sq)
s = s_; // 7
if (!Ns_D_is_sq)
c = r; // 8
const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9
const s2 = s * s;
const W0 = mod((s + s) * D); // 10
const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11
const W2 = mod(_1n - s2); // 12
const W3 = mod(_1n + s2); // 13
return new exports.ed25519.Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));
}
function ristretto255_map(bytes) {
(0, utils_js_1.abytes)(bytes, 64);
const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));
const R1 = calcElligatorRistrettoMap(r1);
const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));
const R2 = calcElligatorRistrettoMap(r2);
return new _RistrettoPoint(R1.add(R2));
}
/**
* Wrapper over Edwards Point for ristretto255.
*
* Each ed25519/ExtendedPoint has 8 different equivalent points. This can be
* a source of bugs for protocols like ring signatures. Ristretto was created to solve this.
* Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,
* but it should work in its own namespace: do not combine those two.
* See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).
*/
class _RistrettoPoint extends edwards_ts_1.PrimeEdwardsPoint {
constructor(ep) {
super(ep);
}
static fromAffine(ap) {
return new _RistrettoPoint(exports.ed25519.Point.fromAffine(ap));
}
assertSame(other) {
if (!(other instanceof _RistrettoPoint))
throw new Error('RistrettoPoint expected');
}
init(ep) {
return new _RistrettoPoint(ep);
}
/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */
static hashToCurve(hex) {
return ristretto255_map((0, utils_ts_1.ensureBytes)('ristrettoHash', hex, 64));
}
static fromBytes(bytes) {
(0, utils_js_1.abytes)(bytes, 32);
const { a, d } = ed25519_CURVE;
const P = ed25519_CURVE_p;
const mod = (n) => Fp.create(n);
const s = bytes255ToNumberLE(bytes);
// 1. Check that s_bytes is the canonical encoding of a field element, or else abort.
// 3. Check that s is non-negative, or else abort
if (!(0, utils_ts_1.equalBytes)(Fp.toBytes(s), bytes) || (0, modular_ts_1.isNegativeLE)(s, P))
throw new Error('invalid ristretto255 encoding 1');
const s2 = mod(s * s);
const u1 = mod(_1n + a * s2); // 4 (a is -1)
const u2 = mod(_1n - a * s2); // 5
const u1_2 = mod(u1 * u1);
const u2_2 = mod(u2 * u2);
const v = mod(a * d * u1_2 - u2_2); // 6
const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7
const Dx = mod(I * u2); // 8
const Dy = mod(I * Dx * v); // 9
let x = mod((s + s) * Dx); // 10
if ((0, modular_ts_1.isNegativeLE)(x, P))
x = mod(-x); // 10
const y = mod(u1 * Dy); // 11
const t = mod(x * y); // 12
if (!isValid || (0, modular_ts_1.isNegativeLE)(t, P) || y === _0n)
throw new Error('invalid ristretto255 encoding 2');
return new _RistrettoPoint(new exports.ed25519.Point(x, y, _1n, t));
}
/**
* Converts ristretto-encoded string to ristretto point.
* Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
* @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
*/
static fromHex(hex) {
return _RistrettoPoint.fromBytes((0, utils_ts_1.ensureBytes)('ristrettoHex', hex, 32));
}
static msm(points, scalars) {
return (0, curve_ts_1.pippenger)(_RistrettoPoint, exports.ed25519.Point.Fn, points, scalars);
}
/**
* Encodes ristretto point to Uint8Array.
* Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).
*/
toBytes() {
let { X, Y, Z, T } = this.ep;
const P = ed25519_CURVE_p;
const mod = (n) => Fp.create(n);
const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1
const u2 = mod(X * Y); // 2
// Square root always exists
const u2sq = mod(u2 * u2);
const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3
const D1 = mod(invsqrt * u1); // 4
const D2 = mod(invsqrt * u2); // 5
const zInv = mod(D1 * D2 * T); // 6
let D; // 7
if ((0, modular_ts_1.isNegativeLE)(T * zInv, P)) {
let _x = mod(Y * SQRT_M1);
let _y = mod(X * SQRT_M1);
X = _x;
Y = _y;
D = mod(D1 * INVSQRT_A_MINUS_D);
}
else {
D = D2; // 8
}
if ((0, modular_ts_1.isNegativeLE)(X * zInv, P))
Y = mod(-Y); // 9
let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a))
if ((0, modular_ts_1.isNegativeLE)(s, P))
s = mod(-s);
return Fp.toBytes(s); // 11
}
/**
* Compares two Ristretto points.
* Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).
*/
equals(other) {
this.assertSame(other);
const { X: X1, Y: Y1 } = this.ep;
const { X: X2, Y: Y2 } = other.ep;
const mod = (n) => Fp.create(n);
// (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)
const one = mod(X1 * Y2) === mod(Y1 * X2);
const two = mod(Y1 * Y2) === mod(X1 * X2);
return one || two;
}
is0() {
return this.equals(_RistrettoPoint.ZERO);
}
}
// Do NOT change syntax: the following gymnastics is done,
// because typescript strips comments, which makes bundlers disable tree-shaking.
// prettier-ignore
_RistrettoPoint.BASE =
/* @__PURE__ */ (() => new _RistrettoPoint(exports.ed25519.Point.BASE))();
// prettier-ignore
_RistrettoPoint.ZERO =
/* @__PURE__ */ (() => new _RistrettoPoint(exports.ed25519.Point.ZERO))();
// prettier-ignore
_RistrettoPoint.Fp =
/* @__PURE__ */ (() => Fp)();
// prettier-ignore
_RistrettoPoint.Fn =
/* @__PURE__ */ (() => Fn)();
exports.ristretto255 = { Point: _RistrettoPoint };
/** Hashing to ristretto255 points / field. RFC 9380 methods. */
exports.ristretto255_hasher = {
hashToCurve(msg, options) {
const DST = options?.DST || 'ristretto255_XMD:SHA-512_R255MAP_RO_';
const xmd = (0, hash_to_curve_ts_1.expand_message_xmd)(msg, DST, 64, sha2_js_1.sha512);
return ristretto255_map(xmd);
},
hashToScalar(msg, options = { DST: hash_to_curve_ts_1._DST_scalar }) {
const xmd = (0, hash_to_curve_ts_1.expand_message_xmd)(msg, options.DST, 64, sha2_js_1.sha512);
return Fn.create((0, utils_ts_1.bytesToNumberLE)(xmd));
},
};
// export const ristretto255_oprf: OPRF = createORPF({
// name: 'ristretto255-SHA512',
// Point: RistrettoPoint,
// hash: sha512,
// hashToGroup: ristretto255_hasher.hashToCurve,
// hashToScalar: ristretto255_hasher.hashToScalar,
// });
/**
* Weird / bogus points, useful for debugging.
* All 8 ed25519 points of 8-torsion subgroup can be generated from the point
* T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.
* ⟨T⟩ = { O, T, 2T, 3T, 4T, 5T, 6T, 7T }
*/
exports.ED25519_TORSION_SUBGROUP = [
'0100000000000000000000000000000000000000000000000000000000000000',
'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',
'0000000000000000000000000000000000000000000000000000000000000080',
'26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',
'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',
'26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',
'0000000000000000000000000000000000000000000000000000000000000000',
'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',
];
/** @deprecated use `ed25519.utils.toMontgomery` */
function edwardsToMontgomeryPub(edwardsPub) {
return exports.ed25519.utils.toMontgomery((0, utils_ts_1.ensureBytes)('pub', edwardsPub));
}
/** @deprecated use `ed25519.utils.toMontgomery` */
exports.edwardsToMontgomery = edwardsToMontgomeryPub;
/** @deprecated use `ed25519.utils.toMontgomerySecret` */
function edwardsToMontgomeryPriv(edwardsPriv) {
return exports.ed25519.utils.toMontgomerySecret((0, utils_ts_1.ensureBytes)('pub', edwardsPriv));
}
/** @deprecated use `ristretto255.Point` */
exports.RistrettoPoint = _RistrettoPoint;
/** @deprecated use `import { ed25519_hasher } from '@noble/curves/ed25519.js';` */
exports.hashToCurve = (() => exports.ed25519_hasher.hashToCurve)();
/** @deprecated use `import { ed25519_hasher } from '@noble/curves/ed25519.js';` */
exports.encodeToCurve = (() => exports.ed25519_hasher.encodeToCurve)();
/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */
exports.hashToRistretto255 = (() => exports.ristretto255_hasher.hashToCurve)();
/** @deprecated use `import { ristretto255_hasher } from '@noble/curves/ed25519.js';` */
exports.hash_to_ristretto255 = (() => exports.ristretto255_hasher.hashToCurve)();
//# sourceMappingURL=ed25519.js.map

View File

@@ -0,0 +1,63 @@
{
"name": "@jridgewell/sourcemap-codec",
"version": "1.5.5",
"description": "Encode/decode sourcemap mappings",
"keywords": [
"sourcemap",
"vlq"
],
"main": "dist/sourcemap-codec.umd.js",
"module": "dist/sourcemap-codec.mjs",
"types": "types/sourcemap-codec.d.cts",
"files": [
"dist",
"src",
"types"
],
"exports": {
".": [
{
"import": {
"types": "./types/sourcemap-codec.d.mts",
"default": "./dist/sourcemap-codec.mjs"
},
"default": {
"types": "./types/sourcemap-codec.d.cts",
"default": "./dist/sourcemap-codec.umd.js"
}
},
"./dist/sourcemap-codec.umd.js"
],
"./package.json": "./package.json"
},
"scripts": {
"benchmark": "run-s build:code benchmark:*",
"benchmark:install": "cd benchmark && npm install",
"benchmark:only": "node --expose-gc benchmark/index.js",
"build": "run-s -n build:code build:types",
"build:code": "node ../../esbuild.mjs sourcemap-codec.ts",
"build:types": "run-s build:types:force build:types:emit build:types:mts",
"build:types:force": "rimraf tsconfig.build.tsbuildinfo",
"build:types:emit": "tsc --project tsconfig.build.json",
"build:types:mts": "node ../../mts-types.mjs",
"clean": "run-s -n clean:code clean:types",
"clean:code": "tsc --build --clean tsconfig.build.json",
"clean:types": "rimraf dist types",
"test": "run-s -n test:types test:only test:format",
"test:format": "prettier --check '{src,test}/**/*.ts'",
"test:only": "mocha",
"test:types": "eslint '{src,test}/**/*.ts'",
"lint": "run-s -n lint:types lint:format",
"lint:format": "npm run test:format -- --write",
"lint:types": "npm run test:types -- --fix",
"prepublishOnly": "npm run-s -n build test"
},
"homepage": "https://github.com/jridgewell/sourcemaps/tree/main/packages/sourcemap-codec",
"repository": {
"type": "git",
"url": "git+https://github.com/jridgewell/sourcemaps.git",
"directory": "packages/sourcemap-codec"
},
"author": "Justin Ridgewell <justin@ridgewell.name>",
"license": "MIT"
}

View File

@@ -0,0 +1,33 @@
"use strict";
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) resolve(value);
else Promise.resolve(value).then(_next, _throw);
}
function _async_to_generator(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
exports._ = _async_to_generator;

View File

@@ -0,0 +1,8 @@
// Code generated by Herebyfile.mjs generate:enums from internal/core/compileroptions.go. DO NOT EDIT.
export var NewLineKind;
(function (NewLineKind) {
NewLineKind[NewLineKind["None"] = 0] = "None";
NewLineKind[NewLineKind["CRLF"] = 1] = "CRLF";
NewLineKind[NewLineKind["LF"] = 2] = "LF";
})(NewLineKind || (NewLineKind = {}));
//# sourceMappingURL=newLineKind.enum.js.map

View File

@@ -0,0 +1,150 @@
import * as tty from "tty"
const {
env = {},
argv = [],
platform = "",
} = typeof process === "undefined" ? {} : process
const isDisabled = "NO_COLOR" in env || argv.includes("--no-color")
const isForced = "FORCE_COLOR" in env || argv.includes("--color")
const isWindows = platform === "win32"
const isDumbTerminal = env.TERM === "dumb"
const isCompatibleTerminal =
tty && tty.isatty && tty.isatty(1) && env.TERM && !isDumbTerminal
const isCI =
"CI" in env &&
("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env)
export const isColorSupported =
!isDisabled &&
(isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI)
const replaceClose = (
index,
string,
close,
replace,
head = string.substring(0, index) + replace,
tail = string.substring(index + close.length),
next = tail.indexOf(close)
) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace))
const clearBleed = (index, string, open, close, replace) =>
index < 0
? open + string + close
: open + replaceClose(index, string, close, replace) + close
const filterEmpty =
(open, close, replace = open, at = open.length + 1) =>
(string) =>
string || !(string === "" || string === undefined)
? clearBleed(
("" + string).indexOf(close, at),
string,
open,
close,
replace
)
: ""
const init = (open, close, replace) =>
filterEmpty(`\x1b[${open}m`, `\x1b[${close}m`, replace)
const colors = {
reset: init(0, 0),
bold: init(1, 22, "\x1b[22m\x1b[1m"),
dim: init(2, 22, "\x1b[22m\x1b[2m"),
italic: init(3, 23),
underline: init(4, 24),
inverse: init(7, 27),
hidden: init(8, 28),
strikethrough: init(9, 29),
black: init(30, 39),
red: init(31, 39),
green: init(32, 39),
yellow: init(33, 39),
blue: init(34, 39),
magenta: init(35, 39),
cyan: init(36, 39),
white: init(37, 39),
gray: init(90, 39),
bgBlack: init(40, 49),
bgRed: init(41, 49),
bgGreen: init(42, 49),
bgYellow: init(43, 49),
bgBlue: init(44, 49),
bgMagenta: init(45, 49),
bgCyan: init(46, 49),
bgWhite: init(47, 49),
blackBright: init(90, 39),
redBright: init(91, 39),
greenBright: init(92, 39),
yellowBright: init(93, 39),
blueBright: init(94, 39),
magentaBright: init(95, 39),
cyanBright: init(96, 39),
whiteBright: init(97, 39),
bgBlackBright: init(100, 49),
bgRedBright: init(101, 49),
bgGreenBright: init(102, 49),
bgYellowBright: init(103, 49),
bgBlueBright: init(104, 49),
bgMagentaBright: init(105, 49),
bgCyanBright: init(106, 49),
bgWhiteBright: init(107, 49),
}
export const createColors = ({ useColor = isColorSupported } = {}) =>
useColor
? colors
: Object.keys(colors).reduce(
(colors, key) => ({ ...colors, [key]: String }),
{}
)
export const {
reset,
bold,
dim,
italic,
underline,
inverse,
hidden,
strikethrough,
black,
red,
green,
yellow,
blue,
magenta,
cyan,
white,
gray,
bgBlack,
bgRed,
bgGreen,
bgYellow,
bgBlue,
bgMagenta,
bgCyan,
bgWhite,
blackBright,
redBright,
greenBright,
yellowBright,
blueBright,
magentaBright,
cyanBright,
whiteBright,
bgBlackBright,
bgRedBright,
bgGreenBright,
bgYellowBright,
bgBlueBright,
bgMagentaBright,
bgCyanBright,
bgWhiteBright,
} = createColors()

View File

@@ -0,0 +1,161 @@
/**
* Utilities for hex, bytes, CSPRNG.
* @module
*/
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
export declare function isBytes(a: unknown): a is Uint8Array;
/** Asserts something is positive integer. */
export declare function anumber(n: number): void;
/** Asserts something is Uint8Array. */
export declare function abytes(b: Uint8Array | undefined, ...lengths: number[]): void;
/** Asserts something is hash */
export declare function ahash(h: IHash): void;
/** Asserts a hash instance has not been destroyed / finished */
export declare function aexists(instance: any, checkFinished?: boolean): void;
/** Asserts output is properly-sized byte array */
export declare function aoutput(out: any, instance: any): void;
/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */
export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array;
/** Cast u8 / u16 / u32 to u8. */
export declare function u8(arr: TypedArray): Uint8Array;
/** Cast u8 / u16 / u32 to u32. */
export declare function u32(arr: TypedArray): Uint32Array;
/** Zeroize a byte array. Warning: JS provides no guarantees. */
export declare function clean(...arrays: TypedArray[]): void;
/** Create DataView of an array for easy byte-level manipulation. */
export declare function createView(arr: TypedArray): DataView;
/** The rotate right (circular right shift) operation for uint32 */
export declare function rotr(word: number, shift: number): number;
/** The rotate left (circular left shift) operation for uint32 */
export declare function rotl(word: number, shift: number): number;
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
export declare const isLE: boolean;
/** The byte swap operation for uint32 */
export declare function byteSwap(word: number): number;
/** Conditionally byte swap if on a big-endian platform */
export declare const swap8IfBE: (n: number) => number;
/** @deprecated */
export declare const byteSwapIfBE: typeof swap8IfBE;
/** In place byte swap for Uint32Array */
export declare function byteSwap32(arr: Uint32Array): Uint32Array;
export declare const swap32IfBE: (u: Uint32Array) => Uint32Array;
/**
* Convert byte array to hex string. Uses built-in function, when available.
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
*/
export declare function bytesToHex(bytes: Uint8Array): string;
/**
* Convert hex string to byte array. Uses built-in function, when available.
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
*/
export declare function hexToBytes(hex: string): Uint8Array;
/**
* There is no setImmediate in browser and setTimeout is slow.
* Call of async fn will return Promise, which will be fullfiled only on
* next scheduler queue processing step and this is exactly what we need.
*/
export declare const nextTick: () => Promise<void>;
/** Returns control to thread each 'tick' ms to avoid blocking. */
export declare function asyncLoop(iters: number, tick: number, cb: (i: number) => void): Promise<void>;
/**
* Converts string to bytes using UTF8 encoding.
* @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
*/
export declare function utf8ToBytes(str: string): Uint8Array;
/**
* Converts bytes to string using UTF8 encoding.
* @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
*/
export declare function bytesToUtf8(bytes: Uint8Array): string;
/** Accepted input of hash functions. Strings are converted to byte arrays. */
export type Input = string | Uint8Array;
/**
* Normalizes (non-hex) string or Uint8Array to Uint8Array.
* Warning: when Uint8Array is passed, it would NOT get copied.
* Keep in mind for future mutable operations.
*/
export declare function toBytes(data: Input): Uint8Array;
/** KDFs can accept string or Uint8Array for user convenience. */
export type KDFInput = string | Uint8Array;
/**
* Helper for KDFs: consumes uint8array or string.
* When string is passed, does utf8 decoding, using TextDecoder.
*/
export declare function kdfInputToBytes(data: KDFInput): Uint8Array;
/** Copies several Uint8Arrays into one. */
export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array;
type EmptyObj = {};
export declare function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(defaults: T1, opts?: T2): T1 & T2;
/** Hash interface. */
export type IHash = {
(data: Uint8Array): Uint8Array;
blockLen: number;
outputLen: number;
create: any;
};
/** For runtime check if class implements interface */
export declare abstract class Hash<T extends Hash<T>> {
abstract blockLen: number;
abstract outputLen: number;
abstract update(buf: Input): this;
abstract digestInto(buf: Uint8Array): void;
abstract digest(): Uint8Array;
/**
* Resets internal state. Makes Hash instance unusable.
* Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed
* by user, they will need to manually call `destroy()` when zeroing is necessary.
*/
abstract destroy(): void;
/**
* Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`
* when no options are passed.
* Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal
* buffers are overwritten => causes buffer overwrite which is used for digest in some cases.
* There are no guarantees for clean-up because it's impossible in JS.
*/
abstract _cloneInto(to?: T): T;
abstract clone(): T;
}
/**
* XOF: streaming API to read digest in chunks.
* Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.
* When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot
* destroy state, next call can require more bytes.
*/
export type HashXOF<T extends Hash<T>> = Hash<T> & {
xof(bytes: number): Uint8Array;
xofInto(buf: Uint8Array): Uint8Array;
};
/** Hash function */
export type CHash = ReturnType<typeof createHasher>;
/** Hash function with output */
export type CHashO = ReturnType<typeof createOptHasher>;
/** XOF with output */
export type CHashXO = ReturnType<typeof createXOFer>;
/** Wraps hash function, creating an interface on top of it */
export declare function createHasher<T extends Hash<T>>(hashCons: () => Hash<T>): {
(msg: Input): Uint8Array;
outputLen: number;
blockLen: number;
create(): Hash<T>;
};
export declare function createOptHasher<H extends Hash<H>, T extends Object>(hashCons: (opts?: T) => Hash<H>): {
(msg: Input, opts?: T): Uint8Array;
outputLen: number;
blockLen: number;
create(opts?: T): Hash<H>;
};
export declare function createXOFer<H extends HashXOF<H>, T extends Object>(hashCons: (opts?: T) => HashXOF<H>): {
(msg: Input, opts?: T): Uint8Array;
outputLen: number;
blockLen: number;
create(opts?: T): HashXOF<H>;
};
export declare const wrapConstructor: typeof createHasher;
export declare const wrapConstructorWithOpts: typeof createOptHasher;
export declare const wrapXOFConstructorWithOpts: typeof createXOFer;
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
export declare function randomBytes(bytesLength?: number): Uint8Array;
export {};
//# sourceMappingURL=utils.d.ts.map

View File

@@ -0,0 +1,14 @@
# `@typescript-eslint/typescript-estree`
> A parser that produces an ESTree-compatible AST for TypeScript code.
[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/typescript-estree.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/utils)
[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/typescript-estree.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/utils)
## Contributing
👉 See **https://typescript-eslint.io/packages/typescript-estree** for documentation on this package.
> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code.
<!-- Local path for docs: docs/packages/TypeScript_ESTree.mdx -->

View File

@@ -0,0 +1,79 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getMemberHeadLoc = getMemberHeadLoc;
exports.getParameterPropertyHeadLoc = getParameterPropertyHeadLoc;
const eslint_utils_1 = require("@typescript-eslint/utils/eslint-utils");
/**
* Generates report loc suitable for reporting on how a class member is
* declared, rather than how it's implemented.
*
* ```ts
* class A {
* abstract method(): void;
* ~~~~~~~~~~~~~~~
*
* concreteMethod(): void {
* ~~~~~~~~~~~~~~
* // code
* }
*
* abstract private property?: string;
* ~~~~~~~~~~~~~~~~~~~~~~~~~
*
* @decorator override concreteProperty = 'value';
* ~~~~~~~~~~~~~~~~~~~~~~~~~
* }
* ```
*/
function getMemberHeadLoc(sourceCode, node) {
let start;
if (node.decorators.length === 0) {
start = node.loc.start;
}
else {
const lastDecorator = node.decorators[node.decorators.length - 1];
const nextToken = (0, eslint_utils_1.nullThrows)(sourceCode.getTokenAfter(lastDecorator), eslint_utils_1.NullThrowsReasons.MissingToken('token', 'last decorator'));
start = nextToken.loc.start;
}
let end;
if (!node.computed) {
end = node.key.loc.end;
}
else {
const closingBracket = (0, eslint_utils_1.nullThrows)(sourceCode.getTokenAfter(node.key, token => token.value === ']'), eslint_utils_1.NullThrowsReasons.MissingToken(']', node.type));
end = closingBracket.loc.end;
}
return {
end: structuredClone(end),
start: structuredClone(start),
};
}
/**
* Generates report loc suitable for reporting on how a parameter property is
* declared.
*
* ```ts
* class A {
* constructor(private property: string = 'value') {
* ~~~~~~~~~~~~~~~~
* }
* ```
*/
function getParameterPropertyHeadLoc(sourceCode, node, nodeName) {
// Parameter properties have a weirdly different AST structure
// than other class members.
let start;
if (node.decorators.length === 0) {
start = structuredClone(node.loc.start);
}
else {
const lastDecorator = node.decorators[node.decorators.length - 1];
const nextToken = (0, eslint_utils_1.nullThrows)(sourceCode.getTokenAfter(lastDecorator), eslint_utils_1.NullThrowsReasons.MissingToken('token', 'last decorator'));
start = structuredClone(nextToken.loc.start);
}
const end = sourceCode.getLocFromIndex(node.parameter.range[0] + nodeName.length);
return {
end,
start,
};
}

View File

@@ -0,0 +1,263 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const tsutils = __importStar(require("ts-api-utils"));
const util_1 = require("../util");
exports.default = (0, util_1.createRule)({
name: 'require-await',
meta: {
type: 'suggestion',
docs: {
description: 'Disallow async functions which do not return promises and have no `await` expression',
extendsBaseRule: true,
recommended: 'recommended',
requiresTypeChecking: true,
},
hasSuggestions: true,
messages: {
missingAwait: "{{name}} has no 'await' expression.",
removeAsync: "Remove 'async'.",
},
schema: [],
},
defaultOptions: [],
create(context) {
const services = (0, util_1.getParserServices)(context);
const checker = services.program.getTypeChecker();
let scopeInfo = null;
/**
* Push the scope info object to the stack.
*/
function enterFunction(node) {
scopeInfo = {
hasAsync: node.async,
hasAwait: false,
isAsyncYield: false,
isGen: node.generator || false,
upper: scopeInfo,
};
}
/**
* Pop the top scope info object from the stack.
* Also, it reports the function if needed.
*/
function exitFunction(node) {
/* istanbul ignore if */ if (!scopeInfo) {
// this shouldn't ever happen, as we have to exit a function after we enter it
return;
}
if (node.async &&
!scopeInfo.hasAwait &&
!isEmptyFunction(node) &&
!(scopeInfo.isGen && scopeInfo.isAsyncYield)) {
// If the function belongs to a method definition or
// property, then the function's range may not include the
// `async` keyword and we should look at the parent instead.
const nodeWithAsyncKeyword = (node.parent.type === utils_1.AST_NODE_TYPES.MethodDefinition &&
node.parent.value === node) ||
(node.parent.type === utils_1.AST_NODE_TYPES.Property &&
node.parent.method &&
node.parent.value === node)
? node.parent
: node;
const asyncToken = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(nodeWithAsyncKeyword, token => token.value === 'async'), 'The node is an async function, so it must have an "async" token.');
const asyncRange = [
asyncToken.range[0],
(0, util_1.nullThrows)(context.sourceCode.getTokenAfter(asyncToken, {
includeComments: true,
}), 'There will always be a token after the "async" keyword.').range[0],
];
// Removing the `async` keyword can cause parsing errors if the
// current statement is relying on automatic semicolon insertion.
// If ASI is currently being used, then we should replace the
// `async` keyword with a semicolon.
const nextToken = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(asyncToken), 'There will always be a token after the "async" keyword.');
const addSemiColon = nextToken.type === utils_1.AST_TOKEN_TYPES.Punctuator &&
(nextToken.value === '[' || nextToken.value === '(') &&
(nodeWithAsyncKeyword.type === utils_1.AST_NODE_TYPES.MethodDefinition ||
(0, util_1.isStartOfExpressionStatement)(nodeWithAsyncKeyword)) &&
(0, util_1.needsPrecedingSemicolon)(context.sourceCode, nodeWithAsyncKeyword);
const changes = [
{ range: asyncRange, replacement: addSemiColon ? ';' : undefined },
];
// If there's a return type annotation and it's a
// `Promise<T>`, we can also change the return type
// annotation to just `T` as part of the suggestion.
// Alternatively, if the function is a generator and
// the return type annotation is `AsyncGenerator<T>`,
// then we can change it to `Generator<T>`.
if (node.returnType?.typeAnnotation.type ===
utils_1.AST_NODE_TYPES.TSTypeReference) {
if (scopeInfo.isGen) {
if (hasTypeName(node.returnType.typeAnnotation, 'AsyncGenerator')) {
changes.push({
range: node.returnType.typeAnnotation.typeName.range,
replacement: 'Generator',
});
}
}
else if (hasTypeName(node.returnType.typeAnnotation, 'Promise') &&
node.returnType.typeAnnotation.typeArguments != null) {
const openAngle = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(node.returnType.typeAnnotation, token => token.type === utils_1.AST_TOKEN_TYPES.Punctuator &&
token.value === '<'), 'There are type arguments, so the angle bracket will exist.');
const closeAngle = (0, util_1.nullThrows)(context.sourceCode.getLastToken(node.returnType.typeAnnotation, token => token.type === utils_1.AST_TOKEN_TYPES.Punctuator &&
token.value === '>'), 'There are type arguments, so the angle bracket will exist.');
changes.push(
// Remove the closing angled bracket.
{ range: closeAngle.range, replacement: undefined },
// Remove the "Promise" identifier
// and the opening angled bracket.
{
range: [
node.returnType.typeAnnotation.typeName.range[0],
openAngle.range[1],
],
replacement: undefined,
});
}
}
context.report({
loc: (0, util_1.getFunctionHeadLoc)(node, context.sourceCode),
node,
messageId: 'missingAwait',
data: {
name: (0, util_1.upperCaseFirst)((0, util_1.getFunctionNameWithKind)(node)),
},
suggest: [
{
messageId: 'removeAsync',
fix: (fixer) => changes.map(change => change.replacement != null
? fixer.replaceTextRange(change.range, change.replacement)
: fixer.removeRange(change.range)),
},
],
});
}
scopeInfo = scopeInfo.upper;
}
/**
* Checks if the node returns a thenable type
*/
function isThenableType(node) {
const type = checker.getTypeAtLocation(node);
return tsutils.isThenableType(checker, node, type);
}
/**
* Marks the current scope as having an await
*/
function markAsHasAwait() {
if (!scopeInfo) {
return;
}
scopeInfo.hasAwait = true;
}
/**
* Mark `scopeInfo.isAsyncYield` to `true` if it
* 1) delegates async generator function
* or
* 2) yields thenable type
*/
function visitYieldExpression(node) {
if (!scopeInfo?.isGen || !node.argument) {
return;
}
if (node.argument.type === utils_1.AST_NODE_TYPES.Literal) {
// ignoring this as for literals we don't need to check the definition
// eg : async function* run() { yield* 1 }
return;
}
if (!node.delegate) {
if (isThenableType(services.esTreeNodeToTSNodeMap.get(node.argument))) {
scopeInfo.isAsyncYield = true;
}
return;
}
const type = services.getTypeAtLocation(node.argument);
const typesToCheck = expandUnionOrIntersectionType(type);
for (const type of typesToCheck) {
const asyncIterator = tsutils.getWellKnownSymbolPropertyOfType(type, 'asyncIterator', checker);
if (asyncIterator != null) {
scopeInfo.isAsyncYield = true;
break;
}
}
}
return {
ArrowFunctionExpression: enterFunction,
'ArrowFunctionExpression:exit': exitFunction,
AwaitExpression: markAsHasAwait,
'ForOfStatement[await = true]': markAsHasAwait,
FunctionDeclaration: enterFunction,
'FunctionDeclaration:exit': exitFunction,
FunctionExpression: enterFunction,
'FunctionExpression:exit': exitFunction,
'VariableDeclaration[kind = "await using"]': markAsHasAwait,
YieldExpression: visitYieldExpression,
// check body-less async arrow function.
// ignore `async () => await foo` because it's obviously correct
'ArrowFunctionExpression[async = true] > :not(BlockStatement, AwaitExpression)'(node) {
const expression = services.esTreeNodeToTSNodeMap.get(node);
if (isThenableType(expression)) {
markAsHasAwait();
}
},
ReturnStatement(node) {
// short circuit early to avoid unnecessary type checks
if (!scopeInfo || scopeInfo.hasAwait || !scopeInfo.hasAsync) {
return;
}
const { expression } = services.esTreeNodeToTSNodeMap.get(node);
if (expression && isThenableType(expression)) {
markAsHasAwait();
}
},
};
},
});
function isEmptyFunction(node) {
return (node.body.type === utils_1.AST_NODE_TYPES.BlockStatement &&
node.body.body.length === 0);
}
function expandUnionOrIntersectionType(type) {
if (type.isUnionOrIntersection()) {
return type.types.flatMap(expandUnionOrIntersectionType);
}
return [type];
}
function hasTypeName(typeReference, typeName) {
return (typeReference.typeName.type === utils_1.AST_NODE_TYPES.Identifier &&
typeReference.typeName.name === typeName);
}

View File

@@ -0,0 +1,3 @@
import type { SelectorsString } from './enums';
import type { Context, NormalizedSelector, ValidatorFunction } from './types';
export declare function createValidator(type: SelectorsString, context: Context, allConfigs: NormalizedSelector[]): ValidatorFunction;

View File

@@ -0,0 +1,47 @@
{
"name": "utf-8-validate",
"version": "6.0.6",
"description": "Check if a buffer contains valid UTF-8",
"main": "index.js",
"engines": {
"node": ">=6.14.2"
},
"scripts": {
"install": "node-gyp-build",
"prebuild": "prebuildify --napi --strip --target=8.11.2",
"prebuild-linux-musl-x64": "prebuildify-cross --image alpine --napi --strip --target=8.11.2",
"test": "mocha"
},
"files": [
"prebuilds/",
"src/",
"deps/is_utf8/LICENSE-MIT",
"deps/is_utf8/include/is_utf8.h",
"deps/is_utf8/src/is_utf8.cpp",
"binding.gyp",
"fallback.js",
"index.js"
],
"repository": {
"type": "git",
"url": "git+https://github.com/websockets/utf-8-validate.git"
},
"keywords": [
"utf-8-validate"
],
"author": "Einar Otto Stangvik <einaros@gmail.com> (http://2x.io)",
"license": "MIT",
"bugs": {
"url": "https://github.com/websockets/utf-8-validate/issues"
},
"homepage": "https://github.com/websockets/utf-8-validate",
"dependencies": {
"node-gyp-build": "^4.3.0"
},
"devDependencies": {
"mocha": "^11.0.1",
"node-gyp": "^12.1.0",
"prebuildify": "^6.0.0",
"prebuildify-cross": "^5.0.0"
}
}

View File

@@ -0,0 +1,124 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.EMPTY_PATH = exports.makeIssue = void 0;
exports.addIssueToContext = addIssueToContext;
const errors_js_1 = require("../errors.cjs");
const en_js_1 = __importDefault(require("../locales/en.cjs"));
const makeIssue = (params) => {
const { data, path, errorMaps, issueData } = params;
const fullPath = [...path, ...(issueData.path || [])];
const fullIssue = {
...issueData,
path: fullPath,
};
if (issueData.message !== undefined) {
return {
...issueData,
path: fullPath,
message: issueData.message,
};
}
let errorMessage = "";
const maps = errorMaps
.filter((m) => !!m)
.slice()
.reverse();
for (const map of maps) {
errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
}
return {
...issueData,
path: fullPath,
message: errorMessage,
};
};
exports.makeIssue = makeIssue;
exports.EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
const overrideMap = (0, errors_js_1.getErrorMap)();
const issue = (0, exports.makeIssue)({
issueData: issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap, // contextual error map is first priority
ctx.schemaErrorMap, // then schema-bound map if available
overrideMap, // then global override map
overrideMap === en_js_1.default ? undefined : en_js_1.default, // then global default map
].filter((x) => !!x),
});
ctx.common.issues.push(issue);
}
class ParseStatus {
constructor() {
this.value = "valid";
}
dirty() {
if (this.value === "valid")
this.value = "dirty";
}
abort() {
if (this.value !== "aborted")
this.value = "aborted";
}
static mergeArray(status, results) {
const arrayValue = [];
for (const s of results) {
if (s.status === "aborted")
return exports.INVALID;
if (s.status === "dirty")
status.dirty();
arrayValue.push(s.value);
}
return { status: status.value, value: arrayValue };
}
static async mergeObjectAsync(status, pairs) {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value,
});
}
return ParseStatus.mergeObjectSync(status, syncPairs);
}
static mergeObjectSync(status, pairs) {
const finalObject = {};
for (const pair of pairs) {
const { key, value } = pair;
if (key.status === "aborted")
return exports.INVALID;
if (value.status === "aborted")
return exports.INVALID;
if (key.status === "dirty")
status.dirty();
if (value.status === "dirty")
status.dirty();
if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
finalObject[key.value] = value.value;
}
}
return { status: status.value, value: finalObject };
}
}
exports.ParseStatus = ParseStatus;
exports.INVALID = Object.freeze({
status: "aborted",
});
const DIRTY = (value) => ({ status: "dirty", value });
exports.DIRTY = DIRTY;
const OK = (value) => ({ status: "valid", value });
exports.OK = OK;
const isAborted = (x) => x.status === "aborted";
exports.isAborted = isAborted;
const isDirty = (x) => x.status === "dirty";
exports.isDirty = isDirty;
const isValid = (x) => x.status === "valid";
exports.isValid = isValid;
const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
exports.isAsync = isAsync;

View File

@@ -0,0 +1,439 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const tsutils = __importStar(require("ts-api-utils"));
const ts = __importStar(require("typescript"));
const util_1 = require("../util");
const getMemberHeadLoc_1 = require("../util/getMemberHeadLoc");
const functionScopeBoundaries = [
utils_1.AST_NODE_TYPES.ArrowFunctionExpression,
utils_1.AST_NODE_TYPES.FunctionDeclaration,
utils_1.AST_NODE_TYPES.FunctionExpression,
utils_1.AST_NODE_TYPES.MethodDefinition,
].join(', ');
exports.default = (0, util_1.createRule)({
name: 'prefer-readonly',
meta: {
type: 'suggestion',
docs: {
description: "Require private members to be marked as `readonly` if they're never modified outside of the constructor",
requiresTypeChecking: true,
},
fixable: 'code',
messages: {
preferReadonly: "Member '{{name}}' is never reassigned; mark it as `readonly`.",
},
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
onlyInlineLambdas: {
type: 'boolean',
description: 'Whether to restrict checking only to members immediately assigned a lambda value.',
},
},
},
],
},
defaultOptions: [{ onlyInlineLambdas: false }],
create(context, [{ onlyInlineLambdas }]) {
const services = (0, util_1.getParserServices)(context);
const checker = services.program.getTypeChecker();
const classScopeStack = [];
function handlePropertyAccessExpression(node, parent, classScope) {
if (ts.isBinaryExpression(parent)) {
handleParentBinaryExpression(node, parent, classScope);
return;
}
if (ts.isDeleteExpression(parent) || isDestructuringAssignment(node)) {
classScope.addVariableModification(node);
return;
}
if (ts.isPostfixUnaryExpression(parent) ||
ts.isPrefixUnaryExpression(parent)) {
handleParentPostfixOrPrefixUnaryExpression(parent, classScope);
}
}
function handleParentBinaryExpression(node, parent, classScope) {
if (parent.left === node &&
tsutils.isAssignmentKind(parent.operatorToken.kind)) {
classScope.addVariableModification(node);
}
}
function handleParentPostfixOrPrefixUnaryExpression(node, classScope) {
if (node.operator === ts.SyntaxKind.PlusPlusToken ||
node.operator === ts.SyntaxKind.MinusMinusToken) {
classScope.addVariableModification(node.operand);
}
}
function isDestructuringAssignment(node) {
let current = node.parent;
while (current) {
const parent = current.parent;
if (ts.isObjectLiteralExpression(parent) ||
ts.isArrayLiteralExpression(parent) ||
ts.isSpreadAssignment(parent) ||
(ts.isSpreadElement(parent) &&
ts.isArrayLiteralExpression(parent.parent))) {
current = parent;
}
else if (ts.isBinaryExpression(parent) &&
!ts.isPropertyAccessExpression(current)) {
return (parent.left === current &&
parent.operatorToken.kind === ts.SyntaxKind.EqualsToken);
}
else {
break;
}
}
return false;
}
function isFunctionScopeBoundaryInStack(node) {
if (classScopeStack.length === 0) {
return false;
}
const tsNode = services.esTreeNodeToTSNodeMap.get(node);
if (ts.isConstructorDeclaration(tsNode)) {
return false;
}
return tsutils.isFunctionScopeBoundary(tsNode);
}
function getEsNodesFromViolatingNode(violatingNode) {
return {
esNode: services.tsNodeToESTreeNodeMap.get(violatingNode),
nameNode: services.tsNodeToESTreeNodeMap.get(violatingNode.name),
};
}
function getTypeAnnotationForViolatingNode(node, type, initializerType) {
const annotation = checker.typeToString(type);
// verify the about-to-be-added type annotation is in-scope
if (tsutils.isTypeFlagSet(initializerType, ts.TypeFlags.EnumLiteral)) {
const scope = context.sourceCode.getScope(node);
const variable = utils_1.ASTUtils.findVariable(scope, annotation);
if (variable == null) {
return null;
}
const definition = variable.defs.find(def => def.isTypeDefinition);
if (definition == null) {
return null;
}
const definitionType = services.getTypeAtLocation(definition.node);
if (definitionType !== type) {
return null;
}
}
return annotation;
}
return {
[`${functionScopeBoundaries}:exit`](node) {
if (utils_1.ASTUtils.isConstructor(node)) {
classScopeStack[classScopeStack.length - 1].exitConstructor();
}
else if (isFunctionScopeBoundaryInStack(node)) {
classScopeStack[classScopeStack.length - 1].exitNonConstructor();
}
},
'ClassDeclaration, ClassExpression'(node) {
classScopeStack.push(new ClassScope(checker, services.esTreeNodeToTSNodeMap.get(node), onlyInlineLambdas));
},
'ClassDeclaration, ClassExpression:exit'() {
const finalizedClassScope = (0, util_1.nullThrows)(classScopeStack.pop(), 'Stack should exist on class exit');
for (const violatingNode of finalizedClassScope.finalizeUnmodifiedPrivateNonReadonlys()) {
const { esNode, nameNode } = getEsNodesFromViolatingNode(violatingNode);
const reportNodeOrLoc = (() => {
switch (esNode.type) {
case utils_1.AST_NODE_TYPES.MethodDefinition:
case utils_1.AST_NODE_TYPES.PropertyDefinition:
case utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition:
return { loc: (0, getMemberHeadLoc_1.getMemberHeadLoc)(context.sourceCode, esNode) };
case utils_1.AST_NODE_TYPES.TSParameterProperty:
return {
loc: (0, getMemberHeadLoc_1.getParameterPropertyHeadLoc)(context.sourceCode, esNode, nameNode.name),
};
default:
return { node: esNode };
}
})();
const typeAnnotation = (() => {
if (esNode.type !== utils_1.AST_NODE_TYPES.PropertyDefinition) {
return null;
}
if (esNode.typeAnnotation || !esNode.value) {
return null;
}
if (nameNode.type !== utils_1.AST_NODE_TYPES.Identifier) {
return null;
}
const hasConstructorModifications = finalizedClassScope.memberHasConstructorModifications(nameNode.name);
if (!hasConstructorModifications) {
return null;
}
const violatingType = services.getTypeAtLocation(esNode);
const initializerType = services.getTypeAtLocation(esNode.value);
// if the RHS is a literal, its type would be narrowed, while the
// type of the initializer (which isn't `readonly`) would be the
// widened type
if (initializerType === violatingType) {
return null;
}
if (!tsutils.isLiteralType(initializerType)) {
return null;
}
return getTypeAnnotationForViolatingNode(esNode, violatingType, initializerType);
})();
context.report({
...reportNodeOrLoc,
messageId: 'preferReadonly',
data: {
name: context.sourceCode.getText(nameNode),
},
*fix(fixer) {
const readonlyInsertionTarget = esNode.type === utils_1.AST_NODE_TYPES.PropertyDefinition &&
esNode.computed
? (0, util_1.nullThrows)(context.sourceCode.getTokenBefore(nameNode), 'Expected to find a token before computed property name')
: nameNode;
yield fixer.insertTextBefore(readonlyInsertionTarget, 'readonly ');
if (typeAnnotation) {
yield fixer.insertTextAfter(nameNode, `: ${typeAnnotation}`);
}
},
});
}
},
[functionScopeBoundaries](node) {
if (utils_1.ASTUtils.isConstructor(node)) {
classScopeStack[classScopeStack.length - 1].enterConstructor(services.esTreeNodeToTSNodeMap.get(node));
}
else if (isFunctionScopeBoundaryInStack(node)) {
classScopeStack[classScopeStack.length - 1].enterNonConstructor();
}
},
MemberExpression(node) {
if (classScopeStack.length === 0) {
return;
}
const classScope = classScopeStack[classScopeStack.length - 1];
if (!node.computed) {
const tsNode = services.esTreeNodeToTSNodeMap.get(node);
handlePropertyAccessExpression(tsNode, tsNode.parent, classScope);
}
else {
const tsNode = services.esTreeNodeToTSNodeMap.get(node);
if (ts.isElementAccessExpression(tsNode) &&
ts.isBinaryExpression(tsNode.parent) &&
tsNode.parent.left === tsNode &&
tsutils.isAssignmentKind(tsNode.parent.operatorToken.kind)) {
const memberName = (0, util_1.getStaticMemberAccessValue)(node, context);
if (typeof memberName === 'string') {
classScope.addVariableModificationByName(tsNode.expression, memberName);
}
}
}
},
};
},
});
const OUTSIDE_CONSTRUCTOR = -1;
const DIRECTLY_INSIDE_CONSTRUCTOR = 0;
var TypeToClassRelation;
(function (TypeToClassRelation) {
TypeToClassRelation[TypeToClassRelation["ClassAndInstance"] = 0] = "ClassAndInstance";
TypeToClassRelation[TypeToClassRelation["Class"] = 1] = "Class";
TypeToClassRelation[TypeToClassRelation["Instance"] = 2] = "Instance";
TypeToClassRelation[TypeToClassRelation["None"] = 3] = "None";
})(TypeToClassRelation || (TypeToClassRelation = {}));
class ClassScope {
checker;
onlyInlineLambdas;
classType;
constructorScopeDepth = OUTSIDE_CONSTRUCTOR;
memberVariableModifications = new Set();
memberVariableWithConstructorModifications = new Set();
privateModifiableMembers = new Map();
privateModifiableStatics = new Map();
staticVariableModifications = new Set();
constructor(checker, classNode, onlyInlineLambdas) {
this.checker = checker;
this.onlyInlineLambdas = onlyInlineLambdas;
const classType = checker.getTypeAtLocation(classNode);
if (tsutils.isIntersectionType(classType)) {
this.classType = classType.types[0];
}
else {
this.classType = classType;
}
for (const member of classNode.members) {
if (ts.isPropertyDeclaration(member)) {
this.addDeclaredVariable(member);
}
}
}
addDeclaredVariable(node) {
if (!(tsutils.isModifierFlagSet(node, ts.ModifierFlags.Private) ||
node.name.kind === ts.SyntaxKind.PrivateIdentifier) ||
tsutils.isModifierFlagSet(node, ts.ModifierFlags.Accessor | ts.ModifierFlags.Readonly)) {
return;
}
if (this.onlyInlineLambdas &&
node.initializer != null &&
!ts.isArrowFunction(node.initializer)) {
return;
}
const memberName = getMemberName(node.name);
if (memberName == null) {
return;
}
(tsutils.isModifierFlagSet(node, ts.ModifierFlags.Static)
? this.privateModifiableStatics
: this.privateModifiableMembers).set(memberName, node);
}
addVariableModification(node) {
this.addVariableModificationByName(node.expression, node.name.text);
}
addVariableModificationByName(expression, memberName) {
const modifierType = this.checker.getTypeAtLocation(expression);
const relationOfModifierTypeToClass = this.getTypeToClassRelation(modifierType);
if (relationOfModifierTypeToClass === TypeToClassRelation.Instance &&
this.constructorScopeDepth === DIRECTLY_INSIDE_CONSTRUCTOR) {
this.memberVariableWithConstructorModifications.add(memberName);
return;
}
if (relationOfModifierTypeToClass === TypeToClassRelation.Instance ||
relationOfModifierTypeToClass === TypeToClassRelation.ClassAndInstance) {
this.memberVariableModifications.add(memberName);
}
if (relationOfModifierTypeToClass === TypeToClassRelation.Class ||
relationOfModifierTypeToClass === TypeToClassRelation.ClassAndInstance) {
this.staticVariableModifications.add(memberName);
}
}
enterConstructor(node) {
this.constructorScopeDepth = DIRECTLY_INSIDE_CONSTRUCTOR;
for (const parameter of node.parameters) {
if (tsutils.isModifierFlagSet(parameter, ts.ModifierFlags.Private)) {
this.addDeclaredVariable(parameter);
}
}
}
enterNonConstructor() {
if (this.constructorScopeDepth !== OUTSIDE_CONSTRUCTOR) {
this.constructorScopeDepth += 1;
}
}
exitConstructor() {
this.constructorScopeDepth = OUTSIDE_CONSTRUCTOR;
}
exitNonConstructor() {
if (this.constructorScopeDepth !== OUTSIDE_CONSTRUCTOR) {
this.constructorScopeDepth -= 1;
}
}
finalizeUnmodifiedPrivateNonReadonlys() {
this.memberVariableModifications.forEach(variableName => {
this.privateModifiableMembers.delete(variableName);
});
this.staticVariableModifications.forEach(variableName => {
this.privateModifiableStatics.delete(variableName);
});
return [
...this.privateModifiableMembers.values(),
...this.privateModifiableStatics.values(),
];
}
getTypeToClassRelation(type) {
if (type.isIntersection()) {
let result = TypeToClassRelation.None;
for (const subType of type.types) {
const subTypeResult = this.getTypeToClassRelation(subType);
switch (subTypeResult) {
case TypeToClassRelation.Class:
if (result === TypeToClassRelation.Instance) {
return TypeToClassRelation.ClassAndInstance;
}
result = TypeToClassRelation.Class;
break;
case TypeToClassRelation.Instance:
if (result === TypeToClassRelation.Class) {
return TypeToClassRelation.ClassAndInstance;
}
result = TypeToClassRelation.Instance;
break;
}
}
return result;
}
if (type.isUnion()) {
// any union of class/instance and something else will prevent access to
// private members, so we assume that union consists only of classes
// or class instances, because otherwise tsc will report an error
return this.getTypeToClassRelation(type.types[0]);
}
if (!type.getSymbol() || !(0, util_1.typeIsOrHasBaseType)(type, this.classType)) {
return TypeToClassRelation.None;
}
const typeIsClass = tsutils.isObjectType(type) &&
tsutils.isObjectFlagSet(type, ts.ObjectFlags.Anonymous);
if (typeIsClass) {
return TypeToClassRelation.Class;
}
return TypeToClassRelation.Instance;
}
memberHasConstructorModifications(name) {
return this.memberVariableWithConstructorModifications.has(name);
}
}
function getMemberName(name) {
if (ts.isIdentifier(name) ||
ts.isPrivateIdentifier(name) ||
ts.isStringLiteral(name) ||
ts.isNoSubstitutionTemplateLiteral(name) ||
ts.isNumericLiteral(name)) {
return name.text;
}
if (ts.isComputedPropertyName(name)) {
const expression = name.expression;
if (ts.isNumericLiteral(expression)) {
return expression.text;
}
if (ts.isPropertyAccessExpression(expression) &&
ts.isIdentifier(expression.expression) &&
expression.expression.text === 'Symbol') {
return expression.getText();
}
}
return undefined;
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"scopes.d.ts","sourceRoot":"","sources":["../src/scopes.ts"],"names":[],"mappings":"AAKA,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,MAAM,GAAG,MAAM,CAAC;AACrB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,GAAG,GAAG,MAAM,CAAC;AAClB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,WAAW,GAAG,MAAM,CAAC;AAE1B,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAEtC,MAAM,MAAM,aAAa,GAAG,GAAG,CAC7B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;CAAC,EAClC;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,IAAI;CAAC,EACxC;IAAE,IAAI,EAAE,GAAG,EAAE,CAAA;CAAE,CAChB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,GAAG,CAC9B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;CAAC,EAC5B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,YAAY;IAAE,WAAW;CAAC,EACvD;IACE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,OAAO,EAAE,OAAO,CAAC;CAClB,CACF,CAAC;AACF,MAAM,MAAM,QAAQ,GAAG,CAAC,YAAY,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AACpD,KAAK,OAAO,GAAG,sBAAsB,EAAE,CAAC;AACxC,MAAM,MAAM,sBAAsB,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAEnE,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,EAAE,CAyCnE;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,CAQpE;AA2CD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,EAAE,CAoGrE;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,CAUtE"}

View File

@@ -0,0 +1,44 @@
"use strict";
var _define_property = require("./_define_property.cjs");
var _super_prop_base = require("./_super_prop_base.cjs");
function set(target, property, value, receiver) {
if (typeof Reflect !== "undefined" && Reflect.set) set = Reflect.set;
else {
set = function set(target, property, value, receiver) {
var base = _super_prop_base._(target, property);
var desc;
if (base) {
desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.set) {
desc.set.call(receiver, value);
return true;
} else if (!desc.writable) {
return false;
}
}
desc = Object.getOwnPropertyDescriptor(receiver, property);
if (desc) {
if (!desc.writable) return false;
desc.value = value;
Object.defineProperty(receiver, property, desc);
} else {
_define_property._(receiver, property, value);
}
return true;
};
}
return set(target, property, value, receiver);
}
function _set(target, property, value, receiver, isStrict) {
var s = set(target, property, value, receiver || target);
if (!s && isStrict) throw new Error("failed to set property");
return value;
}
exports._ = _set;

View File

@@ -0,0 +1,88 @@
/**
* @fileoverview The FileContext class.
* @author Nicholas C. Zakas
*/
"use strict";
/**
* Represents a file context that the linter can use to lint a file.
*/
class FileContext {
/**
* The current working directory.
* @type {string}
*/
cwd;
/**
* The filename of the file being linted.
* @type {string}
*/
filename;
/**
* The physical filename of the file being linted.
* @type {string}
*/
physicalFilename;
/**
* The source code of the file being linted.
* @type {SourceCode}
*/
sourceCode;
/**
* The language options used when parsing this file.
* @type {Record<string, unknown>}
*/
languageOptions;
/**
* The settings for the file being linted.
* @type {Record<string, unknown>}
*/
settings;
/**
* Creates a new instance.
* @param {Object} config The configuration object for the file context.
* @param {string} config.cwd The current working directory.
* @param {string} config.filename The filename of the file being linted.
* @param {string} config.physicalFilename The physical filename of the file being linted.
* @param {SourceCode} config.sourceCode The source code of the file being linted.
* @param {Record<string, unknown>} config.languageOptions The language options used when parsing this file.
* @param {Record<string, unknown>} config.settings The settings for the file being linted.
*/
constructor({
cwd,
filename,
physicalFilename,
sourceCode,
languageOptions,
settings,
}) {
this.cwd = cwd;
this.filename = filename;
this.physicalFilename = physicalFilename;
this.sourceCode = sourceCode;
this.languageOptions = languageOptions;
this.settings = settings;
Object.freeze(this);
}
/**
* Creates a new object with the current object as the prototype and
* the specified properties as its own properties.
* @param {Object} extension The properties to add to the new object.
* @returns {FileContext} A new object with the current object as the prototype
* and the specified properties as its own properties.
*/
extend(extension) {
return Object.freeze(Object.assign(Object.create(this), extension));
}
}
exports.FileContext = FileContext;

View File

@@ -0,0 +1,59 @@
import type Benchmark from "benchmark";
import datetimeBenchmarks from "./datetime.js";
import discriminatedUnionBenchmarks from "./discriminatedUnion.js";
import ipv4Benchmarks from "./ipv4.js";
import objectBenchmarks from "./object.js";
import primitiveBenchmarks from "./primitives.js";
import realworld from "./realworld.js";
import stringBenchmarks from "./string.js";
import unionBenchmarks from "./union.js";
const argv = process.argv.slice(2);
let suites: Benchmark.Suite[] = [];
if (!argv.length) {
suites = [
...realworld.suites,
...primitiveBenchmarks.suites,
...stringBenchmarks.suites,
...objectBenchmarks.suites,
...unionBenchmarks.suites,
...discriminatedUnionBenchmarks.suites,
];
} else {
if (argv.includes("--realworld")) {
suites.push(...realworld.suites);
}
if (argv.includes("--primitives")) {
suites.push(...primitiveBenchmarks.suites);
}
if (argv.includes("--string")) {
suites.push(...stringBenchmarks.suites);
}
if (argv.includes("--object")) {
suites.push(...objectBenchmarks.suites);
}
if (argv.includes("--union")) {
suites.push(...unionBenchmarks.suites);
}
if (argv.includes("--discriminatedUnion")) {
suites.push(...datetimeBenchmarks.suites);
}
if (argv.includes("--datetime")) {
suites.push(...datetimeBenchmarks.suites);
}
if (argv.includes("--ipv4")) {
suites.push(...ipv4Benchmarks.suites);
}
}
for (const suite of suites) {
suite.run({});
}
// exit on Ctrl-C
process.on("SIGINT", function () {
console.log("Exiting...");
process.exit();
});

View File

@@ -0,0 +1,574 @@
"use strict";
/* @minVersion 7.20.0 */
/**
Enums are used in this file, but not assigned to vars to avoid non-hoistable values
CONSTRUCTOR = 0;
PUBLIC = 1;
PRIVATE = 2;
FIELD = 0;
ACCESSOR = 1;
METHOD = 2;
GETTER = 3;
SETTER = 4;
STATIC = 5;
CLASS = 10; // only used in assertValidReturnValue
*/
function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
function createAddInitializerMethod(initializers, decoratorFinishedRef) {
return function addInitializer(initializer) {
assertNotFinished(decoratorFinishedRef, "addInitializer");
assertCallable(initializer, "An initializer");
initializers.push(initializer);
};
}
function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value) {
var kindStr;
switch (kind) {
case 1 /* ACCESSOR */:
kindStr = "accessor";
break;
case 2 /* METHOD */:
kindStr = "method";
break;
case 3 /* GETTER */:
kindStr = "getter";
break;
case 4 /* SETTER */:
kindStr = "setter";
break;
default:
kindStr = "field";
}
var ctx = { kind: kindStr, name: isPrivate ? "#" + name : name, static: isStatic, private: isPrivate, metadata: metadata };
var decoratorFinishedRef = { v: false };
ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
var get, set;
if (kind === 0 /* FIELD */) {
if (isPrivate) {
get = desc.get;
set = desc.set;
} else {
get = function() {
return this[name];
};
set = function(v) {
this[name] = v;
};
}
} else if (kind === 2 /* METHOD */) {
get = function() {
return desc.value;
};
} else {
// replace with values that will go through the final getter and setter
if (kind === 1 /* ACCESSOR */ || kind === 3 /* GETTER */) {
get = function() {
return desc.get.call(this);
};
}
if (kind === 1 /* ACCESSOR */ || kind === 4 /* SETTER */) {
set = function(v) {
desc.set.call(this, v);
};
}
}
if (get) {
var originalGet = get;
get = function(target) {
if (arguments.length === 0) {
target = this;
}
return originalGet.call(target);
};
}
if (set) {
var originalSet = set;
set = function(target, value) {
if (arguments.length === 1) {
value = target;
target = this;
}
return originalSet.call(target, value);
};
}
if (isPrivate) {
ctx.access = get && set ? { get: get, set: set } : get ? { get: get } : { set: set };
} else {
var has = function(target) {
return name in target;
};
ctx.access = get && set ? { has: has, get: get, set: set } : get ? { has: has, get: get } : { has: has, set: set };
}
var newValue = dec(value, ctx);
decoratorFinishedRef.v = true;
return newValue;
}
function assertNotFinished(decoratorFinishedRef, fnName) {
if (decoratorFinishedRef.v) {
throw new Error("attempted to call " + fnName + " after decoration was finished");
}
}
function assertCallable(fn, hint) {
if (typeof fn !== "function") {
throw new TypeError(hint + " must be a function");
}
}
function assertValidReturnValue(kind, value) {
var type = typeof value;
if (kind === 1 /* ACCESSOR */) {
if (type !== "object" || value === null) {
throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
}
if (value.get !== undefined) {
assertCallable(value.get, "accessor.get");
}
if (value.set !== undefined) {
assertCallable(value.set, "accessor.set");
}
if (value.init !== undefined) {
assertCallable(value.init, "accessor.init");
}
} else if (type !== "function") {
var hint;
if (kind === 0 /* FIELD */) {
hint = "field";
} else if (kind === 10 /* CLASS */) {
hint = "class";
} else {
hint = "method";
}
throw new TypeError(hint + " decorators must return a function or void 0");
}
}
function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata) {
var decs = decInfo[0];
var desc, init, value;
if (isPrivate) {
if (kind === 0 /* FIELD */ || kind === 1 /* ACCESSOR */) {
desc = { get: decInfo[3], set: decInfo[4] };
} else if (kind === 3 /* GETTER */) {
desc = { get: decInfo[3] };
} else if (kind === 4 /* SETTER */) {
desc = { set: decInfo[3] };
} else {
desc = { value: decInfo[3] };
}
} else if (kind !== 0 /* FIELD */) {
desc = Object.getOwnPropertyDescriptor(base, name);
}
if (kind === 1 /* ACCESSOR */) {
value = { get: desc.get, set: desc.set };
} else if (kind === 2 /* METHOD */) {
value = desc.value;
} else if (kind === 3 /* GETTER */) {
value = desc.get;
} else if (kind === 4 /* SETTER */) {
value = desc.set;
}
var newValue, get, set;
if (typeof decs === "function") {
newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
if (newValue !== void 0) {
assertValidReturnValue(kind, newValue);
if (kind === 0 /* FIELD */) {
init = newValue;
} else if (kind === 1 /* ACCESSOR */) {
init = newValue.init;
get = newValue.get || value.get;
set = newValue.set || value.set;
value = { get: get, set: set };
} else {
value = newValue;
}
}
} else {
for (var i = decs.length - 1; i >= 0; i--) {
var dec = decs[i];
newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
if (newValue !== void 0) {
assertValidReturnValue(kind, newValue);
var newInit;
if (kind === 0 /* FIELD */) {
newInit = newValue;
} else if (kind === 1 /* ACCESSOR */) {
newInit = newValue.init;
get = newValue.get || value.get;
set = newValue.set || value.set;
value = { get: get, set: set };
} else {
value = newValue;
}
if (newInit !== void 0) {
if (init === void 0) {
init = newInit;
} else if (typeof init === "function") {
init = [init, newInit];
} else {
init.push(newInit);
}
}
}
}
}
if (kind === 0 /* FIELD */ || kind === 1 /* ACCESSOR */) {
if (init === void 0) {
// If the initializer was void 0, sub in a dummy initializer
init = function(instance, init) {
return init;
};
} else if (typeof init !== "function") {
var ownInitializers = init;
init = function(instance, init) {
var value = init;
for (var i = 0; i < ownInitializers.length; i++) value = ownInitializers[i].call(instance, value);
return value;
};
} else {
var originalInitializer = init;
init = function(instance, init) {
return originalInitializer.call(instance, init);
};
}
ret.push(init);
}
if (kind !== 0 /* FIELD */) {
if (kind === 1 /* ACCESSOR */) {
desc.get = value.get;
desc.set = value.set;
} else if (kind === 2 /* METHOD */) {
desc.value = value;
} else if (kind === 3 /* GETTER */) {
desc.get = value;
} else if (kind === 4 /* SETTER */) {
desc.set = value;
}
if (isPrivate) {
if (kind === 1 /* ACCESSOR */) {
ret.push(function(instance, args) {
return value.get.call(instance, args);
});
ret.push(function(instance, args) {
return value.set.call(instance, args);
});
} else if (kind === 2 /* METHOD */) {
ret.push(value);
} else {
ret.push(function(instance, args) {
return value.call(instance, args);
});
}
} else {
Object.defineProperty(base, name, desc);
}
}
}
function applyMemberDecs(Class, decInfos, metadata) {
var ret = [];
var protoInitializers;
var staticInitializers;
var existingProtoNonFields = new Map();
var existingStaticNonFields = new Map();
for (var i = 0; i < decInfos.length; i++) {
var decInfo = decInfos[i];
// skip computed property names
if (!Array.isArray(decInfo)) continue;
var kind = decInfo[1];
var name = decInfo[2];
var isPrivate = decInfo.length > 3;
var isStatic = kind >= 5; /* STATIC */
var base;
var initializers;
if (isStatic) {
base = Class;
kind = kind - 5 /* STATIC */;
// initialize staticInitializers when we see a non-field static member
staticInitializers = staticInitializers || [];
initializers = staticInitializers;
} else {
base = Class.prototype;
// initialize protoInitializers when we see a non-field member
protoInitializers = protoInitializers || [];
initializers = protoInitializers;
}
if (kind !== 0 /* FIELD */ && !isPrivate) {
var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
var existingKind = existingNonFields.get(name) || 0;
if (existingKind === true || (existingKind === 3 /* GETTER */ && kind !== 4) /* SETTER */ || (existingKind === 4 /* SETTER */ && kind !== 3) /* GETTER */) {
throw new Error(
"Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: "
+ name
);
} else if (!existingKind && kind > 2 /* METHOD */) {
existingNonFields.set(name, kind);
} else {
existingNonFields.set(name, true);
}
}
applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata);
}
pushInitializers(ret, protoInitializers);
pushInitializers(ret, staticInitializers);
return ret;
}
function pushInitializers(ret, initializers) {
if (initializers) {
ret.push(function(instance) {
for (var i = 0; i < initializers.length; i++) initializers[i].call(instance);
return instance;
});
}
}
function applyClassDecs(targetClass, classDecs, metadata) {
if (classDecs.length > 0) {
var initializers = [];
var newClass = targetClass;
var name = targetClass.name;
for (var i = classDecs.length - 1; i >= 0; i--) {
var decoratorFinishedRef = { v: false };
var nextNewClass = classDecs[i](newClass, { kind: "class", name: name, addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef), metadata });
decoratorFinishedRef.v = true;
if (nextNewClass !== undefined) {
assertValidReturnValue(10, /* CLASS */ nextNewClass);
newClass = nextNewClass;
}
}
return [defineMetadata(newClass, metadata), function() {
for (var i = 0; i < initializers.length; i++) initializers[i].call(newClass);
}];
}
// The transformer will not emit assignment when there are no class decorators,
// so we don't have to return an empty array here.
}
function defineMetadata(Class, metadata) {
return Object.defineProperty(Class, Symbol.metadata || Symbol.for("Symbol.metadata"), { configurable: true, enumerable: true, value: metadata });
}
/**
Basic usage:
applyDecs(
Class,
[
// member decorators
[
dec, // dec or array of decs
0, // kind of value being decorated
'prop', // name of public prop on class containing the value being decorated,
'#p', // the name of the private property (if is private, void 0 otherwise),
]
],
[
// class decorators
dec1, dec2
]
)
```
Fully transpiled example:
```js
@dec
class Class {
@dec
a = 123;
@dec
#a = 123;
@dec
@dec2
accessor b = 123;
@dec
accessor #b = 123;
@dec
c() { console.log('c'); }
@dec
#c() { console.log('privC'); }
@dec
get d() { console.log('d'); }
@dec
get #d() { console.log('privD'); }
@dec
set e(v) { console.log('e'); }
@dec
set #e(v) { console.log('privE'); }
}
// becomes
let initializeInstance;
let initializeClass;
let initA;
let initPrivA;
let initB;
let initPrivB, getPrivB, setPrivB;
let privC;
let privD;
let privE;
let Class;
class _Class {
static {
let ret = applyDecs(
this,
[
[dec, 0, 'a'],
[dec, 0, 'a', (i) => i.#a, (i, v) => i.#a = v],
[[dec, dec2], 1, 'b'],
[dec, 1, 'b', (i) => i.#privBData, (i, v) => i.#privBData = v],
[dec, 2, 'c'],
[dec, 2, 'c', () => console.log('privC')],
[dec, 3, 'd'],
[dec, 3, 'd', () => console.log('privD')],
[dec, 4, 'e'],
[dec, 4, 'e', () => console.log('privE')],
],
[
dec
]
)
initA = ret[0];
initPrivA = ret[1];
initB = ret[2];
initPrivB = ret[3];
getPrivB = ret[4];
setPrivB = ret[5];
privC = ret[6];
privD = ret[7];
privE = ret[8];
initializeInstance = ret[9];
Class = ret[10]
initializeClass = ret[11];
}
a = (initializeInstance(this), initA(this, 123));
#a = initPrivA(this, 123);
#bData = initB(this, 123);
get b() { return this.#bData }
set b(v) { this.#bData = v }
#privBData = initPrivB(this, 123);
get #b() { return getPrivB(this); }
set #b(v) { setPrivB(this, v); }
c() { console.log('c'); }
#c(...args) { return privC(this, ...args) }
get d() { console.log('d'); }
get #d() { return privD(this); }
set e(v) { console.log('e'); }
set #e(v) { privE(this, v); }
}
initializeClass(Class);
*/
exports._ = _apply_decs_2203_r = function(targetClass, memberDecs, classDecs, parentClass) {
if (parentClass !== void 0) {
var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")];
}
var metadata = Object.create(parentMetadata === void 0 ? null : parentMetadata);
var e = applyMemberDecs(targetClass, memberDecs, metadata);
if (!classDecs.length) defineMetadata(targetClass, metadata);
return {
e: e,
// Lazily apply class decorations so that member init locals can be properly bound.
get c() {
return applyClassDecs(targetClass, classDecs, metadata);
}
};
};
return _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass);
}
exports._ = _apply_decs_2203_r;

View File

@@ -0,0 +1,11 @@
// Code generated by Herebyfile.mjs generate:enums from internal/core/compileroptions.go. DO NOT EDIT.
export var JsxEmit;
(function (JsxEmit) {
JsxEmit[JsxEmit["None"] = 0] = "None";
JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
JsxEmit[JsxEmit["ReactNative"] = 2] = "ReactNative";
JsxEmit[JsxEmit["React"] = 3] = "React";
JsxEmit[JsxEmit["ReactJSX"] = 4] = "ReactJSX";
JsxEmit[JsxEmit["ReactJSXDev"] = 5] = "ReactJSXDev";
})(JsxEmit || (JsxEmit = {}));
//# sourceMappingURL=jsxEmit.js.map

View File

@@ -0,0 +1,67 @@
var fs = require('fs-extra');
var obj = require('../util/object-path');
/**
* Converts the file contents generated by BenchmarkStatsProcessor to a DataSetComparisonResult array.
* @param {Array} arrFileObj
* @returns {Object}
*/
function mergeToMap(arrFileObj) {
return arrFileObj.reduce(function(result, fileObj) {
var name;
var libData;
for (name in fileObj) {
libData = fileObj[name];
obj.setObject(result, [libData.suite, libData.browser, libData.name], libData);
}
return result;
}, {});
}
/**
* Since every machine has its own speed, absolute test results have no absolute value.
* However, (I suspect that) the one that is the fastest will relatively be faster than the others.
* @typedef {Object} DataSetComparisonResultItem
* @prop {string} name
* @prop {string} browser
* @prop {string} suite
* @prop {boolean} success
* @prop {number} hz
* @prop {boolean} fastest - is fastest or, statistic significantly speaking, no slower than the fastest
* @prop {number} rme - relative margin of error (expressed as decimal, NOT %)
* @prop {number} rhz - relative hz compared to the fastest (expressed as decimal, NOT %)
* @prop {number} sampleSize
*/
/**
* Describes all results of a single test suite within single browser
* @typedef {Object} DataSetComparisonResult
* @prop {string} browser
* @prop {string} suite
* @prop {Object<DataSetComparisonResultItem>} resultMap - key is libName
*/
/**
*
* @param {string[]} files
* @returns {Promise<DataSetComparisonResult[]>}
*/
module.exports = function(files) {
return Promise
.all(files.map(function(file) {
return fs.readJson(file);
}))
.then(function (arrFileObj) {
var map = mergeToMap(arrFileObj);
var result = [];
var suiteName;
var browserName;
var suite;
for (suiteName in map) {
suite = map[suiteName];
for (browserName in suite) {
result.push({ browser: browserName, suite: suiteName, resultMap: suite[browserName]})
}
}
return result;
});
};

View File

@@ -0,0 +1 @@
{"version":3,"file":"diagnosticCategory.js","sourceRoot":"","sources":["../../src/enums/diagnosticCategory.ts"],"names":[],"mappings":"AAAA,yGAAyG;AACzG,MAAM,CAAC,IAAI,kBAAuB,CAAC;AACnC,CAAC,UAAU,kBAAkB;IACzB,kBAAkB,CAAC,kBAAkB,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,GAAG,SAAS,CAAC;IAClE,kBAAkB,CAAC,kBAAkB,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC;IAC9D,kBAAkB,CAAC,kBAAkB,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,GAAG,YAAY,CAAC;IACxE,kBAAkB,CAAC,kBAAkB,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,GAAG,SAAS,CAAC;AACtE,CAAC,CAAC,CAAC,kBAAkB,IAAI,CAAC,kBAAkB,GAAG,EAAE,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1,10 @@
import { Test } from '@vitest/runner';
import { a as BenchFunction, c as BenchmarkAPI } from './benchmark.d.DAaHLpsq.js';
import { Options } from 'tinybench';
import '@vitest/runner/utils';
declare function getBenchOptions(key: Test): Options;
declare function getBenchFn(key: Test): BenchFunction;
declare const bench: BenchmarkAPI;
export { getBenchOptions as a, bench as b, getBenchFn as g };