WIP: bootstrap and partial real Solana watcher implementation
This commit is contained in:
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"secp256k1.d.ts","sourceRoot":"","sources":["src/secp256k1.ts"],"names":[],"mappings":"AAUA,OAAO,EAAe,KAAK,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACzE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAEL,KAAK,SAAS,EACd,KAAK,SAAS,EAEf,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAyB,GAAG,EAAQ,MAAM,uBAAuB,CAAC;AACzE,OAAO,EAIL,KAAK,gBAAgB,IAAI,SAAS,EAElC,KAAK,oBAAoB,EAC1B,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EACL,eAAe,EAIf,eAAe,EAEhB,MAAM,YAAY,CAAC;AAyDpB;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,SAAS,EAAE,iBAGvB,CAAC;AAMF,iBAAS,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,GAAG,UAAU,CAQtE;AAeD;;;GAGG;AACH,iBAAS,MAAM,CAAC,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC,CAY5C;AASD;;GAEG;AACH,iBAAS,mBAAmB,CAAC,SAAS,EAAE,GAAG,GAAG,UAAU,CAEvD;AAED;;;GAGG;AACH,iBAAS,WAAW,CAAC,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,GAAE,GAAqB,GAAG,UAAU,CAgBjG;AAED;;;GAGG;AACH,iBAAS,aAAa,CAAC,SAAS,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,GAAG,OAAO,CAsB5E;AAED,MAAM,MAAM,WAAW,GAAG;IACxB,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,UAAU,KAAK;QAAE,SAAS,EAAE,UAAU,CAAC;QAAC,SAAS,EAAE,UAAU,CAAA;KAAE,CAAC;IAChF,YAAY,EAAE,OAAO,mBAAmB,CAAC;IACzC,IAAI,EAAE,OAAO,WAAW,CAAC;IACzB,MAAM,EAAE,OAAO,aAAa,CAAC;IAC7B,KAAK,EAAE,oBAAoB,CAAC,MAAM,CAAC,CAAC;IACpC,KAAK,EAAE;QACL,eAAe,EAAE,CAAC,IAAI,CAAC,EAAE,UAAU,KAAK,UAAU,CAAC;QACnD,YAAY,EAAE,CAAC,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,KAAK,UAAU,CAAC;QACvD,MAAM,EAAE,OAAO,MAAM,CAAC;QACtB,UAAU,EAAE,OAAO,UAAU,CAAC;QAE9B,wCAAwC;QACxC,gBAAgB,EAAE,CAAC,IAAI,CAAC,EAAE,UAAU,KAAK,UAAU,CAAC;QACpD,8BAA8B;QAC9B,eAAe,EAAE,OAAO,eAAe,CAAC;QACxC,8BAA8B;QAC9B,eAAe,EAAE,OAAO,eAAe,CAAC;QACxC,gCAAgC;QAChC,GAAG,EAAE,OAAO,GAAG,CAAC;KACjB,CAAC;IACF,OAAO,EAAE,YAAY,CAAC;CACvB,CAAC;AACF;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,OAAO,EAAE,WAsClB,CAAC;AA0CL,wEAAwE;AACxE,eAAO,MAAM,gBAAgB,EAAE,SAAS,CAAC,MAAM,CAgBzC,CAAC;AAEP,uFAAuF;AACvF,eAAO,MAAM,WAAW,EAAE,SAAS,CAAC,MAAM,CACT,CAAC;AAElC,uFAAuF;AACvF,eAAO,MAAM,aAAa,EAAE,SAAS,CAAC,MAAM,CACT,CAAC"}
|
||||
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "base64-js",
|
||||
"description": "Base64 encoding/decoding in pure JS",
|
||||
"version": "1.5.1",
|
||||
"author": "T. Jameson Little <t.jameson.little@gmail.com>",
|
||||
"typings": "index.d.ts",
|
||||
"bugs": {
|
||||
"url": "https://github.com/beatgammit/base64-js/issues"
|
||||
},
|
||||
"devDependencies": {
|
||||
"babel-minify": "^0.5.1",
|
||||
"benchmark": "^2.1.4",
|
||||
"browserify": "^16.3.0",
|
||||
"standard": "*",
|
||||
"tape": "4.x"
|
||||
},
|
||||
"homepage": "https://github.com/beatgammit/base64-js",
|
||||
"keywords": [
|
||||
"base64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "index.js",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/beatgammit/base64-js.git"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "browserify -s base64js -r ./ | minify > base64js.min.js",
|
||||
"lint": "standard",
|
||||
"test": "npm run lint && npm run unit",
|
||||
"unit": "tape test/*.js"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/*! *****************************************************************************
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
||||
this file except in compliance with the License. You may obtain a copy of the
|
||||
License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
||||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
||||
MERCHANTABLITY OR NON-INFRINGEMENT.
|
||||
|
||||
See the Apache Version 2.0 License for specific language governing permissions
|
||||
and limitations under the License.
|
||||
***************************************************************************** */
|
||||
|
||||
|
||||
/// <reference no-default-lib="true"/>
|
||||
|
||||
/// <reference lib="es2015.iterable" />
|
||||
|
||||
interface String {
|
||||
/**
|
||||
* Matches a string with a regular expression, and returns an iterable of matches
|
||||
* containing the results of that search.
|
||||
* @param regexp A variable name or string literal containing the regular expression pattern and flags.
|
||||
*/
|
||||
matchAll(regexp: RegExp): IterableIterator<RegExpExecArray>;
|
||||
|
||||
/** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */
|
||||
toLocaleLowerCase(locales?: Intl.LocalesArgument): string;
|
||||
|
||||
/** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */
|
||||
toLocaleUpperCase(locales?: Intl.LocalesArgument): string;
|
||||
|
||||
/**
|
||||
* Determines whether two strings are equivalent in the current or specified locale.
|
||||
* @param that String to compare to target string
|
||||
* @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.
|
||||
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
|
||||
*/
|
||||
localeCompare(that: string, locales?: Intl.LocalesArgument, options?: Intl.CollatorOptions): number;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import {Buffer} from 'buffer';
|
||||
import {
|
||||
assert as assertType,
|
||||
optional,
|
||||
string,
|
||||
type as pick,
|
||||
} from 'superstruct';
|
||||
|
||||
import * as Layout from './layout';
|
||||
import * as shortvec from './utils/shortvec-encoding';
|
||||
import {PublicKey, PUBLIC_KEY_LENGTH} from './publickey';
|
||||
import {guardedShift, guardedSplice} from './utils/guarded-array-utils';
|
||||
|
||||
export const VALIDATOR_INFO_KEY = new PublicKey(
|
||||
'Va1idator1nfo111111111111111111111111111111',
|
||||
);
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
type ConfigKey = {
|
||||
publicKey: PublicKey;
|
||||
isSigner: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Info used to identity validators.
|
||||
*/
|
||||
export type Info = {
|
||||
/** validator name */
|
||||
name: string;
|
||||
/** optional, validator website */
|
||||
website?: string;
|
||||
/** optional, extra information the validator chose to share */
|
||||
details?: string;
|
||||
/** optional, validator logo URL */
|
||||
iconUrl?: string;
|
||||
/** optional, used to identify validators on keybase.io */
|
||||
keybaseUsername?: string;
|
||||
};
|
||||
|
||||
const InfoString = pick({
|
||||
name: string(),
|
||||
website: optional(string()),
|
||||
details: optional(string()),
|
||||
iconUrl: optional(string()),
|
||||
keybaseUsername: optional(string()),
|
||||
});
|
||||
|
||||
/**
|
||||
* ValidatorInfo class
|
||||
*/
|
||||
export class ValidatorInfo {
|
||||
/**
|
||||
* validator public key
|
||||
*/
|
||||
key: PublicKey;
|
||||
/**
|
||||
* validator information
|
||||
*/
|
||||
info: Info;
|
||||
|
||||
/**
|
||||
* Construct a valid ValidatorInfo
|
||||
*
|
||||
* @param key validator public key
|
||||
* @param info validator information
|
||||
*/
|
||||
constructor(key: PublicKey, info: Info) {
|
||||
this.key = key;
|
||||
this.info = info;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserialize ValidatorInfo from the config account data. Exactly two config
|
||||
* keys are required in the data.
|
||||
*
|
||||
* @param buffer config account data
|
||||
* @return null if info was not found
|
||||
*/
|
||||
static fromConfigData(
|
||||
buffer: Buffer | Uint8Array | Array<number>,
|
||||
): ValidatorInfo | null {
|
||||
let byteArray = [...buffer];
|
||||
const configKeyCount = shortvec.decodeLength(byteArray);
|
||||
if (configKeyCount !== 2) return null;
|
||||
|
||||
const configKeys: Array<ConfigKey> = [];
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const publicKey = new PublicKey(
|
||||
guardedSplice(byteArray, 0, PUBLIC_KEY_LENGTH),
|
||||
);
|
||||
const isSigner = guardedShift(byteArray) === 1;
|
||||
configKeys.push({publicKey, isSigner});
|
||||
}
|
||||
|
||||
if (configKeys[0].publicKey.equals(VALIDATOR_INFO_KEY)) {
|
||||
if (configKeys[1].isSigner) {
|
||||
const rawInfo: any = Layout.rustString().decode(Buffer.from(byteArray));
|
||||
const info = JSON.parse(rawInfo as string);
|
||||
assertType(info, InfoString);
|
||||
return new ValidatorInfo(configKeys[1].publicKey, info);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- 0.6
|
||||
- 0.8
|
||||
- 0.10
|
||||
@@ -0,0 +1,5 @@
|
||||
import assertClassBrand from "./assertClassBrand.js";
|
||||
function _classCheckPrivateStaticAccess(s, a, r) {
|
||||
return assertClassBrand(a, s, r);
|
||||
}
|
||||
export { _classCheckPrivateStaticAccess as default };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "../v4/locales/index.cjs";
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,15 @@
|
||||
export declare const TYPE: Readonly<{
|
||||
eslintImplicitGlobalSetting: "readonly";
|
||||
isTypeVariable: true;
|
||||
isValueVariable: false;
|
||||
}>;
|
||||
export declare const VALUE: Readonly<{
|
||||
eslintImplicitGlobalSetting: "readonly";
|
||||
isTypeVariable: false;
|
||||
isValueVariable: true;
|
||||
}>;
|
||||
export declare const TYPE_VALUE: Readonly<{
|
||||
eslintImplicitGlobalSetting: "readonly";
|
||||
isTypeVariable: true;
|
||||
isValueVariable: true;
|
||||
}>;
|
||||
@@ -0,0 +1,131 @@
|
||||
declare module "node:zlib/iter" {
|
||||
import { StatefulTransform, SyncStatefulTransform } from "node:stream/iter";
|
||||
interface BrotliOptions {
|
||||
chunkSize?: number | undefined;
|
||||
params?: { [key: number]: number | boolean } | undefined;
|
||||
dictionary?: NodeJS.ArrayBufferView | undefined;
|
||||
}
|
||||
interface ZlibOptions {
|
||||
chunkSize?: number | undefined;
|
||||
windowBits?: number | undefined;
|
||||
dictionary?: NodeJS.ArrayBufferView | undefined;
|
||||
}
|
||||
interface ZlibCompressionOptions extends ZlibOptions {
|
||||
level?: number | undefined;
|
||||
memLevel?: number | undefined;
|
||||
strategy?: number | undefined;
|
||||
}
|
||||
interface ZstdOptions {
|
||||
chunkSize?: number | undefined;
|
||||
params?: { [key: number]: number | boolean } | undefined;
|
||||
dictionary?: NodeJS.ArrayBufferView | undefined;
|
||||
}
|
||||
interface ZstdCompressionOptions extends ZstdOptions {
|
||||
pledgedSrcSize?: number | undefined;
|
||||
}
|
||||
/**
|
||||
* Create a Brotli compression transform. Output is compatible with
|
||||
* `zlib.brotliDecompress()` and `decompressBrotli()`/`decompressBrotliSync()`.
|
||||
* @since v25.9.0
|
||||
* @returns A stateful transform.
|
||||
*/
|
||||
function compressBrotli(options?: BrotliOptions): StatefulTransform;
|
||||
/**
|
||||
* Create a Brotli compression transform. Output is compatible with
|
||||
* `zlib.brotliDecompress()` and `decompressBrotli()`/`decompressBrotliSync()`.
|
||||
* @since v25.9.0
|
||||
* @returns A stateful transform.
|
||||
*/
|
||||
function compressBrotliSync(options?: BrotliOptions): SyncStatefulTransform;
|
||||
/**
|
||||
* Create a deflate compression transform. Output is compatible with
|
||||
* `zlib.inflate()` and `decompressDeflate()`/`decompressDeflateSync()`.
|
||||
* @since v25.9.0
|
||||
* @returns A stateful transform.
|
||||
*/
|
||||
function compressDeflate(options?: ZlibCompressionOptions): StatefulTransform;
|
||||
/**
|
||||
* Create a deflate compression transform. Output is compatible with
|
||||
* `zlib.inflate()` and `decompressDeflate()`/`decompressDeflateSync()`.
|
||||
* @since v25.9.0
|
||||
* @returns A stateful transform.
|
||||
*/
|
||||
function compressDeflateSync(options?: ZlibCompressionOptions): SyncStatefulTransform;
|
||||
/**
|
||||
* Create a gzip compression transform. Output is compatible with `zlib.gunzip()`
|
||||
* and `decompressGzip()`/`decompressGzipSync()`.
|
||||
* @returns A stateful transform.
|
||||
*/
|
||||
function compressGzip(options?: ZlibCompressionOptions): StatefulTransform;
|
||||
/**
|
||||
* Create a gzip compression transform. Output is compatible with `zlib.gunzip()`
|
||||
* and `decompressGzip()`/`decompressGzipSync()`.
|
||||
* @returns A stateful transform.
|
||||
*/
|
||||
function compressGzipSync(options?: ZlibCompressionOptions): SyncStatefulTransform;
|
||||
/**
|
||||
* Create a Zstandard compression transform. Output is compatible with
|
||||
* `zlib.zstdDecompress()` and `decompressZstd()`/`decompressZstdSync()`.
|
||||
* @since v25.9.0
|
||||
* @returns A stateful transform.
|
||||
*/
|
||||
function compressZstd(options?: ZstdCompressionOptions): StatefulTransform;
|
||||
/**
|
||||
* Create a Zstandard compression transform. Output is compatible with
|
||||
* `zlib.zstdDecompress()` and `decompressZstd()`/`decompressZstdSync()`.
|
||||
* @since v25.9.0
|
||||
* @returns A stateful transform.
|
||||
*/
|
||||
function compressZstdSync(options?: ZstdCompressionOptions): SyncStatefulTransform;
|
||||
/**
|
||||
* Create a Brotli decompression transform.
|
||||
* @since v25.9.0
|
||||
* @returns A stateful transform.
|
||||
*/
|
||||
function decompressBrotli(options?: BrotliOptions): StatefulTransform;
|
||||
/**
|
||||
* Create a Brotli decompression transform.
|
||||
* @since v25.9.0
|
||||
* @returns A stateful transform.
|
||||
*/
|
||||
function decompressBrotliSync(options?: BrotliOptions): SyncStatefulTransform;
|
||||
/**
|
||||
* Create a deflate decompression transform.
|
||||
* @since v25.9.0
|
||||
* @returns A stateful transform.
|
||||
*/
|
||||
function decompressDeflate(options?: ZlibOptions): StatefulTransform;
|
||||
/**
|
||||
* Create a deflate decompression transform.
|
||||
* @since v25.9.0
|
||||
* @returns A stateful transform.
|
||||
*/
|
||||
function decompressDeflateSync(options?: ZlibOptions): SyncStatefulTransform;
|
||||
/**
|
||||
* Create a gzip decompression transform.
|
||||
* @since v25.9.0
|
||||
* @returns A stateful transform.
|
||||
*/
|
||||
function decompressGzip(options?: ZlibOptions): StatefulTransform;
|
||||
/**
|
||||
* Create a gzip decompression transform.
|
||||
* @since v25.9.0
|
||||
* @returns A stateful transform.
|
||||
*/
|
||||
function decompressGzipSync(options?: ZlibOptions): SyncStatefulTransform;
|
||||
/**
|
||||
* Create a Zstandard decompression transform.
|
||||
* @since v25.9.0
|
||||
* @returns A stateful transform.
|
||||
*/
|
||||
function decompressZstd(options?: ZstdOptions): StatefulTransform;
|
||||
/**
|
||||
* Create a Zstandard decompression transform.
|
||||
* @since v25.9.0
|
||||
* @returns A stateful transform.
|
||||
*/
|
||||
function decompressZstdSync(options?: ZstdOptions): SyncStatefulTransform;
|
||||
}
|
||||
declare module "zlib/iter" {
|
||||
export * from "node:zlib/iter";
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
const isWindows = process.platform === 'win32' ||
|
||||
process.env.OSTYPE === 'cygwin' ||
|
||||
process.env.OSTYPE === 'msys'
|
||||
|
||||
const path = require('path')
|
||||
const COLON = isWindows ? ';' : ':'
|
||||
const isexe = require('isexe')
|
||||
|
||||
const getNotFoundError = (cmd) =>
|
||||
Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })
|
||||
|
||||
const getPathInfo = (cmd, opt) => {
|
||||
const colon = opt.colon || COLON
|
||||
|
||||
// If it has a slash, then we don't bother searching the pathenv.
|
||||
// just check the file itself, and that's it.
|
||||
const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
|
||||
: (
|
||||
[
|
||||
// windows always checks the cwd first
|
||||
...(isWindows ? [process.cwd()] : []),
|
||||
...(opt.path || process.env.PATH ||
|
||||
/* istanbul ignore next: very unusual */ '').split(colon),
|
||||
]
|
||||
)
|
||||
const pathExtExe = isWindows
|
||||
? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
|
||||
: ''
|
||||
const pathExt = isWindows ? pathExtExe.split(colon) : ['']
|
||||
|
||||
if (isWindows) {
|
||||
if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
|
||||
pathExt.unshift('')
|
||||
}
|
||||
|
||||
return {
|
||||
pathEnv,
|
||||
pathExt,
|
||||
pathExtExe,
|
||||
}
|
||||
}
|
||||
|
||||
const which = (cmd, opt, cb) => {
|
||||
if (typeof opt === 'function') {
|
||||
cb = opt
|
||||
opt = {}
|
||||
}
|
||||
if (!opt)
|
||||
opt = {}
|
||||
|
||||
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
|
||||
const found = []
|
||||
|
||||
const step = i => new Promise((resolve, reject) => {
|
||||
if (i === pathEnv.length)
|
||||
return opt.all && found.length ? resolve(found)
|
||||
: reject(getNotFoundError(cmd))
|
||||
|
||||
const ppRaw = pathEnv[i]
|
||||
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
|
||||
|
||||
const pCmd = path.join(pathPart, cmd)
|
||||
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
|
||||
: pCmd
|
||||
|
||||
resolve(subStep(p, i, 0))
|
||||
})
|
||||
|
||||
const subStep = (p, i, ii) => new Promise((resolve, reject) => {
|
||||
if (ii === pathExt.length)
|
||||
return resolve(step(i + 1))
|
||||
const ext = pathExt[ii]
|
||||
isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
|
||||
if (!er && is) {
|
||||
if (opt.all)
|
||||
found.push(p + ext)
|
||||
else
|
||||
return resolve(p + ext)
|
||||
}
|
||||
return resolve(subStep(p, i, ii + 1))
|
||||
})
|
||||
})
|
||||
|
||||
return cb ? step(0).then(res => cb(null, res), cb) : step(0)
|
||||
}
|
||||
|
||||
const whichSync = (cmd, opt) => {
|
||||
opt = opt || {}
|
||||
|
||||
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
|
||||
const found = []
|
||||
|
||||
for (let i = 0; i < pathEnv.length; i ++) {
|
||||
const ppRaw = pathEnv[i]
|
||||
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
|
||||
|
||||
const pCmd = path.join(pathPart, cmd)
|
||||
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
|
||||
: pCmd
|
||||
|
||||
for (let j = 0; j < pathExt.length; j ++) {
|
||||
const cur = p + pathExt[j]
|
||||
try {
|
||||
const is = isexe.sync(cur, { pathExt: pathExtExe })
|
||||
if (is) {
|
||||
if (opt.all)
|
||||
found.push(cur)
|
||||
else
|
||||
return cur
|
||||
}
|
||||
} catch (ex) {}
|
||||
}
|
||||
}
|
||||
|
||||
if (opt.all && found.length)
|
||||
return found
|
||||
|
||||
if (opt.nothrow)
|
||||
return null
|
||||
|
||||
throw getNotFoundError(cmd)
|
||||
}
|
||||
|
||||
module.exports = which
|
||||
which.sync = whichSync
|
||||
@@ -0,0 +1,122 @@
|
||||
import * as util from "../core/util.js";
|
||||
const error = () => {
|
||||
const Sizable = {
|
||||
string: { unit: "znakova", verb: "imati" },
|
||||
file: { unit: "bajtova", verb: "imati" },
|
||||
array: { unit: "stavki", verb: "imati" },
|
||||
set: { unit: "stavki", verb: "imati" },
|
||||
};
|
||||
function getSizing(origin) {
|
||||
return Sizable[origin] ?? null;
|
||||
}
|
||||
const FormatDictionary = {
|
||||
regex: "unos",
|
||||
email: "email adresa",
|
||||
url: "URL",
|
||||
emoji: "emoji",
|
||||
uuid: "UUID",
|
||||
uuidv4: "UUIDv4",
|
||||
uuidv6: "UUIDv6",
|
||||
nanoid: "nanoid",
|
||||
guid: "GUID",
|
||||
cuid: "cuid",
|
||||
cuid2: "cuid2",
|
||||
ulid: "ULID",
|
||||
xid: "XID",
|
||||
ksuid: "KSUID",
|
||||
datetime: "ISO datum i vrijeme",
|
||||
date: "ISO datum",
|
||||
time: "ISO vrijeme",
|
||||
duration: "ISO trajanje",
|
||||
ipv4: "IPv4 adresa",
|
||||
ipv6: "IPv6 adresa",
|
||||
cidrv4: "IPv4 raspon",
|
||||
cidrv6: "IPv6 raspon",
|
||||
base64: "base64 kodirani tekst",
|
||||
base64url: "base64url kodirani tekst",
|
||||
json_string: "JSON tekst",
|
||||
e164: "E.164 broj",
|
||||
jwt: "JWT",
|
||||
template_literal: "unos",
|
||||
};
|
||||
const TypeDictionary = {
|
||||
nan: "NaN",
|
||||
string: "tekst",
|
||||
number: "broj",
|
||||
boolean: "boolean",
|
||||
array: "niz",
|
||||
object: "objekt",
|
||||
set: "skup",
|
||||
file: "datoteka",
|
||||
date: "datum",
|
||||
bigint: "bigint",
|
||||
symbol: "simbol",
|
||||
undefined: "undefined",
|
||||
null: "null",
|
||||
function: "funkcija",
|
||||
map: "mapa",
|
||||
};
|
||||
return (issue) => {
|
||||
switch (issue.code) {
|
||||
case "invalid_type": {
|
||||
const expected = TypeDictionary[issue.expected] ?? issue.expected;
|
||||
const receivedType = util.parsedType(issue.input);
|
||||
const received = TypeDictionary[receivedType] ?? receivedType;
|
||||
if (/^[A-Z]/.test(issue.expected)) {
|
||||
return `Neispravan unos: očekuje se instanceof ${issue.expected}, a primljeno je ${received}`;
|
||||
}
|
||||
return `Neispravan unos: očekuje se ${expected}, a primljeno je ${received}`;
|
||||
}
|
||||
case "invalid_value":
|
||||
if (issue.values.length === 1)
|
||||
return `Neispravna vrijednost: očekivano ${util.stringifyPrimitive(issue.values[0])}`;
|
||||
return `Neispravna opcija: očekivano jedno od ${util.joinValues(issue.values, "|")}`;
|
||||
case "too_big": {
|
||||
const adj = issue.inclusive ? "<=" : "<";
|
||||
const sizing = getSizing(issue.origin);
|
||||
const origin = TypeDictionary[issue.origin] ?? issue.origin;
|
||||
if (sizing)
|
||||
return `Preveliko: očekivano da ${origin ?? "vrijednost"} ima ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elemenata"}`;
|
||||
return `Preveliko: očekivano da ${origin ?? "vrijednost"} bude ${adj}${issue.maximum.toString()}`;
|
||||
}
|
||||
case "too_small": {
|
||||
const adj = issue.inclusive ? ">=" : ">";
|
||||
const sizing = getSizing(issue.origin);
|
||||
const origin = TypeDictionary[issue.origin] ?? issue.origin;
|
||||
if (sizing) {
|
||||
return `Premalo: očekivano da ${origin} ima ${adj}${issue.minimum.toString()} ${sizing.unit}`;
|
||||
}
|
||||
return `Premalo: očekivano da ${origin} bude ${adj}${issue.minimum.toString()}`;
|
||||
}
|
||||
case "invalid_format": {
|
||||
const _issue = issue;
|
||||
if (_issue.format === "starts_with")
|
||||
return `Neispravan tekst: mora započinjati s "${_issue.prefix}"`;
|
||||
if (_issue.format === "ends_with")
|
||||
return `Neispravan tekst: mora završavati s "${_issue.suffix}"`;
|
||||
if (_issue.format === "includes")
|
||||
return `Neispravan tekst: mora sadržavati "${_issue.includes}"`;
|
||||
if (_issue.format === "regex")
|
||||
return `Neispravan tekst: mora odgovarati uzorku ${_issue.pattern}`;
|
||||
return `Neispravna ${FormatDictionary[_issue.format] ?? issue.format}`;
|
||||
}
|
||||
case "not_multiple_of":
|
||||
return `Neispravan broj: mora biti višekratnik od ${issue.divisor}`;
|
||||
case "unrecognized_keys":
|
||||
return `Neprepoznat${issue.keys.length > 1 ? "i ključevi" : " ključ"}: ${util.joinValues(issue.keys, ", ")}`;
|
||||
case "invalid_key":
|
||||
return `Neispravan ključ u ${TypeDictionary[issue.origin] ?? issue.origin}`;
|
||||
case "invalid_union":
|
||||
return "Neispravan unos";
|
||||
case "invalid_element":
|
||||
return `Neispravna vrijednost u ${TypeDictionary[issue.origin] ?? issue.origin}`;
|
||||
default:
|
||||
return `Neispravan unos`;
|
||||
}
|
||||
};
|
||||
};
|
||||
export default function () {
|
||||
return {
|
||||
localeError: error(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*! *****************************************************************************
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
||||
this file except in compliance with the License. You may obtain a copy of the
|
||||
License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
||||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
||||
MERCHANTABLITY OR NON-INFRINGEMENT.
|
||||
|
||||
See the Apache Version 2.0 License for specific language governing permissions
|
||||
and limitations under the License.
|
||||
***************************************************************************** */
|
||||
|
||||
|
||||
/// <reference no-default-lib="true"/>
|
||||
|
||||
declare namespace Intl {
|
||||
interface DateTimeFormatPartTypesRegistry {
|
||||
day: any;
|
||||
dayPeriod: any;
|
||||
era: any;
|
||||
hour: any;
|
||||
literal: any;
|
||||
minute: any;
|
||||
month: any;
|
||||
second: any;
|
||||
timeZoneName: any;
|
||||
weekday: any;
|
||||
year: any;
|
||||
}
|
||||
|
||||
type DateTimeFormatPartTypes = keyof DateTimeFormatPartTypesRegistry;
|
||||
|
||||
interface DateTimeFormatPart {
|
||||
type: DateTimeFormatPartTypes;
|
||||
value: string;
|
||||
}
|
||||
|
||||
interface DateTimeFormat {
|
||||
formatToParts(date?: Date | number): DateTimeFormatPart[];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export type MessageIds = 'preferConstructor' | 'preferTypeAnnotation';
|
||||
export type Options = ['constructor' | 'type-annotation'];
|
||||
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<MessageIds, Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
|
||||
name: string;
|
||||
};
|
||||
export default _default;
|
||||
@@ -0,0 +1,272 @@
|
||||
/* eslint-env browser */
|
||||
|
||||
/**
|
||||
* This is the web browser implementation of `debug()`.
|
||||
*/
|
||||
|
||||
exports.formatArgs = formatArgs;
|
||||
exports.save = save;
|
||||
exports.load = load;
|
||||
exports.useColors = useColors;
|
||||
exports.storage = localstorage();
|
||||
exports.destroy = (() => {
|
||||
let warned = false;
|
||||
|
||||
return () => {
|
||||
if (!warned) {
|
||||
warned = true;
|
||||
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
|
||||
}
|
||||
};
|
||||
})();
|
||||
|
||||
/**
|
||||
* Colors.
|
||||
*/
|
||||
|
||||
exports.colors = [
|
||||
'#0000CC',
|
||||
'#0000FF',
|
||||
'#0033CC',
|
||||
'#0033FF',
|
||||
'#0066CC',
|
||||
'#0066FF',
|
||||
'#0099CC',
|
||||
'#0099FF',
|
||||
'#00CC00',
|
||||
'#00CC33',
|
||||
'#00CC66',
|
||||
'#00CC99',
|
||||
'#00CCCC',
|
||||
'#00CCFF',
|
||||
'#3300CC',
|
||||
'#3300FF',
|
||||
'#3333CC',
|
||||
'#3333FF',
|
||||
'#3366CC',
|
||||
'#3366FF',
|
||||
'#3399CC',
|
||||
'#3399FF',
|
||||
'#33CC00',
|
||||
'#33CC33',
|
||||
'#33CC66',
|
||||
'#33CC99',
|
||||
'#33CCCC',
|
||||
'#33CCFF',
|
||||
'#6600CC',
|
||||
'#6600FF',
|
||||
'#6633CC',
|
||||
'#6633FF',
|
||||
'#66CC00',
|
||||
'#66CC33',
|
||||
'#9900CC',
|
||||
'#9900FF',
|
||||
'#9933CC',
|
||||
'#9933FF',
|
||||
'#99CC00',
|
||||
'#99CC33',
|
||||
'#CC0000',
|
||||
'#CC0033',
|
||||
'#CC0066',
|
||||
'#CC0099',
|
||||
'#CC00CC',
|
||||
'#CC00FF',
|
||||
'#CC3300',
|
||||
'#CC3333',
|
||||
'#CC3366',
|
||||
'#CC3399',
|
||||
'#CC33CC',
|
||||
'#CC33FF',
|
||||
'#CC6600',
|
||||
'#CC6633',
|
||||
'#CC9900',
|
||||
'#CC9933',
|
||||
'#CCCC00',
|
||||
'#CCCC33',
|
||||
'#FF0000',
|
||||
'#FF0033',
|
||||
'#FF0066',
|
||||
'#FF0099',
|
||||
'#FF00CC',
|
||||
'#FF00FF',
|
||||
'#FF3300',
|
||||
'#FF3333',
|
||||
'#FF3366',
|
||||
'#FF3399',
|
||||
'#FF33CC',
|
||||
'#FF33FF',
|
||||
'#FF6600',
|
||||
'#FF6633',
|
||||
'#FF9900',
|
||||
'#FF9933',
|
||||
'#FFCC00',
|
||||
'#FFCC33'
|
||||
];
|
||||
|
||||
/**
|
||||
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
|
||||
* and the Firebug extension (any Firefox version) are known
|
||||
* to support "%c" CSS customizations.
|
||||
*
|
||||
* TODO: add a `localStorage` variable to explicitly enable/disable colors
|
||||
*/
|
||||
|
||||
// eslint-disable-next-line complexity
|
||||
function useColors() {
|
||||
// NB: In an Electron preload script, document will be defined but not fully
|
||||
// initialized. Since we know we're in Chrome, we'll just detect this case
|
||||
// explicitly
|
||||
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Internet Explorer and Edge do not support colors.
|
||||
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let m;
|
||||
|
||||
// Is webkit? http://stackoverflow.com/a/16459606/376773
|
||||
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
|
||||
// eslint-disable-next-line no-return-assign
|
||||
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
|
||||
// Is firebug? http://stackoverflow.com/a/398120/376773
|
||||
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
|
||||
// Is firefox >= v31?
|
||||
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
|
||||
(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) ||
|
||||
// Double check webkit in userAgent just in case we are in a worker
|
||||
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
|
||||
}
|
||||
|
||||
/**
|
||||
* Colorize log arguments if enabled.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
|
||||
function formatArgs(args) {
|
||||
args[0] = (this.useColors ? '%c' : '') +
|
||||
this.namespace +
|
||||
(this.useColors ? ' %c' : ' ') +
|
||||
args[0] +
|
||||
(this.useColors ? '%c ' : ' ') +
|
||||
'+' + module.exports.humanize(this.diff);
|
||||
|
||||
if (!this.useColors) {
|
||||
return;
|
||||
}
|
||||
|
||||
const c = 'color: ' + this.color;
|
||||
args.splice(1, 0, c, 'color: inherit');
|
||||
|
||||
// The final "%c" is somewhat tricky, because there could be other
|
||||
// arguments passed either before or after the %c, so we need to
|
||||
// figure out the correct index to insert the CSS into
|
||||
let index = 0;
|
||||
let lastC = 0;
|
||||
args[0].replace(/%[a-zA-Z%]/g, match => {
|
||||
if (match === '%%') {
|
||||
return;
|
||||
}
|
||||
index++;
|
||||
if (match === '%c') {
|
||||
// We only are interested in the *last* %c
|
||||
// (the user may have provided their own)
|
||||
lastC = index;
|
||||
}
|
||||
});
|
||||
|
||||
args.splice(lastC, 0, c);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes `console.debug()` when available.
|
||||
* No-op when `console.debug` is not a "function".
|
||||
* If `console.debug` is not available, falls back
|
||||
* to `console.log`.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
exports.log = console.debug || console.log || (() => {});
|
||||
|
||||
/**
|
||||
* Save `namespaces`.
|
||||
*
|
||||
* @param {String} namespaces
|
||||
* @api private
|
||||
*/
|
||||
function save(namespaces) {
|
||||
try {
|
||||
if (namespaces) {
|
||||
exports.storage.setItem('debug', namespaces);
|
||||
} else {
|
||||
exports.storage.removeItem('debug');
|
||||
}
|
||||
} catch (error) {
|
||||
// Swallow
|
||||
// XXX (@Qix-) should we be logging these?
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load `namespaces`.
|
||||
*
|
||||
* @return {String} returns the previously persisted debug modes
|
||||
* @api private
|
||||
*/
|
||||
function load() {
|
||||
let r;
|
||||
try {
|
||||
r = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;
|
||||
} catch (error) {
|
||||
// Swallow
|
||||
// XXX (@Qix-) should we be logging these?
|
||||
}
|
||||
|
||||
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
|
||||
if (!r && typeof process !== 'undefined' && 'env' in process) {
|
||||
r = process.env.DEBUG;
|
||||
}
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* Localstorage attempts to return the localstorage.
|
||||
*
|
||||
* This is necessary because safari throws
|
||||
* when a user disables cookies/localstorage
|
||||
* and you attempt to access it.
|
||||
*
|
||||
* @return {LocalStorage}
|
||||
* @api private
|
||||
*/
|
||||
|
||||
function localstorage() {
|
||||
try {
|
||||
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
|
||||
// The Browser also has localStorage in the global context.
|
||||
return localStorage;
|
||||
} catch (error) {
|
||||
// Swallow
|
||||
// XXX (@Qix-) should we be logging these?
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = require('./common')(exports);
|
||||
|
||||
const {formatters} = module.exports;
|
||||
|
||||
/**
|
||||
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
|
||||
*/
|
||||
|
||||
formatters.j = function (v) {
|
||||
try {
|
||||
return JSON.stringify(v);
|
||||
} catch (error) {
|
||||
return '[UnexpectedJSONParseError]: ' + error.message;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
"use strict";
|
||||
// THIS CODE WAS AUTOMATICALLY GENERATED
|
||||
// DO NOT EDIT THIS CODE BY HAND
|
||||
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
|
||||
// npx nx generate-lib repo
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.esnext_regexp = void 0;
|
||||
const base_config_1 = require("./base-config");
|
||||
exports.esnext_regexp = {
|
||||
libs: [],
|
||||
variables: [['RegExp', base_config_1.TYPE]],
|
||||
};
|
||||
@@ -0,0 +1,554 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isNegativeLE = void 0;
|
||||
exports.mod = mod;
|
||||
exports.pow = pow;
|
||||
exports.pow2 = pow2;
|
||||
exports.invert = invert;
|
||||
exports.tonelliShanks = tonelliShanks;
|
||||
exports.FpSqrt = FpSqrt;
|
||||
exports.validateField = validateField;
|
||||
exports.FpPow = FpPow;
|
||||
exports.FpInvertBatch = FpInvertBatch;
|
||||
exports.FpDiv = FpDiv;
|
||||
exports.FpLegendre = FpLegendre;
|
||||
exports.FpIsSquare = FpIsSquare;
|
||||
exports.nLength = nLength;
|
||||
exports.Field = Field;
|
||||
exports.FpSqrtOdd = FpSqrtOdd;
|
||||
exports.FpSqrtEven = FpSqrtEven;
|
||||
exports.hashToPrivateScalar = hashToPrivateScalar;
|
||||
exports.getFieldBytesLength = getFieldBytesLength;
|
||||
exports.getMinHashLength = getMinHashLength;
|
||||
exports.mapHashToField = mapHashToField;
|
||||
/**
|
||||
* Utils for modular division and fields.
|
||||
* Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
|
||||
* There is no division: it is replaced by modular multiplicative inverse.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
const utils_ts_1 = require("../utils.js");
|
||||
// prettier-ignore
|
||||
const _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);
|
||||
// prettier-ignore
|
||||
const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);
|
||||
// prettier-ignore
|
||||
const _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
|
||||
// Calculates a modulo b
|
||||
function mod(a, b) {
|
||||
const result = a % b;
|
||||
return result >= _0n ? result : b + result;
|
||||
}
|
||||
/**
|
||||
* Efficiently raise num to power and do modular division.
|
||||
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
|
||||
* @example
|
||||
* pow(2n, 6n, 11n) // 64n % 11n == 9n
|
||||
*/
|
||||
function pow(num, power, modulo) {
|
||||
return FpPow(Field(modulo), num, power);
|
||||
}
|
||||
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
|
||||
function pow2(x, power, modulo) {
|
||||
let res = x;
|
||||
while (power-- > _0n) {
|
||||
res *= res;
|
||||
res %= modulo;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
/**
|
||||
* Inverses number over modulo.
|
||||
* Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
|
||||
*/
|
||||
function invert(number, modulo) {
|
||||
if (number === _0n)
|
||||
throw new Error('invert: expected non-zero number');
|
||||
if (modulo <= _0n)
|
||||
throw new Error('invert: expected positive modulus, got ' + modulo);
|
||||
// Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
|
||||
let a = mod(number, modulo);
|
||||
let b = modulo;
|
||||
// prettier-ignore
|
||||
let x = _0n, y = _1n, u = _1n, v = _0n;
|
||||
while (a !== _0n) {
|
||||
// JIT applies optimization if those two lines follow each other
|
||||
const q = b / a;
|
||||
const r = b % a;
|
||||
const m = x - u * q;
|
||||
const n = y - v * q;
|
||||
// prettier-ignore
|
||||
b = a, a = r, x = u, y = v, u = m, v = n;
|
||||
}
|
||||
const gcd = b;
|
||||
if (gcd !== _1n)
|
||||
throw new Error('invert: does not exist');
|
||||
return mod(x, modulo);
|
||||
}
|
||||
function assertIsSquare(Fp, root, n) {
|
||||
if (!Fp.eql(Fp.sqr(root), n))
|
||||
throw new Error('Cannot find square root');
|
||||
}
|
||||
// Not all roots are possible! Example which will throw:
|
||||
// const NUM =
|
||||
// n = 72057594037927816n;
|
||||
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
|
||||
function sqrt3mod4(Fp, n) {
|
||||
const p1div4 = (Fp.ORDER + _1n) / _4n;
|
||||
const root = Fp.pow(n, p1div4);
|
||||
assertIsSquare(Fp, root, n);
|
||||
return root;
|
||||
}
|
||||
function sqrt5mod8(Fp, n) {
|
||||
const p5div8 = (Fp.ORDER - _5n) / _8n;
|
||||
const n2 = Fp.mul(n, _2n);
|
||||
const v = Fp.pow(n2, p5div8);
|
||||
const nv = Fp.mul(n, v);
|
||||
const i = Fp.mul(Fp.mul(nv, _2n), v);
|
||||
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
|
||||
assertIsSquare(Fp, root, n);
|
||||
return root;
|
||||
}
|
||||
// Based on RFC9380, Kong algorithm
|
||||
// prettier-ignore
|
||||
function sqrt9mod16(P) {
|
||||
const Fp_ = Field(P);
|
||||
const tn = tonelliShanks(P);
|
||||
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
|
||||
const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
|
||||
const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
|
||||
const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic
|
||||
return (Fp, n) => {
|
||||
let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4
|
||||
let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1
|
||||
const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1
|
||||
const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1
|
||||
const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x
|
||||
const e2 = Fp.eql(Fp.sqr(tv3), n); // 6. e2 = (tv3^2) == x
|
||||
tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x
|
||||
tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x
|
||||
const e3 = Fp.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x
|
||||
const root = Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2
|
||||
assertIsSquare(Fp, root, n);
|
||||
return root;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Tonelli-Shanks square root search algorithm.
|
||||
* 1. https://eprint.iacr.org/2012/685.pdf (page 12)
|
||||
* 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
|
||||
* @param P field order
|
||||
* @returns function that takes field Fp (created from P) and number n
|
||||
*/
|
||||
function tonelliShanks(P) {
|
||||
// Initialization (precomputation).
|
||||
// Caching initialization could boost perf by 7%.
|
||||
if (P < _3n)
|
||||
throw new Error('sqrt is not defined for small field');
|
||||
// Factor P - 1 = Q * 2^S, where Q is odd
|
||||
let Q = P - _1n;
|
||||
let S = 0;
|
||||
while (Q % _2n === _0n) {
|
||||
Q /= _2n;
|
||||
S++;
|
||||
}
|
||||
// Find the first quadratic non-residue Z >= 2
|
||||
let Z = _2n;
|
||||
const _Fp = Field(P);
|
||||
while (FpLegendre(_Fp, Z) === 1) {
|
||||
// Basic primality test for P. After x iterations, chance of
|
||||
// not finding quadratic non-residue is 2^x, so 2^1000.
|
||||
if (Z++ > 1000)
|
||||
throw new Error('Cannot find square root: probably non-prime P');
|
||||
}
|
||||
// Fast-path; usually done before Z, but we do "primality test".
|
||||
if (S === 1)
|
||||
return sqrt3mod4;
|
||||
// Slow-path
|
||||
// TODO: test on Fp2 and others
|
||||
let cc = _Fp.pow(Z, Q); // c = z^Q
|
||||
const Q1div2 = (Q + _1n) / _2n;
|
||||
return function tonelliSlow(Fp, n) {
|
||||
if (Fp.is0(n))
|
||||
return n;
|
||||
// Check if n is a quadratic residue using Legendre symbol
|
||||
if (FpLegendre(Fp, n) !== 1)
|
||||
throw new Error('Cannot find square root');
|
||||
// Initialize variables for the main loop
|
||||
let M = S;
|
||||
let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
|
||||
let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor
|
||||
let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
|
||||
// Main loop
|
||||
// while t != 1
|
||||
while (!Fp.eql(t, Fp.ONE)) {
|
||||
if (Fp.is0(t))
|
||||
return Fp.ZERO; // if t=0 return R=0
|
||||
let i = 1;
|
||||
// Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
|
||||
let t_tmp = Fp.sqr(t); // t^(2^1)
|
||||
while (!Fp.eql(t_tmp, Fp.ONE)) {
|
||||
i++;
|
||||
t_tmp = Fp.sqr(t_tmp); // t^(2^2)...
|
||||
if (i === M)
|
||||
throw new Error('Cannot find square root');
|
||||
}
|
||||
// Calculate the exponent for b: 2^(M - i - 1)
|
||||
const exponent = _1n << BigInt(M - i - 1); // bigint is important
|
||||
const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)
|
||||
// Update variables
|
||||
M = i;
|
||||
c = Fp.sqr(b); // c = b^2
|
||||
t = Fp.mul(t, c); // t = (t * b^2)
|
||||
R = Fp.mul(R, b); // R = R*b
|
||||
}
|
||||
return R;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Square root for a finite field. Will try optimized versions first:
|
||||
*
|
||||
* 1. P ≡ 3 (mod 4)
|
||||
* 2. P ≡ 5 (mod 8)
|
||||
* 3. P ≡ 9 (mod 16)
|
||||
* 4. Tonelli-Shanks algorithm
|
||||
*
|
||||
* Different algorithms can give different roots, it is up to user to decide which one they want.
|
||||
* For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
|
||||
*/
|
||||
function FpSqrt(P) {
|
||||
// P ≡ 3 (mod 4) => √n = n^((P+1)/4)
|
||||
if (P % _4n === _3n)
|
||||
return sqrt3mod4;
|
||||
// P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
|
||||
if (P % _8n === _5n)
|
||||
return sqrt5mod8;
|
||||
// P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
|
||||
if (P % _16n === _9n)
|
||||
return sqrt9mod16(P);
|
||||
// Tonelli-Shanks algorithm
|
||||
return tonelliShanks(P);
|
||||
}
|
||||
// Little-endian check for first LE bit (last BE bit);
|
||||
const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
|
||||
exports.isNegativeLE = isNegativeLE;
|
||||
// prettier-ignore
|
||||
const FIELD_FIELDS = [
|
||||
'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
|
||||
'eql', 'add', 'sub', 'mul', 'pow', 'div',
|
||||
'addN', 'subN', 'mulN', 'sqrN'
|
||||
];
|
||||
function validateField(field) {
|
||||
const initial = {
|
||||
ORDER: 'bigint',
|
||||
MASK: 'bigint',
|
||||
BYTES: 'number',
|
||||
BITS: 'number',
|
||||
};
|
||||
const opts = FIELD_FIELDS.reduce((map, val) => {
|
||||
map[val] = 'function';
|
||||
return map;
|
||||
}, initial);
|
||||
(0, utils_ts_1._validateObject)(field, opts);
|
||||
// const max = 16384;
|
||||
// if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');
|
||||
// if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');
|
||||
return field;
|
||||
}
|
||||
// Generic field functions
|
||||
/**
|
||||
* Same as `pow` but for Fp: non-constant-time.
|
||||
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
|
||||
*/
|
||||
function FpPow(Fp, num, power) {
|
||||
if (power < _0n)
|
||||
throw new Error('invalid exponent, negatives unsupported');
|
||||
if (power === _0n)
|
||||
return Fp.ONE;
|
||||
if (power === _1n)
|
||||
return num;
|
||||
let p = Fp.ONE;
|
||||
let d = num;
|
||||
while (power > _0n) {
|
||||
if (power & _1n)
|
||||
p = Fp.mul(p, d);
|
||||
d = Fp.sqr(d);
|
||||
power >>= _1n;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
/**
|
||||
* Efficiently invert an array of Field elements.
|
||||
* Exception-free. Will return `undefined` for 0 elements.
|
||||
* @param passZero map 0 to 0 (instead of undefined)
|
||||
*/
|
||||
function FpInvertBatch(Fp, nums, passZero = false) {
|
||||
const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
|
||||
// Walk from first to last, multiply them by each other MOD p
|
||||
const multipliedAcc = nums.reduce((acc, num, i) => {
|
||||
if (Fp.is0(num))
|
||||
return acc;
|
||||
inverted[i] = acc;
|
||||
return Fp.mul(acc, num);
|
||||
}, Fp.ONE);
|
||||
// Invert last element
|
||||
const invertedAcc = Fp.inv(multipliedAcc);
|
||||
// Walk from last to first, multiply them by inverted each other MOD p
|
||||
nums.reduceRight((acc, num, i) => {
|
||||
if (Fp.is0(num))
|
||||
return acc;
|
||||
inverted[i] = Fp.mul(acc, inverted[i]);
|
||||
return Fp.mul(acc, num);
|
||||
}, invertedAcc);
|
||||
return inverted;
|
||||
}
|
||||
// TODO: remove
|
||||
function FpDiv(Fp, lhs, rhs) {
|
||||
return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));
|
||||
}
|
||||
/**
|
||||
* Legendre symbol.
|
||||
* Legendre constant is used to calculate Legendre symbol (a | p)
|
||||
* which denotes the value of a^((p-1)/2) (mod p).
|
||||
*
|
||||
* * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
|
||||
* * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
|
||||
* * (a | p) ≡ 0 if a ≡ 0 (mod p)
|
||||
*/
|
||||
function FpLegendre(Fp, n) {
|
||||
// We can use 3rd argument as optional cache of this value
|
||||
// but seems unneeded for now. The operation is very fast.
|
||||
const p1mod2 = (Fp.ORDER - _1n) / _2n;
|
||||
const powered = Fp.pow(n, p1mod2);
|
||||
const yes = Fp.eql(powered, Fp.ONE);
|
||||
const zero = Fp.eql(powered, Fp.ZERO);
|
||||
const no = Fp.eql(powered, Fp.neg(Fp.ONE));
|
||||
if (!yes && !zero && !no)
|
||||
throw new Error('invalid Legendre symbol result');
|
||||
return yes ? 1 : zero ? 0 : -1;
|
||||
}
|
||||
// This function returns True whenever the value x is a square in the field F.
|
||||
function FpIsSquare(Fp, n) {
|
||||
const l = FpLegendre(Fp, n);
|
||||
return l === 1;
|
||||
}
|
||||
// CURVE.n lengths
|
||||
function nLength(n, nBitLength) {
|
||||
// Bit size, byte size of CURVE.n
|
||||
if (nBitLength !== undefined)
|
||||
(0, utils_ts_1.anumber)(nBitLength);
|
||||
const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
|
||||
const nByteLength = Math.ceil(_nBitLength / 8);
|
||||
return { nBitLength: _nBitLength, nByteLength };
|
||||
}
|
||||
/**
|
||||
* Creates a finite field. Major performance optimizations:
|
||||
* * 1. Denormalized operations like mulN instead of mul.
|
||||
* * 2. Identical object shape: never add or remove keys.
|
||||
* * 3. `Object.freeze`.
|
||||
* Fragile: always run a benchmark on a change.
|
||||
* Security note: operations don't check 'isValid' for all elements for performance reasons,
|
||||
* it is caller responsibility to check this.
|
||||
* This is low-level code, please make sure you know what you're doing.
|
||||
*
|
||||
* Note about field properties:
|
||||
* * CHARACTERISTIC p = prime number, number of elements in main subgroup.
|
||||
* * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
|
||||
*
|
||||
* @param ORDER field order, probably prime, or could be composite
|
||||
* @param bitLen how many bits the field consumes
|
||||
* @param isLE (default: false) if encoding / decoding should be in little-endian
|
||||
* @param redef optional faster redefinitions of sqrt and other methods
|
||||
*/
|
||||
function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?
|
||||
isLE = false, opts = {}) {
|
||||
if (ORDER <= _0n)
|
||||
throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
|
||||
let _nbitLength = undefined;
|
||||
let _sqrt = undefined;
|
||||
let modFromBytes = false;
|
||||
let allowedLengths = undefined;
|
||||
if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {
|
||||
if (opts.sqrt || isLE)
|
||||
throw new Error('cannot specify opts in two arguments');
|
||||
const _opts = bitLenOrOpts;
|
||||
if (_opts.BITS)
|
||||
_nbitLength = _opts.BITS;
|
||||
if (_opts.sqrt)
|
||||
_sqrt = _opts.sqrt;
|
||||
if (typeof _opts.isLE === 'boolean')
|
||||
isLE = _opts.isLE;
|
||||
if (typeof _opts.modFromBytes === 'boolean')
|
||||
modFromBytes = _opts.modFromBytes;
|
||||
allowedLengths = _opts.allowedLengths;
|
||||
}
|
||||
else {
|
||||
if (typeof bitLenOrOpts === 'number')
|
||||
_nbitLength = bitLenOrOpts;
|
||||
if (opts.sqrt)
|
||||
_sqrt = opts.sqrt;
|
||||
}
|
||||
const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
|
||||
if (BYTES > 2048)
|
||||
throw new Error('invalid field: expected ORDER of <= 2048 bytes');
|
||||
let sqrtP; // cached sqrtP
|
||||
const f = Object.freeze({
|
||||
ORDER,
|
||||
isLE,
|
||||
BITS,
|
||||
BYTES,
|
||||
MASK: (0, utils_ts_1.bitMask)(BITS),
|
||||
ZERO: _0n,
|
||||
ONE: _1n,
|
||||
allowedLengths: allowedLengths,
|
||||
create: (num) => mod(num, ORDER),
|
||||
isValid: (num) => {
|
||||
if (typeof num !== 'bigint')
|
||||
throw new Error('invalid field element: expected bigint, got ' + typeof num);
|
||||
return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
|
||||
},
|
||||
is0: (num) => num === _0n,
|
||||
// is valid and invertible
|
||||
isValidNot0: (num) => !f.is0(num) && f.isValid(num),
|
||||
isOdd: (num) => (num & _1n) === _1n,
|
||||
neg: (num) => mod(-num, ORDER),
|
||||
eql: (lhs, rhs) => lhs === rhs,
|
||||
sqr: (num) => mod(num * num, ORDER),
|
||||
add: (lhs, rhs) => mod(lhs + rhs, ORDER),
|
||||
sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
|
||||
mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
|
||||
pow: (num, power) => FpPow(f, num, power),
|
||||
div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
|
||||
// Same as above, but doesn't normalize
|
||||
sqrN: (num) => num * num,
|
||||
addN: (lhs, rhs) => lhs + rhs,
|
||||
subN: (lhs, rhs) => lhs - rhs,
|
||||
mulN: (lhs, rhs) => lhs * rhs,
|
||||
inv: (num) => invert(num, ORDER),
|
||||
sqrt: _sqrt ||
|
||||
((n) => {
|
||||
if (!sqrtP)
|
||||
sqrtP = FpSqrt(ORDER);
|
||||
return sqrtP(f, n);
|
||||
}),
|
||||
toBytes: (num) => (isLE ? (0, utils_ts_1.numberToBytesLE)(num, BYTES) : (0, utils_ts_1.numberToBytesBE)(num, BYTES)),
|
||||
fromBytes: (bytes, skipValidation = true) => {
|
||||
if (allowedLengths) {
|
||||
if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
|
||||
throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
|
||||
}
|
||||
const padded = new Uint8Array(BYTES);
|
||||
// isLE add 0 to right, !isLE to the left.
|
||||
padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
|
||||
bytes = padded;
|
||||
}
|
||||
if (bytes.length !== BYTES)
|
||||
throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
|
||||
let scalar = isLE ? (0, utils_ts_1.bytesToNumberLE)(bytes) : (0, utils_ts_1.bytesToNumberBE)(bytes);
|
||||
if (modFromBytes)
|
||||
scalar = mod(scalar, ORDER);
|
||||
if (!skipValidation)
|
||||
if (!f.isValid(scalar))
|
||||
throw new Error('invalid field element: outside of range 0..ORDER');
|
||||
// NOTE: we don't validate scalar here, please use isValid. This done such way because some
|
||||
// protocol may allow non-reduced scalar that reduced later or changed some other way.
|
||||
return scalar;
|
||||
},
|
||||
// TODO: we don't need it here, move out to separate fn
|
||||
invertBatch: (lst) => FpInvertBatch(f, lst),
|
||||
// We can't move this out because Fp6, Fp12 implement it
|
||||
// and it's unclear what to return in there.
|
||||
cmov: (a, b, c) => (c ? b : a),
|
||||
});
|
||||
return Object.freeze(f);
|
||||
}
|
||||
// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?
|
||||
// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).
|
||||
// which mean we cannot force this via opts.
|
||||
// Not sure what to do with randomBytes, we can accept it inside opts if wanted.
|
||||
// Probably need to export getMinHashLength somewhere?
|
||||
// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {
|
||||
// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;
|
||||
// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?
|
||||
// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
||||
// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
|
||||
// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;
|
||||
// return reduced;
|
||||
// },
|
||||
function FpSqrtOdd(Fp, elm) {
|
||||
if (!Fp.isOdd)
|
||||
throw new Error("Field doesn't have isOdd");
|
||||
const root = Fp.sqrt(elm);
|
||||
return Fp.isOdd(root) ? root : Fp.neg(root);
|
||||
}
|
||||
function FpSqrtEven(Fp, elm) {
|
||||
if (!Fp.isOdd)
|
||||
throw new Error("Field doesn't have isOdd");
|
||||
const root = Fp.sqrt(elm);
|
||||
return Fp.isOdd(root) ? Fp.neg(root) : root;
|
||||
}
|
||||
/**
|
||||
* "Constant-time" private key generation utility.
|
||||
* Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
|
||||
* Which makes it slightly more biased, less secure.
|
||||
* @deprecated use `mapKeyToField` instead
|
||||
*/
|
||||
function hashToPrivateScalar(hash, groupOrder, isLE = false) {
|
||||
hash = (0, utils_ts_1.ensureBytes)('privateHash', hash);
|
||||
const hashLen = hash.length;
|
||||
const minLen = nLength(groupOrder).nByteLength + 8;
|
||||
if (minLen < 24 || hashLen < minLen || hashLen > 1024)
|
||||
throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);
|
||||
const num = isLE ? (0, utils_ts_1.bytesToNumberLE)(hash) : (0, utils_ts_1.bytesToNumberBE)(hash);
|
||||
return mod(num, groupOrder - _1n) + _1n;
|
||||
}
|
||||
/**
|
||||
* Returns total number of bytes consumed by the field element.
|
||||
* For example, 32 bytes for usual 256-bit weierstrass curve.
|
||||
* @param fieldOrder number of field elements, usually CURVE.n
|
||||
* @returns byte length of field
|
||||
*/
|
||||
function getFieldBytesLength(fieldOrder) {
|
||||
if (typeof fieldOrder !== 'bigint')
|
||||
throw new Error('field order must be bigint');
|
||||
const bitLength = fieldOrder.toString(2).length;
|
||||
return Math.ceil(bitLength / 8);
|
||||
}
|
||||
/**
|
||||
* Returns minimal amount of bytes that can be safely reduced
|
||||
* by field order.
|
||||
* Should be 2^-128 for 128-bit curve such as P256.
|
||||
* @param fieldOrder number of field elements, usually CURVE.n
|
||||
* @returns byte length of target hash
|
||||
*/
|
||||
function getMinHashLength(fieldOrder) {
|
||||
const length = getFieldBytesLength(fieldOrder);
|
||||
return length + Math.ceil(length / 2);
|
||||
}
|
||||
/**
|
||||
* "Constant-time" private key generation utility.
|
||||
* Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
|
||||
* and convert them into private scalar, with the modulo bias being negligible.
|
||||
* Needs at least 48 bytes of input for 32-byte private key.
|
||||
* https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
|
||||
* FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
|
||||
* RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
|
||||
* @param hash hash output from SHA3 or a similar function
|
||||
* @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
|
||||
* @param isLE interpret hash bytes as LE num
|
||||
* @returns valid private scalar
|
||||
*/
|
||||
function mapHashToField(key, fieldOrder, isLE = false) {
|
||||
const len = key.length;
|
||||
const fieldLen = getFieldBytesLength(fieldOrder);
|
||||
const minLen = getMinHashLength(fieldOrder);
|
||||
// No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
|
||||
if (len < 16 || len < minLen || len > 1024)
|
||||
throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
|
||||
const num = isLE ? (0, utils_ts_1.bytesToNumberLE)(key) : (0, utils_ts_1.bytesToNumberBE)(key);
|
||||
// `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
|
||||
const reduced = mod(num, fieldOrder - _1n) + _1n;
|
||||
return isLE ? (0, utils_ts_1.numberToBytesLE)(reduced, fieldLen) : (0, utils_ts_1.numberToBytesBE)(reduced, fieldLen);
|
||||
}
|
||||
//# sourceMappingURL=modular.js.map
|
||||
@@ -0,0 +1,299 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
const util_1 = require("../util");
|
||||
const getMemberHeadLoc_1 = require("../util/getMemberHeadLoc");
|
||||
const rangeToLoc_1 = require("../util/rangeToLoc");
|
||||
exports.default = (0, util_1.createRule)({
|
||||
name: 'explicit-member-accessibility',
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Require explicit accessibility modifiers on class properties and methods',
|
||||
// too opinionated to be recommended
|
||||
},
|
||||
fixable: 'code',
|
||||
hasSuggestions: true,
|
||||
messages: {
|
||||
addExplicitAccessibility: "Add '{{ type }}' accessibility modifier",
|
||||
missingAccessibility: 'Missing accessibility modifier on {{type}} {{name}}.',
|
||||
unwantedPublicAccessibility: 'Public accessibility modifier on {{type}} {{name}}.',
|
||||
},
|
||||
schema: [
|
||||
{
|
||||
type: 'object',
|
||||
$defs: {
|
||||
accessibilityLevel: {
|
||||
oneOf: [
|
||||
{
|
||||
type: 'string',
|
||||
description: 'Always require an accessor.',
|
||||
enum: ['explicit'],
|
||||
},
|
||||
{
|
||||
type: 'string',
|
||||
description: 'Require an accessor except when public.',
|
||||
enum: ['no-public'],
|
||||
},
|
||||
{
|
||||
type: 'string',
|
||||
description: 'Never check whether there is an accessor.',
|
||||
enum: ['off'],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
accessibility: {
|
||||
$ref: '#/items/0/$defs/accessibilityLevel',
|
||||
description: 'Which accessibility modifier is required to exist or not exist.',
|
||||
},
|
||||
ignoredMethodNames: {
|
||||
type: 'array',
|
||||
description: 'Specific method names that may be ignored.',
|
||||
items: {
|
||||
type: 'string',
|
||||
},
|
||||
},
|
||||
overrides: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
description: 'Changes to required accessibility modifiers for specific kinds of class members.',
|
||||
properties: {
|
||||
accessors: {
|
||||
$ref: '#/items/0/$defs/accessibilityLevel',
|
||||
description: 'Which member accessibility modifier requirements to apply for accessors.',
|
||||
},
|
||||
constructors: {
|
||||
$ref: '#/items/0/$defs/accessibilityLevel',
|
||||
description: 'Which member accessibility modifier requirements to apply for constructors.',
|
||||
},
|
||||
methods: {
|
||||
$ref: '#/items/0/$defs/accessibilityLevel',
|
||||
description: 'Which member accessibility modifier requirements to apply for methods.',
|
||||
},
|
||||
parameterProperties: {
|
||||
$ref: '#/items/0/$defs/accessibilityLevel',
|
||||
description: 'Which member accessibility modifier requirements to apply for parameterProperties.',
|
||||
},
|
||||
properties: {
|
||||
$ref: '#/items/0/$defs/accessibilityLevel',
|
||||
description: 'Which member accessibility modifier requirements to apply for properties.',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
defaultOptions: [{ accessibility: 'explicit' }],
|
||||
create(context, [option]) {
|
||||
const baseCheck = option.accessibility ?? 'explicit';
|
||||
const overrides = option.overrides ?? {};
|
||||
const ctorCheck = overrides.constructors ?? baseCheck;
|
||||
const accessorCheck = overrides.accessors ?? baseCheck;
|
||||
const methodCheck = overrides.methods ?? baseCheck;
|
||||
const propCheck = overrides.properties ?? baseCheck;
|
||||
const paramPropCheck = overrides.parameterProperties ?? baseCheck;
|
||||
const ignoredMethodNames = new Set(option.ignoredMethodNames ?? []);
|
||||
/**
|
||||
* Checks if a method declaration has an accessibility modifier.
|
||||
* @param methodDefinition The node representing a MethodDefinition.
|
||||
*/
|
||||
function checkMethodAccessibilityModifier(methodDefinition) {
|
||||
if (methodDefinition.key.type === utils_1.AST_NODE_TYPES.PrivateIdentifier) {
|
||||
return;
|
||||
}
|
||||
let nodeType = 'method definition';
|
||||
let check = baseCheck;
|
||||
switch (methodDefinition.kind) {
|
||||
case 'method':
|
||||
check = methodCheck;
|
||||
break;
|
||||
case 'constructor':
|
||||
check = ctorCheck;
|
||||
break;
|
||||
case 'get':
|
||||
case 'set':
|
||||
check = accessorCheck;
|
||||
nodeType = `${methodDefinition.kind} property accessor`;
|
||||
break;
|
||||
}
|
||||
const { name: methodName } = (0, util_1.getNameFromMember)(methodDefinition, context.sourceCode);
|
||||
if (check === 'off' || ignoredMethodNames.has(methodName)) {
|
||||
return;
|
||||
}
|
||||
if (check === 'no-public' &&
|
||||
methodDefinition.accessibility === 'public') {
|
||||
const publicKeyword = findPublicKeyword(methodDefinition);
|
||||
context.report({
|
||||
loc: (0, rangeToLoc_1.rangeToLoc)(context.sourceCode, publicKeyword.range),
|
||||
messageId: 'unwantedPublicAccessibility',
|
||||
data: {
|
||||
name: methodName,
|
||||
type: nodeType,
|
||||
},
|
||||
fix: fixer => fixer.removeRange(publicKeyword.rangeToRemove),
|
||||
});
|
||||
}
|
||||
else if (check === 'explicit' && !methodDefinition.accessibility) {
|
||||
context.report({
|
||||
loc: (0, getMemberHeadLoc_1.getMemberHeadLoc)(context.sourceCode, methodDefinition),
|
||||
messageId: 'missingAccessibility',
|
||||
data: {
|
||||
name: methodName,
|
||||
type: nodeType,
|
||||
},
|
||||
suggest: getMissingAccessibilitySuggestions(methodDefinition),
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Returns an object containing a range that corresponds to the "public"
|
||||
* keyword for a node, and the range that would need to be removed to
|
||||
* remove the "public" keyword (including associated whitespace).
|
||||
*/
|
||||
function findPublicKeyword(node) {
|
||||
const tokens = context.sourceCode.getTokens(node);
|
||||
let rangeToRemove;
|
||||
let keywordRange;
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
const token = tokens[i];
|
||||
if (token.type === utils_1.AST_TOKEN_TYPES.Keyword &&
|
||||
token.value === 'public') {
|
||||
keywordRange = structuredClone(token.range);
|
||||
const commentsAfterPublicKeyword = context.sourceCode.getCommentsAfter(token);
|
||||
if (commentsAfterPublicKeyword.length) {
|
||||
// public /* Hi there! */ static foo()
|
||||
// ^^^^^^^
|
||||
rangeToRemove = [
|
||||
token.range[0],
|
||||
commentsAfterPublicKeyword[0].range[0],
|
||||
];
|
||||
break;
|
||||
}
|
||||
else {
|
||||
// public static foo()
|
||||
// ^^^^^^^
|
||||
rangeToRemove = [token.range[0], tokens[i + 1].range[0]];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return { range: keywordRange, rangeToRemove };
|
||||
}
|
||||
/**
|
||||
* Creates a fixer that adds an accessibility modifier keyword
|
||||
*/
|
||||
function getMissingAccessibilitySuggestions(node) {
|
||||
function fix(accessibility, fixer) {
|
||||
if (node.decorators.length) {
|
||||
const lastDecorator = node.decorators[node.decorators.length - 1];
|
||||
const nextToken = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(lastDecorator), util_1.NullThrowsReasons.MissingToken('token', 'last decorator'));
|
||||
return fixer.insertTextBefore(nextToken, `${accessibility} `);
|
||||
}
|
||||
return fixer.insertTextBefore(node, `${accessibility} `);
|
||||
}
|
||||
return [
|
||||
{
|
||||
messageId: 'addExplicitAccessibility',
|
||||
data: { type: 'public' },
|
||||
fix: fixer => fix('public', fixer),
|
||||
},
|
||||
{
|
||||
messageId: 'addExplicitAccessibility',
|
||||
data: { type: 'private' },
|
||||
fix: fixer => fix('private', fixer),
|
||||
},
|
||||
{
|
||||
messageId: 'addExplicitAccessibility',
|
||||
data: { type: 'protected' },
|
||||
fix: fixer => fix('protected', fixer),
|
||||
},
|
||||
];
|
||||
}
|
||||
/**
|
||||
* Checks if property has an accessibility modifier.
|
||||
* @param propertyDefinition The node representing a PropertyDefinition.
|
||||
*/
|
||||
function checkPropertyAccessibilityModifier(propertyDefinition) {
|
||||
if (propertyDefinition.key.type === utils_1.AST_NODE_TYPES.PrivateIdentifier) {
|
||||
return;
|
||||
}
|
||||
const nodeType = 'class property';
|
||||
const { name: propertyName } = (0, util_1.getNameFromMember)(propertyDefinition, context.sourceCode);
|
||||
if (propCheck === 'no-public' &&
|
||||
propertyDefinition.accessibility === 'public') {
|
||||
const publicKeywordRange = findPublicKeyword(propertyDefinition);
|
||||
context.report({
|
||||
loc: (0, rangeToLoc_1.rangeToLoc)(context.sourceCode, publicKeywordRange.range),
|
||||
messageId: 'unwantedPublicAccessibility',
|
||||
data: {
|
||||
name: propertyName,
|
||||
type: nodeType,
|
||||
},
|
||||
fix: fixer => fixer.removeRange(publicKeywordRange.rangeToRemove),
|
||||
});
|
||||
}
|
||||
else if (propCheck === 'explicit' &&
|
||||
!propertyDefinition.accessibility) {
|
||||
context.report({
|
||||
loc: (0, getMemberHeadLoc_1.getMemberHeadLoc)(context.sourceCode, propertyDefinition),
|
||||
messageId: 'missingAccessibility',
|
||||
data: {
|
||||
name: propertyName,
|
||||
type: nodeType,
|
||||
},
|
||||
suggest: getMissingAccessibilitySuggestions(propertyDefinition),
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Checks that the parameter property has the desired accessibility modifiers set.
|
||||
* @param node The node representing a Parameter Property
|
||||
*/
|
||||
function checkParameterPropertyAccessibilityModifier(node) {
|
||||
const nodeType = 'parameter property';
|
||||
const nodeName = node.parameter.type === utils_1.AST_NODE_TYPES.Identifier
|
||||
? node.parameter.name
|
||||
: node.parameter.left.name;
|
||||
switch (paramPropCheck) {
|
||||
case 'explicit': {
|
||||
if (!node.accessibility) {
|
||||
context.report({
|
||||
loc: (0, getMemberHeadLoc_1.getParameterPropertyHeadLoc)(context.sourceCode, node, nodeName),
|
||||
messageId: 'missingAccessibility',
|
||||
data: {
|
||||
name: nodeName,
|
||||
type: nodeType,
|
||||
},
|
||||
suggest: getMissingAccessibilitySuggestions(node),
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'no-public': {
|
||||
if (node.accessibility === 'public' && node.readonly) {
|
||||
const publicKeyword = findPublicKeyword(node);
|
||||
context.report({
|
||||
loc: (0, rangeToLoc_1.rangeToLoc)(context.sourceCode, publicKeyword.range),
|
||||
messageId: 'unwantedPublicAccessibility',
|
||||
data: {
|
||||
name: nodeName,
|
||||
type: nodeType,
|
||||
},
|
||||
fix: fixer => fixer.removeRange(publicKeyword.rangeToRemove),
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
'MethodDefinition, TSAbstractMethodDefinition': checkMethodAccessibilityModifier,
|
||||
'PropertyDefinition, TSAbstractPropertyDefinition, AccessorProperty, TSAbstractAccessorProperty': checkPropertyAccessibilityModifier,
|
||||
TSParameterProperty: checkParameterPropertyAccessibilityModifier,
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { Codec, Decoder, Encoder, FixedSizeCodec, FixedSizeDecoder, FixedSizeEncoder } from './codec';
|
||||
/**
|
||||
* Creates a fixed-size encoder from a given encoder.
|
||||
*
|
||||
* The resulting encoder ensures that encoded values always have the specified number of bytes.
|
||||
* If the original encoded value is larger than `fixedBytes`, it is truncated.
|
||||
* If it is smaller, it is padded with trailing zeroes.
|
||||
*
|
||||
* For more details, see {@link fixCodecSize}.
|
||||
*
|
||||
* @typeParam TFrom - The type of the value to encode.
|
||||
* @typeParam TSize - The fixed size of the encoded value in bytes.
|
||||
*
|
||||
* @param encoder - The encoder to wrap into a fixed-size encoder.
|
||||
* @param fixedBytes - The fixed number of bytes to write.
|
||||
* @returns A `FixedSizeEncoder` that ensures a consistent output size.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const encoder = fixEncoderSize(getUtf8Encoder(), 4);
|
||||
* encoder.encode("Hello"); // 0x48656c6c (truncated)
|
||||
* encoder.encode("Hi"); // 0x48690000 (padded)
|
||||
* encoder.encode("Hiya"); // 0x48697961 (same length)
|
||||
* ```
|
||||
*
|
||||
* @remarks
|
||||
* If you need a full codec with both encoding and decoding, use {@link fixCodecSize}.
|
||||
*
|
||||
* @see {@link fixCodecSize}
|
||||
* @see {@link fixDecoderSize}
|
||||
*/
|
||||
export declare function fixEncoderSize<TFrom, TSize extends number>(encoder: Encoder<TFrom>, fixedBytes: TSize): FixedSizeEncoder<TFrom, TSize>;
|
||||
/**
|
||||
* Creates a fixed-size decoder from a given decoder.
|
||||
*
|
||||
* The resulting decoder always reads exactly `fixedBytes` bytes from the input.
|
||||
* If the nested decoder is also fixed-size, the bytes are truncated or padded as needed.
|
||||
*
|
||||
* For more details, see {@link fixCodecSize}.
|
||||
*
|
||||
* @typeParam TTo - The type of the decoded value.
|
||||
* @typeParam TSize - The fixed size of the encoded value in bytes.
|
||||
*
|
||||
* @param decoder - The decoder to wrap into a fixed-size decoder.
|
||||
* @param fixedBytes - The fixed number of bytes to read.
|
||||
* @returns A `FixedSizeDecoder` that ensures a consistent input size.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const decoder = fixDecoderSize(getUtf8Decoder(), 4);
|
||||
* decoder.decode(new Uint8Array([72, 101, 108, 108, 111])); // "Hell" (truncated)
|
||||
* decoder.decode(new Uint8Array([72, 105, 0, 0])); // "Hi" (zeroes ignored)
|
||||
* decoder.decode(new Uint8Array([72, 105, 121, 97])); // "Hiya" (same length)
|
||||
* ```
|
||||
*
|
||||
* @remarks
|
||||
* If you need a full codec with both encoding and decoding, use {@link fixCodecSize}.
|
||||
*
|
||||
* @see {@link fixCodecSize}
|
||||
* @see {@link fixEncoderSize}
|
||||
*/
|
||||
export declare function fixDecoderSize<TTo, TSize extends number>(decoder: Decoder<TTo>, fixedBytes: TSize): FixedSizeDecoder<TTo, TSize>;
|
||||
/**
|
||||
* Creates a fixed-size codec from a given codec.
|
||||
*
|
||||
* The resulting codec ensures that both encoding and decoding operate on a fixed number of bytes.
|
||||
* When encoding:
|
||||
* - If the encoded value is larger than `fixedBytes`, it is truncated.
|
||||
* - If it is smaller, it is padded with trailing zeroes.
|
||||
* - If it is exactly `fixedBytes`, it remains unchanged.
|
||||
*
|
||||
* When decoding:
|
||||
* - Exactly `fixedBytes` bytes are read from the input.
|
||||
* - If the nested decoder has a smaller fixed size, bytes are truncated or padded as necessary.
|
||||
*
|
||||
* @typeParam TFrom - The type of the value to encode.
|
||||
* @typeParam TTo - The type of the decoded value.
|
||||
* @typeParam TSize - The fixed size of the encoded value in bytes.
|
||||
*
|
||||
* @param codec - The codec to wrap into a fixed-size codec.
|
||||
* @param fixedBytes - The fixed number of bytes to read/write.
|
||||
* @returns A `FixedSizeCodec` that ensures both encoding and decoding conform to a fixed size.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const codec = fixCodecSize(getUtf8Codec(), 4);
|
||||
*
|
||||
* const bytes1 = codec.encode("Hello"); // 0x48656c6c (truncated)
|
||||
* const value1 = codec.decode(bytes1); // "Hell"
|
||||
*
|
||||
* const bytes2 = codec.encode("Hi"); // 0x48690000 (padded)
|
||||
* const value2 = codec.decode(bytes2); // "Hi"
|
||||
*
|
||||
* const bytes3 = codec.encode("Hiya"); // 0x48697961 (same length)
|
||||
* const value3 = codec.decode(bytes3); // "Hiya"
|
||||
* ```
|
||||
*
|
||||
* @remarks
|
||||
* If you only need to enforce a fixed size for encoding, use {@link fixEncoderSize}.
|
||||
* If you only need to enforce a fixed size for decoding, use {@link fixDecoderSize}.
|
||||
*
|
||||
* ```ts
|
||||
* const bytes = fixEncoderSize(getUtf8Encoder(), 4).encode("Hiya");
|
||||
* const value = fixDecoderSize(getUtf8Decoder(), 4).decode(bytes);
|
||||
* ```
|
||||
*
|
||||
* @see {@link fixEncoderSize}
|
||||
* @see {@link fixDecoderSize}
|
||||
*/
|
||||
export declare function fixCodecSize<TFrom, TTo extends TFrom, TSize extends number>(codec: Codec<TFrom, TTo>, fixedBytes: TSize): FixedSizeCodec<TFrom, TTo, TSize>;
|
||||
//# sourceMappingURL=fix-codec-size.d.ts.map
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
|
||||
interface WrappingFixerParams {
|
||||
/**
|
||||
* Descendant of `node` we want to preserve.
|
||||
* Use this to replace some code with another.
|
||||
* By default it's the node we are modifying (so nothing is removed).
|
||||
* You can pass multiple nodes as an array.
|
||||
*/
|
||||
innerNode?: TSESTree.Node | TSESTree.Node[];
|
||||
/** The node we want to modify. */
|
||||
node: TSESTree.Node;
|
||||
/** Source code. */
|
||||
sourceCode: Readonly<TSESLint.SourceCode>;
|
||||
/**
|
||||
* The function which gets the code of the `innerNode` and returns some code around it.
|
||||
* Receives multiple arguments if there are multiple innerNodes.
|
||||
* E.g. ``code => `${code} != null` ``
|
||||
*/
|
||||
wrap?: (...code: string[]) => string;
|
||||
}
|
||||
/**
|
||||
* Wraps node with some code. Adds parentheses as necessary.
|
||||
* @returns Fixer which adds the specified code and parens if necessary.
|
||||
*/
|
||||
export declare function getWrappingFixer(params: WrappingFixerParams): (fixer: TSESLint.RuleFixer) => TSESLint.RuleFix;
|
||||
/**
|
||||
* If the node to be moved and the destination node require parentheses, include parentheses in the node to be moved.
|
||||
* @param sourceCode Source code of current file
|
||||
* @param nodeToMove Nodes that need to be moved
|
||||
* @param destinationNode Final destination node with nodeToMove
|
||||
* @returns If parentheses are required, code for the nodeToMove node is returned with parentheses at both ends of the code.
|
||||
*/
|
||||
export declare function getMovedNodeCode(params: {
|
||||
destinationNode: TSESTree.Node;
|
||||
nodeToMove: TSESTree.Node;
|
||||
sourceCode: Readonly<TSESLint.SourceCode>;
|
||||
}): string;
|
||||
/**
|
||||
* Check if a node will always have the same precedence if its parent changes.
|
||||
*/
|
||||
export declare function isStrongPrecedenceNode(innerNode: TSESTree.Node): boolean;
|
||||
/**
|
||||
* Check if a node's parent could have different precedence if the node changes.
|
||||
*/
|
||||
export declare function isWeakPrecedenceParent(node: TSESTree.Node): boolean;
|
||||
export {};
|
||||
@@ -0,0 +1,86 @@
|
||||
"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 tsutils = __importStar(require("ts-api-utils"));
|
||||
const ts = __importStar(require("typescript"));
|
||||
const util_1 = require("../util");
|
||||
const getForStatementHeadLoc_1 = require("../util/getForStatementHeadLoc");
|
||||
exports.default = (0, util_1.createRule)({
|
||||
name: 'no-for-in-array',
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Disallow iterating over an array with a for-in loop',
|
||||
recommended: 'recommended',
|
||||
requiresTypeChecking: true,
|
||||
},
|
||||
messages: {
|
||||
forInViolation: 'For-in loops over arrays skips holes, returns indices as strings, and may visit the prototype chain or other enumerable properties. Use a more robust iteration method such as for-of or array.forEach instead.',
|
||||
},
|
||||
schema: [],
|
||||
},
|
||||
defaultOptions: [],
|
||||
create(context) {
|
||||
return {
|
||||
ForInStatement(node) {
|
||||
const services = (0, util_1.getParserServices)(context);
|
||||
const checker = services.program.getTypeChecker();
|
||||
const type = (0, util_1.getConstrainedTypeAtLocation)(services, node.right);
|
||||
if (isArrayLike(checker, type)) {
|
||||
context.report({
|
||||
loc: (0, getForStatementHeadLoc_1.getForStatementHeadLoc)(context.sourceCode, node),
|
||||
messageId: 'forInViolation',
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
function isArrayLike(checker, type) {
|
||||
return isTypeRecurser(type, t => t.getNumberIndexType() != null && hasArrayishLength(checker, t));
|
||||
}
|
||||
function hasArrayishLength(checker, type) {
|
||||
const lengthProperty = type.getProperty('length');
|
||||
if (lengthProperty == null) {
|
||||
return false;
|
||||
}
|
||||
return tsutils.isTypeFlagSet(checker.getTypeOfSymbol(lengthProperty), ts.TypeFlags.NumberLike);
|
||||
}
|
||||
function isTypeRecurser(type, predicate) {
|
||||
if (type.isUnionOrIntersection()) {
|
||||
return type.types.some(t => isTypeRecurser(t, predicate));
|
||||
}
|
||||
return predicate(type);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"espree.d.ts","sourceRoot":"","sources":["../espree.js"],"names":[],"mappings":"AAuNA;;;;;;;GAOG;AACH,+BANW,MAAM,YACN,OAAO,GACL,YAAY,CAaxB;AAMD;;;;;;GAMG;AACH,4BALW,MAAM,YACN,OAAO,GACL,KAAK,CAAC,OAAO,CAOzB;AAMD,qBAAqB;AACrB,sBADW,MAAM,CACe;AAChC,mBAAoB,QAAQ,CAAC;AAG7B,4CAoBK;AAEL,mCAAwE;AAExE,uFAAgF;;0BAlNnE,CAAC,GAAC,CAAC,GAAC,CAAC,GAAC,CAAC,GAAC,CAAC,GAAC,CAAC,GAAC,EAAE,GAAC,EAAE,GAAC,EAAE,GAAC,EAAE,GAAC,EAAE,GAAC,EAAE,GAAC,EAAE,GAAC,EAAE,GAAC,IAAI,GAAC,IAAI,GAAC,IAAI,GAAC,IAAI,GAAC,IAAI,GAAC,IAAI,GAAC,IAAI,GAAC,IAAI,GAAC,IAAI,GAAC,IAAI,GAAC,IAAI,GAAC,IAAI,GAAC,QAAQ;0BAIxG;IACR,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,GAAG,CAAC;IACX,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC;IAC3B,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACzB,KAAK,CAAC,EAAE;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAC,CAAC;CAC1C;4BAIS;IACR,IAAI,EAAE,OAAO,GAAG,UAAU,GAAG,MAAM,CAAC;IACpC,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE;QACJ,KAAK,EAAE,KAAK,CAAC,QAAQ,GAAG,SAAS,CAAC;QAClC,GAAG,EAAE,KAAK,CAAC,QAAQ,GAAG,SAAS,CAAA;KAChC,CAAA;CACF;2BAIS;IACR,QAAQ,CAAC,EAAE,aAAa,EAAE,CAAA;CAC3B,GAAG,WAAW,EAAE;sBAeP;IACR,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,UAAU,CAAC,EAAE,QAAQ,GAAC,QAAQ,GAAC,UAAU,CAAC;IAC1C,YAAY,CAAC,EAAE;QACb,GAAG,CAAC,EAAE,OAAO,CAAC;QACd,YAAY,CAAC,EAAE,OAAO,CAAC;QACvB,aAAa,CAAC,EAAE,OAAO,CAAA;KACxB,CAAC;IACF,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,GAAG,CAAC,EAAE,OAAO,CAAC;IACd,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;uBA7EmB,OAAO"}
|
||||
@@ -0,0 +1,323 @@
|
||||
//#region src/utils.ts
|
||||
const postfixRE = /[?#].*$/;
|
||||
function cleanUrl(url) {
|
||||
return url.replace(postfixRE, "");
|
||||
}
|
||||
function extractQueryWithoutFragment(url) {
|
||||
const questionMarkIndex = url.indexOf("?");
|
||||
if (questionMarkIndex === -1) return "";
|
||||
const fragmentIndex = url.indexOf("#", questionMarkIndex);
|
||||
if (fragmentIndex === -1) return url.substring(questionMarkIndex);
|
||||
else return url.substring(questionMarkIndex, fragmentIndex);
|
||||
}
|
||||
//#endregion
|
||||
//#region src/filter/composable-filters.ts
|
||||
var And = class {
|
||||
kind;
|
||||
args;
|
||||
constructor(...args) {
|
||||
if (args.length === 0) throw new Error("`And` expects at least one operand");
|
||||
this.args = args;
|
||||
this.kind = "and";
|
||||
}
|
||||
};
|
||||
var Or = class {
|
||||
kind;
|
||||
args;
|
||||
constructor(...args) {
|
||||
if (args.length === 0) throw new Error("`Or` expects at least one operand");
|
||||
this.args = args;
|
||||
this.kind = "or";
|
||||
}
|
||||
};
|
||||
var Not = class {
|
||||
kind;
|
||||
expr;
|
||||
constructor(expr) {
|
||||
this.expr = expr;
|
||||
this.kind = "not";
|
||||
}
|
||||
};
|
||||
var Id = class {
|
||||
kind;
|
||||
pattern;
|
||||
params;
|
||||
constructor(pattern, params) {
|
||||
this.pattern = pattern;
|
||||
this.kind = "id";
|
||||
this.params = params ?? { cleanUrl: false };
|
||||
}
|
||||
};
|
||||
var ImporterId = class {
|
||||
kind;
|
||||
pattern;
|
||||
params;
|
||||
constructor(pattern, params) {
|
||||
this.pattern = pattern;
|
||||
this.kind = "importerId";
|
||||
this.params = params ?? { cleanUrl: false };
|
||||
}
|
||||
};
|
||||
var ModuleType = class {
|
||||
kind;
|
||||
pattern;
|
||||
constructor(pattern) {
|
||||
this.pattern = pattern;
|
||||
this.kind = "moduleType";
|
||||
}
|
||||
};
|
||||
var Code = class {
|
||||
kind;
|
||||
pattern;
|
||||
constructor(expr) {
|
||||
this.pattern = expr;
|
||||
this.kind = "code";
|
||||
}
|
||||
};
|
||||
var Query = class {
|
||||
kind;
|
||||
key;
|
||||
pattern;
|
||||
constructor(key, pattern) {
|
||||
this.pattern = pattern;
|
||||
this.key = key;
|
||||
this.kind = "query";
|
||||
}
|
||||
};
|
||||
var Include = class {
|
||||
kind;
|
||||
expr;
|
||||
constructor(expr) {
|
||||
this.expr = expr;
|
||||
this.kind = "include";
|
||||
}
|
||||
};
|
||||
var Exclude = class {
|
||||
kind;
|
||||
expr;
|
||||
constructor(expr) {
|
||||
this.expr = expr;
|
||||
this.kind = "exclude";
|
||||
}
|
||||
};
|
||||
function and(...args) {
|
||||
return new And(...args);
|
||||
}
|
||||
function or(...args) {
|
||||
return new Or(...args);
|
||||
}
|
||||
function not(expr) {
|
||||
return new Not(expr);
|
||||
}
|
||||
function id(pattern, params) {
|
||||
return new Id(pattern, params);
|
||||
}
|
||||
function importerId(pattern, params) {
|
||||
return new ImporterId(pattern, params);
|
||||
}
|
||||
function moduleType(pattern) {
|
||||
return new ModuleType(pattern);
|
||||
}
|
||||
function code(pattern) {
|
||||
return new Code(pattern);
|
||||
}
|
||||
function query(key, pattern) {
|
||||
return new Query(key, pattern);
|
||||
}
|
||||
function include(expr) {
|
||||
return new Include(expr);
|
||||
}
|
||||
function exclude(expr) {
|
||||
return new Exclude(expr);
|
||||
}
|
||||
/**
|
||||
* convert a queryObject to FilterExpression like
|
||||
* ```js
|
||||
* and(query(k1, v1), query(k2, v2))
|
||||
* ```
|
||||
* @param queryFilterObject The query filter object needs to be matched.
|
||||
* @returns a `And` FilterExpression
|
||||
*/
|
||||
function queries(queryFilter) {
|
||||
return and(...Object.entries(queryFilter).map(([key, value]) => {
|
||||
return new Query(key, value);
|
||||
}));
|
||||
}
|
||||
function interpreter(exprs, code, id, moduleType, importerId) {
|
||||
let arr = [];
|
||||
if (Array.isArray(exprs)) arr = exprs;
|
||||
else arr = [exprs];
|
||||
return interpreterImpl(arr, code, id, moduleType, importerId);
|
||||
}
|
||||
function interpreterImpl(expr, code, id, moduleType, importerId, ctx = {}) {
|
||||
let hasInclude = false;
|
||||
for (const e of expr) switch (e.kind) {
|
||||
case "include":
|
||||
hasInclude = true;
|
||||
if (exprInterpreter(e.expr, code, id, moduleType, importerId, ctx)) return true;
|
||||
break;
|
||||
case "exclude":
|
||||
if (exprInterpreter(e.expr, code, id, moduleType, importerId, ctx)) return false;
|
||||
break;
|
||||
}
|
||||
return !hasInclude;
|
||||
}
|
||||
function exprInterpreter(expr, code, id, moduleType, importerId, ctx = {}) {
|
||||
switch (expr.kind) {
|
||||
case "and": return expr.args.every((e) => exprInterpreter(e, code, id, moduleType, importerId, ctx));
|
||||
case "or": return expr.args.some((e) => exprInterpreter(e, code, id, moduleType, importerId, ctx));
|
||||
case "not": return !exprInterpreter(expr.expr, code, id, moduleType, importerId, ctx);
|
||||
case "id": {
|
||||
if (id === void 0) throw new Error("`id` is required for `id` expression");
|
||||
let idToMatch = id;
|
||||
if (expr.params.cleanUrl) idToMatch = cleanUrl(idToMatch);
|
||||
return typeof expr.pattern === "string" ? idToMatch === expr.pattern : expr.pattern.test(idToMatch);
|
||||
}
|
||||
case "importerId": {
|
||||
if (importerId === void 0) return false;
|
||||
let importerIdToMatch = importerId;
|
||||
if (expr.params.cleanUrl) importerIdToMatch = cleanUrl(importerIdToMatch);
|
||||
return typeof expr.pattern === "string" ? importerIdToMatch === expr.pattern : expr.pattern.test(importerIdToMatch);
|
||||
}
|
||||
case "moduleType":
|
||||
if (moduleType === void 0) throw new Error("`moduleType` is required for `moduleType` expression");
|
||||
return moduleType === expr.pattern;
|
||||
case "code":
|
||||
if (code === void 0) throw new Error("`code` is required for `code` expression");
|
||||
return typeof expr.pattern === "string" ? code.includes(expr.pattern) : expr.pattern.test(code);
|
||||
case "query": {
|
||||
if (id === void 0) throw new Error("`id` is required for `Query` expression");
|
||||
if (!ctx.urlSearchParamsCache) {
|
||||
let queryString = extractQueryWithoutFragment(id);
|
||||
ctx.urlSearchParamsCache = new URLSearchParams(queryString);
|
||||
}
|
||||
let urlParams = ctx.urlSearchParamsCache;
|
||||
if (typeof expr.pattern === "boolean") if (expr.pattern) return urlParams.has(expr.key);
|
||||
else return !urlParams.has(expr.key);
|
||||
else if (typeof expr.pattern === "string") return urlParams.get(expr.key) === expr.pattern;
|
||||
else return expr.pattern.test(urlParams.get(expr.key) ?? "");
|
||||
}
|
||||
default: throw new Error(`Expression ${JSON.stringify(expr)} is not expected.`);
|
||||
}
|
||||
}
|
||||
//#endregion
|
||||
//#region src/filter/filter-vite-plugins.ts
|
||||
/**
|
||||
* Filters out Vite plugins that have `apply: 'serve'` set.
|
||||
*
|
||||
* Since Rolldown operates in build mode, plugins marked with `apply: 'serve'`
|
||||
* are intended only for Vite's dev server and should be excluded from the build process.
|
||||
*
|
||||
* @param plugins - Array of plugins (can include nested arrays)
|
||||
* @returns Filtered array with serve-only plugins removed
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { defineConfig } from 'rolldown';
|
||||
* import { filterVitePlugins } from '@rolldown/pluginutils';
|
||||
* import viteReact from '@vitejs/plugin-react';
|
||||
*
|
||||
* export default defineConfig({
|
||||
* plugins: filterVitePlugins([
|
||||
* viteReact(),
|
||||
* {
|
||||
* name: 'dev-only',
|
||||
* apply: 'serve', // This will be filtered out
|
||||
* // ...
|
||||
* }
|
||||
* ])
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
function filterVitePlugins(plugins) {
|
||||
if (!plugins) return [];
|
||||
const pluginArray = Array.isArray(plugins) ? plugins : [plugins];
|
||||
const result = [];
|
||||
for (const plugin of pluginArray) {
|
||||
if (!plugin) continue;
|
||||
if (Array.isArray(plugin)) {
|
||||
result.push(...filterVitePlugins(plugin));
|
||||
continue;
|
||||
}
|
||||
const pluginWithApply = plugin;
|
||||
if ("apply" in pluginWithApply) {
|
||||
const applyValue = pluginWithApply.apply;
|
||||
if (typeof applyValue === "function") try {
|
||||
if (applyValue({}, {
|
||||
command: "build",
|
||||
mode: "production"
|
||||
})) result.push(plugin);
|
||||
} catch {
|
||||
result.push(plugin);
|
||||
}
|
||||
else if (applyValue === "serve") continue;
|
||||
else result.push(plugin);
|
||||
} else result.push(plugin);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
//#endregion
|
||||
//#region src/filter/simple-filters.ts
|
||||
/**
|
||||
* Constructs a RegExp that matches the exact string specified.
|
||||
*
|
||||
* This is useful for plugin hook filters.
|
||||
*
|
||||
* @param str the string to match.
|
||||
* @param flags flags for the RegExp.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { exactRegex } from '@rolldown/pluginutils';
|
||||
* const plugin = {
|
||||
* name: 'plugin',
|
||||
* resolveId: {
|
||||
* filter: { id: exactRegex('foo') },
|
||||
* handler(id) {} // will only be called for `foo`
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
function exactRegex(str, flags) {
|
||||
return new RegExp(`^${escapeRegex(str)}$`, flags);
|
||||
}
|
||||
/**
|
||||
* Constructs a RegExp that matches a value that has the specified prefix.
|
||||
*
|
||||
* This is useful for plugin hook filters.
|
||||
*
|
||||
* @param str the string to match.
|
||||
* @param flags flags for the RegExp.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { prefixRegex } from '@rolldown/pluginutils';
|
||||
* const plugin = {
|
||||
* name: 'plugin',
|
||||
* resolveId: {
|
||||
* filter: { id: prefixRegex('foo') },
|
||||
* handler(id) {} // will only be called for IDs starting with `foo`
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
function prefixRegex(str, flags) {
|
||||
return new RegExp(`^${escapeRegex(str)}`, flags);
|
||||
}
|
||||
const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g;
|
||||
function escapeRegex(str) {
|
||||
return str.replace(escapeRegexRE, "\\$&");
|
||||
}
|
||||
function makeIdFiltersToMatchWithQuery(input) {
|
||||
if (!Array.isArray(input)) return makeIdFilterToMatchWithQuery(input);
|
||||
return input.map((i) => makeIdFilterToMatchWithQuery(i));
|
||||
}
|
||||
function makeIdFilterToMatchWithQuery(input) {
|
||||
if (typeof input === "string") return `${input}{?*,}`;
|
||||
return makeRegexIdFilterToMatchWithQuery(input);
|
||||
}
|
||||
function makeRegexIdFilterToMatchWithQuery(input) {
|
||||
return new RegExp(input.source.replace(/(?<!\\)\$/g, "(?:\\?.*)?$"), input.flags);
|
||||
}
|
||||
//#endregion
|
||||
export { queries as _, and as a, exprInterpreter as c, include as d, interpreter as f, or as g, not as h, filterVitePlugins as i, id as l, moduleType as m, makeIdFiltersToMatchWithQuery as n, code as o, interpreterImpl as p, prefixRegex as r, exclude as s, exactRegex as t, importerId as u, query as v };
|
||||
@@ -0,0 +1,132 @@
|
||||
'use strict'
|
||||
|
||||
const { test } = require('node:test')
|
||||
const getColorizer = require('./colors')
|
||||
|
||||
const testDefaultColorizer = getColorizer => t => {
|
||||
const colorizer = getColorizer()
|
||||
let colorized = colorizer(10)
|
||||
t.assert.strictEqual(colorized, 'TRACE')
|
||||
|
||||
colorized = colorizer(20)
|
||||
t.assert.strictEqual(colorized, 'DEBUG')
|
||||
|
||||
colorized = colorizer(30)
|
||||
t.assert.strictEqual(colorized, 'INFO')
|
||||
|
||||
colorized = colorizer(40)
|
||||
t.assert.strictEqual(colorized, 'WARN')
|
||||
|
||||
colorized = colorizer(50)
|
||||
t.assert.strictEqual(colorized, 'ERROR')
|
||||
|
||||
colorized = colorizer(60)
|
||||
t.assert.strictEqual(colorized, 'FATAL')
|
||||
|
||||
colorized = colorizer(900)
|
||||
t.assert.strictEqual(colorized, 'USERLVL')
|
||||
|
||||
colorized = colorizer('info')
|
||||
t.assert.strictEqual(colorized, 'INFO')
|
||||
|
||||
colorized = colorizer('use-default')
|
||||
t.assert.strictEqual(colorized, 'USERLVL')
|
||||
|
||||
colorized = colorizer.message('foo')
|
||||
t.assert.strictEqual(colorized, 'foo')
|
||||
|
||||
colorized = colorizer.greyMessage('foo')
|
||||
t.assert.strictEqual(colorized, 'foo')
|
||||
}
|
||||
|
||||
const testColoringColorizer = getColorizer => t => {
|
||||
const colorizer = getColorizer(true)
|
||||
let colorized = colorizer(10)
|
||||
t.assert.strictEqual(colorized, '\u001B[90mTRACE\u001B[39m')
|
||||
|
||||
colorized = colorizer(20)
|
||||
t.assert.strictEqual(colorized, '\u001B[34mDEBUG\u001B[39m')
|
||||
|
||||
colorized = colorizer(30)
|
||||
t.assert.strictEqual(colorized, '\u001B[32mINFO\u001B[39m')
|
||||
|
||||
colorized = colorizer(40)
|
||||
t.assert.strictEqual(colorized, '\u001B[33mWARN\u001B[39m')
|
||||
|
||||
colorized = colorizer(50)
|
||||
t.assert.strictEqual(colorized, '\u001B[31mERROR\u001B[39m')
|
||||
|
||||
colorized = colorizer(60)
|
||||
t.assert.strictEqual(colorized, '\u001B[41mFATAL\u001B[49m')
|
||||
|
||||
colorized = colorizer(900)
|
||||
t.assert.strictEqual(colorized, '\u001B[37mUSERLVL\u001B[39m')
|
||||
|
||||
colorized = colorizer('info')
|
||||
t.assert.strictEqual(colorized, '\u001B[32mINFO\u001B[39m')
|
||||
|
||||
colorized = colorizer('use-default')
|
||||
t.assert.strictEqual(colorized, '\u001B[37mUSERLVL\u001B[39m')
|
||||
|
||||
colorized = colorizer.message('foo')
|
||||
t.assert.strictEqual(colorized, '\u001B[36mfoo\u001B[39m')
|
||||
|
||||
colorized = colorizer.greyMessage('foo')
|
||||
t.assert.strictEqual(colorized, '\u001B[90mfoo\u001B[39m')
|
||||
}
|
||||
|
||||
const testCustomColoringColorizer = getColorizer => t => {
|
||||
const customLevels = {
|
||||
0: 'INFO',
|
||||
1: 'ERR',
|
||||
default: 'USERLVL'
|
||||
}
|
||||
const customLevelNames = {
|
||||
info: 0,
|
||||
err: 1
|
||||
}
|
||||
const customColors = [
|
||||
[0, 'not-a-color'],
|
||||
[1, 'red']
|
||||
]
|
||||
const opts = {
|
||||
customLevels,
|
||||
customLevelNames
|
||||
}
|
||||
|
||||
const colorizer = getColorizer(true, customColors)
|
||||
const colorizerWithCustomPropUse = getColorizer(true, customColors, true)
|
||||
let colorized = colorizer(1, opts)
|
||||
t.assert.strictEqual(colorized, '\u001B[31mERR\u001B[39m')
|
||||
|
||||
colorized = colorizer(0, opts)
|
||||
t.assert.strictEqual(colorized, '\u001B[37mINFO\u001B[39m')
|
||||
|
||||
colorized = colorizer(900)
|
||||
t.assert.strictEqual(colorized, '\u001B[37mUSERLVL\u001B[39m')
|
||||
|
||||
colorized = colorizer('err', opts)
|
||||
t.assert.strictEqual(colorized, '\u001B[31mERR\u001B[39m')
|
||||
|
||||
colorized = colorizer('info', opts)
|
||||
t.assert.strictEqual(colorized, '\u001B[37mINFO\u001B[39m')
|
||||
|
||||
colorized = colorizer('use-default')
|
||||
t.assert.strictEqual(colorized, '\u001B[37mUSERLVL\u001B[39m')
|
||||
|
||||
colorized = colorizer(40, opts)
|
||||
t.assert.strictEqual(colorized, '\u001B[33mWARN\u001B[39m')
|
||||
|
||||
colorized = colorizerWithCustomPropUse(50, opts)
|
||||
t.assert.strictEqual(colorized, '\u001B[37mUSERLVL\u001B[39m')
|
||||
}
|
||||
|
||||
test('returns default colorizer - private export', testDefaultColorizer(getColorizer))
|
||||
test('returns colorizing colorizer - private export', testColoringColorizer(getColorizer))
|
||||
test('returns custom colorizing colorizer - private export', testCustomColoringColorizer(getColorizer))
|
||||
|
||||
test('custom props defaults to standard levels', t => {
|
||||
const colorizer = getColorizer(true, [], true)
|
||||
const colorized = colorizer('info')
|
||||
t.assert.strictEqual(colorized, '\u001B[37mINFO\u001B[39m')
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* @deprecated CUID v1 is deprecated by its authors due to information leakage
|
||||
* (timestamps embedded in the id). Use {@link cuid2} instead.
|
||||
* See https://github.com/paralleldrive/cuid.
|
||||
*/
|
||||
export declare const cuid: RegExp;
|
||||
export declare const cuid2: RegExp;
|
||||
export declare const ulid: RegExp;
|
||||
export declare const xid: RegExp;
|
||||
export declare const ksuid: RegExp;
|
||||
export declare const nanoid: RegExp;
|
||||
/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
|
||||
export declare const duration: RegExp;
|
||||
/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */
|
||||
export declare const extendedDuration: RegExp;
|
||||
/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
|
||||
export declare const guid: RegExp;
|
||||
/** Returns a regex for validating an RFC 9562/4122 UUID.
|
||||
*
|
||||
* @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
|
||||
export declare const uuid: (version?: number | undefined) => RegExp;
|
||||
export declare const uuid4: RegExp;
|
||||
export declare const uuid6: RegExp;
|
||||
export declare const uuid7: RegExp;
|
||||
/** Practical email validation */
|
||||
export declare const email: RegExp;
|
||||
/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */
|
||||
export declare const html5Email: RegExp;
|
||||
/** The classic emailregex.com regex for RFC 5322-compliant emails */
|
||||
export declare const rfc5322Email: RegExp;
|
||||
/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */
|
||||
export declare const unicodeEmail: RegExp;
|
||||
export declare const idnEmail: RegExp;
|
||||
export declare const browserEmail: RegExp;
|
||||
export declare function emoji(): RegExp;
|
||||
export declare const ipv4: RegExp;
|
||||
export declare const ipv6: RegExp;
|
||||
export declare const mac: (delimiter?: string) => RegExp;
|
||||
export declare const cidrv4: RegExp;
|
||||
export declare const cidrv6: RegExp;
|
||||
export declare const base64: RegExp;
|
||||
export declare const base64url: RegExp;
|
||||
export declare const hostname: RegExp;
|
||||
export declare const domain: RegExp;
|
||||
export declare const httpProtocol: RegExp;
|
||||
export declare const e164: RegExp;
|
||||
export declare const date: RegExp;
|
||||
export declare function time(args: {
|
||||
precision?: number | null;
|
||||
}): RegExp;
|
||||
export declare function datetime(args: {
|
||||
precision?: number | null;
|
||||
offset?: boolean;
|
||||
local?: boolean;
|
||||
}): RegExp;
|
||||
export declare const string: (params?: {
|
||||
minimum?: number | undefined;
|
||||
maximum?: number | undefined;
|
||||
}) => RegExp;
|
||||
export declare const bigint: RegExp;
|
||||
export declare const integer: RegExp;
|
||||
export declare const number: RegExp;
|
||||
export declare const boolean: RegExp;
|
||||
declare const _null: RegExp;
|
||||
export { _null as null };
|
||||
declare const _undefined: RegExp;
|
||||
export { _undefined as undefined };
|
||||
export declare const lowercase: RegExp;
|
||||
export declare const uppercase: RegExp;
|
||||
export declare const hex: RegExp;
|
||||
export declare const md5_hex: RegExp;
|
||||
export declare const md5_base64: RegExp;
|
||||
export declare const md5_base64url: RegExp;
|
||||
export declare const sha1_hex: RegExp;
|
||||
export declare const sha1_base64: RegExp;
|
||||
export declare const sha1_base64url: RegExp;
|
||||
export declare const sha256_hex: RegExp;
|
||||
export declare const sha256_base64: RegExp;
|
||||
export declare const sha256_base64url: RegExp;
|
||||
export declare const sha384_hex: RegExp;
|
||||
export declare const sha384_base64: RegExp;
|
||||
export declare const sha384_base64url: RegExp;
|
||||
export declare const sha512_hex: RegExp;
|
||||
export declare const sha512_base64: RegExp;
|
||||
export declare const sha512_base64url: RegExp;
|
||||
@@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
const pLimit = require('p-limit');
|
||||
|
||||
class EndError extends Error {
|
||||
constructor(value) {
|
||||
super();
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
|
||||
// The input can also be a promise, so we await it
|
||||
const testElement = async (element, tester) => tester(await element);
|
||||
|
||||
// The input can also be a promise, so we `Promise.all()` them both
|
||||
const finder = async element => {
|
||||
const values = await Promise.all(element);
|
||||
if (values[1] === true) {
|
||||
throw new EndError(values[0]);
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
const pLocate = async (iterable, tester, options) => {
|
||||
options = {
|
||||
concurrency: Infinity,
|
||||
preserveOrder: true,
|
||||
...options
|
||||
};
|
||||
|
||||
const limit = pLimit(options.concurrency);
|
||||
|
||||
// Start all the promises concurrently with optional limit
|
||||
const items = [...iterable].map(element => [element, limit(testElement, element, tester)]);
|
||||
|
||||
// Check the promises either serially or concurrently
|
||||
const checkLimit = pLimit(options.preserveOrder ? 1 : Infinity);
|
||||
|
||||
try {
|
||||
await Promise.all(items.map(element => checkLimit(finder, element)));
|
||||
} catch (error) {
|
||||
if (error instanceof EndError) {
|
||||
return error.value;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = pLocate;
|
||||
@@ -0,0 +1,38 @@
|
||||
// if changed, update also jsdocs and docs
|
||||
const defaultPort = 51204;
|
||||
const defaultBrowserPort = 63315;
|
||||
const defaultInspectPort = 9229;
|
||||
const API_PATH = "/__vitest_api__";
|
||||
const CONFIG_NAMES = ["vitest.config", "vite.config"];
|
||||
const CONFIG_EXTENSIONS = [
|
||||
".ts",
|
||||
".mts",
|
||||
".cts",
|
||||
".js",
|
||||
".mjs",
|
||||
".cjs"
|
||||
];
|
||||
const configFiles = CONFIG_NAMES.flatMap((name) => CONFIG_EXTENSIONS.map((ext) => name + ext));
|
||||
const globalApis = [
|
||||
"suite",
|
||||
"test",
|
||||
"describe",
|
||||
"it",
|
||||
"chai",
|
||||
"expect",
|
||||
"assert",
|
||||
"expectTypeOf",
|
||||
"assertType",
|
||||
"vitest",
|
||||
"vi",
|
||||
"beforeAll",
|
||||
"afterAll",
|
||||
"beforeEach",
|
||||
"afterEach",
|
||||
"onTestFinished",
|
||||
"onTestFailed",
|
||||
"aroundEach",
|
||||
"aroundAll"
|
||||
];
|
||||
|
||||
export { API_PATH as A, defaultInspectPort as a, defaultPort as b, configFiles as c, defaultBrowserPort as d, globalApis as g };
|
||||
@@ -0,0 +1,56 @@
|
||||
"use strict";
|
||||
var _a;
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.globalRegistry = exports.$ZodRegistry = exports.$input = exports.$output = void 0;
|
||||
exports.registry = registry;
|
||||
exports.$output = Symbol("ZodOutput");
|
||||
exports.$input = Symbol("ZodInput");
|
||||
class $ZodRegistry {
|
||||
constructor() {
|
||||
this._map = new WeakMap();
|
||||
this._idmap = new Map();
|
||||
}
|
||||
add(schema, ..._meta) {
|
||||
const meta = _meta[0];
|
||||
this._map.set(schema, meta);
|
||||
if (meta && typeof meta === "object" && "id" in meta) {
|
||||
this._idmap.set(meta.id, schema);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
clear() {
|
||||
this._map = new WeakMap();
|
||||
this._idmap = new Map();
|
||||
return this;
|
||||
}
|
||||
remove(schema) {
|
||||
const meta = this._map.get(schema);
|
||||
if (meta && typeof meta === "object" && "id" in meta) {
|
||||
this._idmap.delete(meta.id);
|
||||
}
|
||||
this._map.delete(schema);
|
||||
return this;
|
||||
}
|
||||
get(schema) {
|
||||
// return this._map.get(schema) as any;
|
||||
// inherit metadata
|
||||
const p = schema._zod.parent;
|
||||
if (p) {
|
||||
const pm = { ...(this.get(p) ?? {}) };
|
||||
delete pm.id; // do not inherit id
|
||||
const f = { ...pm, ...this._map.get(schema) };
|
||||
return Object.keys(f).length ? f : undefined;
|
||||
}
|
||||
return this._map.get(schema);
|
||||
}
|
||||
has(schema) {
|
||||
return this._map.has(schema);
|
||||
}
|
||||
}
|
||||
exports.$ZodRegistry = $ZodRegistry;
|
||||
// registries
|
||||
function registry() {
|
||||
return new $ZodRegistry();
|
||||
}
|
||||
(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
|
||||
exports.globalRegistry = globalThis.__zod_globalRegistry;
|
||||
@@ -0,0 +1,12 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = default_1;
|
||||
const km_js_1 = __importDefault(require("./km.cjs"));
|
||||
/** @deprecated Use `km` instead. */
|
||||
function default_1() {
|
||||
return (0, km_js_1.default)();
|
||||
}
|
||||
module.exports = exports.default;
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,23 @@
|
||||
"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 __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AST_TOKEN_TYPES = exports.AST_NODE_TYPES = void 0;
|
||||
var ast_spec_1 = require("./generated/ast-spec");
|
||||
Object.defineProperty(exports, "AST_NODE_TYPES", { enumerable: true, get: function () { return ast_spec_1.AST_NODE_TYPES; } });
|
||||
Object.defineProperty(exports, "AST_TOKEN_TYPES", { enumerable: true, get: function () { return ast_spec_1.AST_TOKEN_TYPES; } });
|
||||
__exportStar(require("./lib"), exports);
|
||||
__exportStar(require("./parser-options"), exports);
|
||||
__exportStar(require("./ts-estree"), exports);
|
||||
@@ -0,0 +1,24 @@
|
||||
'use strict'
|
||||
|
||||
const { Transform, pipeline } = require('stream')
|
||||
const build = require('../..')
|
||||
|
||||
module.exports = function (threadStreamOpts) {
|
||||
const { opts = {} } = threadStreamOpts
|
||||
return build(function (source) {
|
||||
const transform = new Transform({
|
||||
objectMode: true,
|
||||
autoDestroy: true,
|
||||
transform (chunk, enc, cb) {
|
||||
chunk.service = 'from transform'
|
||||
chunk.level = `${source.levels.labels[chunk.level]}(${chunk.level})`
|
||||
chunk[source.messageKey] = chunk[source.messageKey].toUpperCase()
|
||||
cb(null, JSON.stringify(chunk) + '\n')
|
||||
}
|
||||
})
|
||||
|
||||
pipeline(source, transform, () => {})
|
||||
|
||||
return transform
|
||||
}, { ...opts, enablePipelining: true })
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
'use strict'
|
||||
|
||||
const SemVer = require('../classes/semver')
|
||||
const Comparator = require('../classes/comparator')
|
||||
const { ANY } = Comparator
|
||||
const Range = require('../classes/range')
|
||||
const satisfies = require('../functions/satisfies')
|
||||
const gt = require('../functions/gt')
|
||||
const lt = require('../functions/lt')
|
||||
const lte = require('../functions/lte')
|
||||
const gte = require('../functions/gte')
|
||||
|
||||
const outside = (version, range, hilo, options) => {
|
||||
version = new SemVer(version, options)
|
||||
range = new Range(range, options)
|
||||
|
||||
let gtfn, ltefn, ltfn, comp, ecomp
|
||||
switch (hilo) {
|
||||
case '>':
|
||||
gtfn = gt
|
||||
ltefn = lte
|
||||
ltfn = lt
|
||||
comp = '>'
|
||||
ecomp = '>='
|
||||
break
|
||||
case '<':
|
||||
gtfn = lt
|
||||
ltefn = gte
|
||||
ltfn = gt
|
||||
comp = '<'
|
||||
ecomp = '<='
|
||||
break
|
||||
default:
|
||||
throw new TypeError('Must provide a hilo val of "<" or ">"')
|
||||
}
|
||||
|
||||
// If it satisfies the range it is not outside
|
||||
if (satisfies(version, range, options)) {
|
||||
return false
|
||||
}
|
||||
|
||||
// From now on, variable terms are as if we're in "gtr" mode.
|
||||
// but note that everything is flipped for the "ltr" function.
|
||||
|
||||
for (let i = 0; i < range.set.length; ++i) {
|
||||
const comparators = range.set[i]
|
||||
|
||||
let high = null
|
||||
let low = null
|
||||
|
||||
comparators.forEach((comparator) => {
|
||||
if (comparator.semver === ANY) {
|
||||
comparator = new Comparator('>=0.0.0')
|
||||
}
|
||||
high = high || comparator
|
||||
low = low || comparator
|
||||
if (gtfn(comparator.semver, high.semver, options)) {
|
||||
high = comparator
|
||||
} else if (ltfn(comparator.semver, low.semver, options)) {
|
||||
low = comparator
|
||||
}
|
||||
})
|
||||
|
||||
// If the edge version comparator has a operator then our version
|
||||
// isn't outside it
|
||||
if (high.operator === comp || high.operator === ecomp) {
|
||||
return false
|
||||
}
|
||||
|
||||
// If the lowest version comparator has an operator and our version
|
||||
// is less than it then it isn't higher than the range
|
||||
if ((!low.operator || low.operator === comp) &&
|
||||
ltefn(version, low.semver)) {
|
||||
return false
|
||||
} else if (low.operator === ecomp && ltfn(version, low.semver)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
module.exports = outside
|
||||
@@ -0,0 +1,188 @@
|
||||
/// <reference types="node" />
|
||||
|
||||
import type { Blob } from 'node:buffer'
|
||||
import type { ReadableStream, WritableStream } from 'node:stream/web'
|
||||
import type { MessagePort } from 'node:worker_threads'
|
||||
import {
|
||||
EventInit,
|
||||
EventListenerOptions,
|
||||
AddEventListenerOptions,
|
||||
EventListenerOrEventListenerObject
|
||||
} from './patch'
|
||||
import Dispatcher from './dispatcher'
|
||||
import { HeadersInit } from './fetch'
|
||||
|
||||
export type BinaryType = 'blob' | 'arraybuffer'
|
||||
|
||||
interface WebSocketEventMap {
|
||||
close: CloseEvent
|
||||
error: ErrorEvent
|
||||
message: MessageEvent
|
||||
open: Event
|
||||
}
|
||||
|
||||
interface WebSocket extends EventTarget {
|
||||
binaryType: BinaryType
|
||||
|
||||
readonly bufferedAmount: number
|
||||
readonly extensions: string
|
||||
|
||||
onclose: ((this: WebSocket, ev: WebSocketEventMap['close']) => any) | null
|
||||
onerror: ((this: WebSocket, ev: WebSocketEventMap['error']) => any) | null
|
||||
onmessage: ((this: WebSocket, ev: WebSocketEventMap['message']) => any) | null
|
||||
onopen: ((this: WebSocket, ev: WebSocketEventMap['open']) => any) | null
|
||||
|
||||
readonly protocol: string
|
||||
readonly readyState: number
|
||||
readonly url: string
|
||||
|
||||
close(code?: number, reason?: string): void
|
||||
send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void
|
||||
|
||||
readonly CLOSED: number
|
||||
readonly CLOSING: number
|
||||
readonly CONNECTING: number
|
||||
readonly OPEN: number
|
||||
|
||||
addEventListener<K extends keyof WebSocketEventMap>(
|
||||
type: K,
|
||||
listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,
|
||||
options?: boolean | AddEventListenerOptions
|
||||
): void
|
||||
addEventListener(
|
||||
type: string,
|
||||
listener: EventListenerOrEventListenerObject,
|
||||
options?: boolean | AddEventListenerOptions
|
||||
): void
|
||||
removeEventListener<K extends keyof WebSocketEventMap>(
|
||||
type: K,
|
||||
listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,
|
||||
options?: boolean | EventListenerOptions
|
||||
): void
|
||||
removeEventListener(
|
||||
type: string,
|
||||
listener: EventListenerOrEventListenerObject,
|
||||
options?: boolean | EventListenerOptions
|
||||
): void
|
||||
}
|
||||
|
||||
export declare const WebSocket: {
|
||||
prototype: WebSocket
|
||||
new (url: string | URL, protocols?: string | string[] | WebSocketInit): WebSocket
|
||||
readonly CLOSED: number
|
||||
readonly CLOSING: number
|
||||
readonly CONNECTING: number
|
||||
readonly OPEN: number
|
||||
}
|
||||
|
||||
interface CloseEventInit extends EventInit {
|
||||
code?: number
|
||||
reason?: string
|
||||
wasClean?: boolean
|
||||
}
|
||||
|
||||
interface CloseEvent extends Event {
|
||||
readonly code: number
|
||||
readonly reason: string
|
||||
readonly wasClean: boolean
|
||||
}
|
||||
|
||||
export declare const CloseEvent: {
|
||||
prototype: CloseEvent
|
||||
new (type: string, eventInitDict?: CloseEventInit): CloseEvent
|
||||
}
|
||||
|
||||
interface MessageEventInit<T = any> extends EventInit {
|
||||
data?: T
|
||||
lastEventId?: string
|
||||
origin?: string
|
||||
ports?: MessagePort[]
|
||||
source?: MessagePort | null
|
||||
}
|
||||
|
||||
interface MessageEvent<T = any> extends Event {
|
||||
readonly data: T
|
||||
readonly lastEventId: string
|
||||
readonly origin: string
|
||||
readonly ports: readonly MessagePort[]
|
||||
readonly source: MessagePort | null
|
||||
initMessageEvent(
|
||||
type: string,
|
||||
bubbles?: boolean,
|
||||
cancelable?: boolean,
|
||||
data?: any,
|
||||
origin?: string,
|
||||
lastEventId?: string,
|
||||
source?: MessagePort | null,
|
||||
ports?: MessagePort[]
|
||||
): void;
|
||||
}
|
||||
|
||||
export declare const MessageEvent: {
|
||||
prototype: MessageEvent
|
||||
new<T>(type: string, eventInitDict?: MessageEventInit<T>): MessageEvent<T>
|
||||
}
|
||||
|
||||
interface ErrorEventInit extends EventInit {
|
||||
message?: string
|
||||
filename?: string
|
||||
lineno?: number
|
||||
colno?: number
|
||||
error?: any
|
||||
}
|
||||
|
||||
interface ErrorEvent extends Event {
|
||||
readonly message: string
|
||||
readonly filename: string
|
||||
readonly lineno: number
|
||||
readonly colno: number
|
||||
readonly error: Error
|
||||
}
|
||||
|
||||
export declare const ErrorEvent: {
|
||||
prototype: ErrorEvent
|
||||
new (type: string, eventInitDict?: ErrorEventInit): ErrorEvent
|
||||
}
|
||||
|
||||
interface WebSocketInit {
|
||||
protocols?: string | string[],
|
||||
dispatcher?: Dispatcher,
|
||||
headers?: HeadersInit
|
||||
}
|
||||
|
||||
interface WebSocketStreamOptions {
|
||||
protocols?: string | string[]
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
interface WebSocketCloseInfo {
|
||||
closeCode: number
|
||||
reason: string
|
||||
}
|
||||
|
||||
interface WebSocketStream {
|
||||
closed: Promise<WebSocketCloseInfo>
|
||||
opened: Promise<{
|
||||
extensions: string
|
||||
protocol: string
|
||||
readable: ReadableStream
|
||||
writable: WritableStream
|
||||
}>
|
||||
url: string
|
||||
|
||||
close(options?: Partial<WebSocketCloseInfo>): void
|
||||
}
|
||||
|
||||
export declare const WebSocketStream: {
|
||||
prototype: WebSocketStream
|
||||
new (url: string | URL, options?: WebSocketStreamOptions): WebSocketStream
|
||||
}
|
||||
|
||||
interface WebSocketError extends Event, WebSocketCloseInfo {}
|
||||
|
||||
export declare const WebSocketError: {
|
||||
prototype: WebSocketError
|
||||
new (type: string, init?: WebSocketCloseInfo): WebSocketError
|
||||
}
|
||||
|
||||
export declare const ping: (ws: WebSocket, body?: Buffer) => void
|
||||
@@ -0,0 +1,54 @@
|
||||
# which
|
||||
|
||||
Like the unix `which` utility.
|
||||
|
||||
Finds the first instance of a specified executable in the PATH
|
||||
environment variable. Does not cache the results, so `hash -r` is not
|
||||
needed when the PATH changes.
|
||||
|
||||
## USAGE
|
||||
|
||||
```javascript
|
||||
var which = require('which')
|
||||
|
||||
// async usage
|
||||
which('node', function (er, resolvedPath) {
|
||||
// er is returned if no "node" is found on the PATH
|
||||
// if it is found, then the absolute path to the exec is returned
|
||||
})
|
||||
|
||||
// or promise
|
||||
which('node').then(resolvedPath => { ... }).catch(er => { ... not found ... })
|
||||
|
||||
// sync usage
|
||||
// throws if not found
|
||||
var resolved = which.sync('node')
|
||||
|
||||
// if nothrow option is used, returns null if not found
|
||||
resolved = which.sync('node', {nothrow: true})
|
||||
|
||||
// Pass options to override the PATH and PATHEXT environment vars.
|
||||
which('node', { path: someOtherPath }, function (er, resolved) {
|
||||
if (er)
|
||||
throw er
|
||||
console.log('found at %j', resolved)
|
||||
})
|
||||
```
|
||||
|
||||
## CLI USAGE
|
||||
|
||||
Same as the BSD `which(1)` binary.
|
||||
|
||||
```
|
||||
usage: which [-as] program ...
|
||||
```
|
||||
|
||||
## OPTIONS
|
||||
|
||||
You may pass an options object as the second argument.
|
||||
|
||||
- `path`: Use instead of the `PATH` environment variable.
|
||||
- `pathExt`: Use instead of the `PATHEXT` environment variable.
|
||||
- `all`: Return all matches, instead of just the first one. Note that
|
||||
this means the function returns an array of strings instead of a
|
||||
single string.
|
||||
@@ -0,0 +1,389 @@
|
||||
'use strict';
|
||||
|
||||
var resolve = require('./resolve')
|
||||
, util = require('./util')
|
||||
, errorClasses = require('./error_classes')
|
||||
, stableStringify = require('fast-json-stable-stringify');
|
||||
|
||||
var validateGenerator = require('../dotjs/validate');
|
||||
|
||||
/**
|
||||
* Functions below are used inside compiled validations function
|
||||
*/
|
||||
|
||||
var ucs2length = util.ucs2length;
|
||||
var equal = require('fast-deep-equal');
|
||||
|
||||
// this error is thrown by async schemas to return validation errors via exception
|
||||
var ValidationError = errorClasses.Validation;
|
||||
|
||||
module.exports = compile;
|
||||
|
||||
|
||||
/**
|
||||
* Compiles schema to validation function
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema object
|
||||
* @param {Object} root object with information about the root schema for this schema
|
||||
* @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
|
||||
* @param {String} baseId base ID for IDs in the schema
|
||||
* @return {Function} validation function
|
||||
*/
|
||||
function compile(schema, root, localRefs, baseId) {
|
||||
/* jshint validthis: true, evil: true */
|
||||
/* eslint no-shadow: 0 */
|
||||
var self = this
|
||||
, opts = this._opts
|
||||
, refVal = [ undefined ]
|
||||
, refs = {}
|
||||
, patterns = []
|
||||
, patternsHash = {}
|
||||
, defaults = []
|
||||
, defaultsHash = {}
|
||||
, customRules = [];
|
||||
|
||||
function patternCode(i, patterns) {
|
||||
var regExpCode = opts.regExp ? 'regExp' : 'new RegExp';
|
||||
return 'var pattern' + i + ' = ' + regExpCode + '(' + util.toQuotedString(patterns[i]) + ');';
|
||||
}
|
||||
|
||||
root = root || { schema: schema, refVal: refVal, refs: refs };
|
||||
|
||||
var c = checkCompiling.call(this, schema, root, baseId);
|
||||
var compilation = this._compilations[c.index];
|
||||
if (c.compiling) return (compilation.callValidate = callValidate);
|
||||
|
||||
var formats = this._formats;
|
||||
var RULES = this.RULES;
|
||||
|
||||
try {
|
||||
var v = localCompile(schema, root, localRefs, baseId);
|
||||
compilation.validate = v;
|
||||
var cv = compilation.callValidate;
|
||||
if (cv) {
|
||||
cv.schema = v.schema;
|
||||
cv.errors = null;
|
||||
cv.refs = v.refs;
|
||||
cv.refVal = v.refVal;
|
||||
cv.root = v.root;
|
||||
cv.$async = v.$async;
|
||||
if (opts.sourceCode) cv.source = v.source;
|
||||
}
|
||||
return v;
|
||||
} finally {
|
||||
endCompiling.call(this, schema, root, baseId);
|
||||
}
|
||||
|
||||
/* @this {*} - custom context, see passContext option */
|
||||
function callValidate() {
|
||||
/* jshint validthis: true */
|
||||
var validate = compilation.validate;
|
||||
var result = validate.apply(this, arguments);
|
||||
callValidate.errors = validate.errors;
|
||||
return result;
|
||||
}
|
||||
|
||||
function localCompile(_schema, _root, localRefs, baseId) {
|
||||
var isRoot = !_root || (_root && _root.schema == _schema);
|
||||
if (_root.schema != root.schema)
|
||||
return compile.call(self, _schema, _root, localRefs, baseId);
|
||||
|
||||
var $async = _schema.$async === true;
|
||||
|
||||
var sourceCode = validateGenerator({
|
||||
isTop: true,
|
||||
schema: _schema,
|
||||
isRoot: isRoot,
|
||||
baseId: baseId,
|
||||
root: _root,
|
||||
schemaPath: '',
|
||||
errSchemaPath: '#',
|
||||
errorPath: '""',
|
||||
MissingRefError: errorClasses.MissingRef,
|
||||
RULES: RULES,
|
||||
validate: validateGenerator,
|
||||
util: util,
|
||||
resolve: resolve,
|
||||
resolveRef: resolveRef,
|
||||
usePattern: usePattern,
|
||||
useDefault: useDefault,
|
||||
useCustomRule: useCustomRule,
|
||||
opts: opts,
|
||||
formats: formats,
|
||||
logger: self.logger,
|
||||
self: self
|
||||
});
|
||||
|
||||
sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
|
||||
+ vars(defaults, defaultCode) + vars(customRules, customRuleCode)
|
||||
+ sourceCode;
|
||||
|
||||
if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema);
|
||||
// console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
|
||||
var validate;
|
||||
try {
|
||||
var makeValidate = new Function(
|
||||
'self',
|
||||
'RULES',
|
||||
'formats',
|
||||
'root',
|
||||
'refVal',
|
||||
'defaults',
|
||||
'customRules',
|
||||
'equal',
|
||||
'ucs2length',
|
||||
'ValidationError',
|
||||
'regExp',
|
||||
sourceCode
|
||||
);
|
||||
|
||||
validate = makeValidate(
|
||||
self,
|
||||
RULES,
|
||||
formats,
|
||||
root,
|
||||
refVal,
|
||||
defaults,
|
||||
customRules,
|
||||
equal,
|
||||
ucs2length,
|
||||
ValidationError,
|
||||
opts.regExp
|
||||
);
|
||||
|
||||
refVal[0] = validate;
|
||||
} catch(e) {
|
||||
self.logger.error('Error compiling schema, function code:', sourceCode);
|
||||
throw e;
|
||||
}
|
||||
|
||||
validate.schema = _schema;
|
||||
validate.errors = null;
|
||||
validate.refs = refs;
|
||||
validate.refVal = refVal;
|
||||
validate.root = isRoot ? validate : _root;
|
||||
if ($async) validate.$async = true;
|
||||
if (opts.sourceCode === true) {
|
||||
validate.source = {
|
||||
code: sourceCode,
|
||||
patterns: patterns,
|
||||
defaults: defaults
|
||||
};
|
||||
}
|
||||
|
||||
return validate;
|
||||
}
|
||||
|
||||
function resolveRef(baseId, ref, isRoot) {
|
||||
ref = resolve.url(baseId, ref);
|
||||
var refIndex = refs[ref];
|
||||
var _refVal, refCode;
|
||||
if (refIndex !== undefined) {
|
||||
_refVal = refVal[refIndex];
|
||||
refCode = 'refVal[' + refIndex + ']';
|
||||
return resolvedRef(_refVal, refCode);
|
||||
}
|
||||
if (!isRoot && root.refs) {
|
||||
var rootRefId = root.refs[ref];
|
||||
if (rootRefId !== undefined) {
|
||||
_refVal = root.refVal[rootRefId];
|
||||
refCode = addLocalRef(ref, _refVal);
|
||||
return resolvedRef(_refVal, refCode);
|
||||
}
|
||||
}
|
||||
|
||||
refCode = addLocalRef(ref);
|
||||
var v = resolve.call(self, localCompile, root, ref);
|
||||
if (v === undefined) {
|
||||
var localSchema = localRefs && localRefs[ref];
|
||||
if (localSchema) {
|
||||
v = resolve.inlineRef(localSchema, opts.inlineRefs)
|
||||
? localSchema
|
||||
: compile.call(self, localSchema, root, localRefs, baseId);
|
||||
}
|
||||
}
|
||||
|
||||
if (v === undefined) {
|
||||
removeLocalRef(ref);
|
||||
} else {
|
||||
replaceLocalRef(ref, v);
|
||||
return resolvedRef(v, refCode);
|
||||
}
|
||||
}
|
||||
|
||||
function addLocalRef(ref, v) {
|
||||
var refId = refVal.length;
|
||||
refVal[refId] = v;
|
||||
refs[ref] = refId;
|
||||
return 'refVal' + refId;
|
||||
}
|
||||
|
||||
function removeLocalRef(ref) {
|
||||
delete refs[ref];
|
||||
}
|
||||
|
||||
function replaceLocalRef(ref, v) {
|
||||
var refId = refs[ref];
|
||||
refVal[refId] = v;
|
||||
}
|
||||
|
||||
function resolvedRef(refVal, code) {
|
||||
return typeof refVal == 'object' || typeof refVal == 'boolean'
|
||||
? { code: code, schema: refVal, inline: true }
|
||||
: { code: code, $async: refVal && !!refVal.$async };
|
||||
}
|
||||
|
||||
function usePattern(regexStr) {
|
||||
var index = patternsHash[regexStr];
|
||||
if (index === undefined) {
|
||||
index = patternsHash[regexStr] = patterns.length;
|
||||
patterns[index] = regexStr;
|
||||
}
|
||||
return 'pattern' + index;
|
||||
}
|
||||
|
||||
function useDefault(value) {
|
||||
switch (typeof value) {
|
||||
case 'boolean':
|
||||
case 'number':
|
||||
return '' + value;
|
||||
case 'string':
|
||||
return util.toQuotedString(value);
|
||||
case 'object':
|
||||
if (value === null) return 'null';
|
||||
var valueStr = stableStringify(value);
|
||||
var index = defaultsHash[valueStr];
|
||||
if (index === undefined) {
|
||||
index = defaultsHash[valueStr] = defaults.length;
|
||||
defaults[index] = value;
|
||||
}
|
||||
return 'default' + index;
|
||||
}
|
||||
}
|
||||
|
||||
function useCustomRule(rule, schema, parentSchema, it) {
|
||||
if (self._opts.validateSchema !== false) {
|
||||
var deps = rule.definition.dependencies;
|
||||
if (deps && !deps.every(function(keyword) {
|
||||
return Object.prototype.hasOwnProperty.call(parentSchema, keyword);
|
||||
}))
|
||||
throw new Error('parent schema must have all required keywords: ' + deps.join(','));
|
||||
|
||||
var validateSchema = rule.definition.validateSchema;
|
||||
if (validateSchema) {
|
||||
var valid = validateSchema(schema);
|
||||
if (!valid) {
|
||||
var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
|
||||
if (self._opts.validateSchema == 'log') self.logger.error(message);
|
||||
else throw new Error(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var compile = rule.definition.compile
|
||||
, inline = rule.definition.inline
|
||||
, macro = rule.definition.macro;
|
||||
|
||||
var validate;
|
||||
if (compile) {
|
||||
validate = compile.call(self, schema, parentSchema, it);
|
||||
} else if (macro) {
|
||||
validate = macro.call(self, schema, parentSchema, it);
|
||||
if (opts.validateSchema !== false) self.validateSchema(validate, true);
|
||||
} else if (inline) {
|
||||
validate = inline.call(self, it, rule.keyword, schema, parentSchema);
|
||||
} else {
|
||||
validate = rule.definition.validate;
|
||||
if (!validate) return;
|
||||
}
|
||||
|
||||
if (validate === undefined)
|
||||
throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
|
||||
|
||||
var index = customRules.length;
|
||||
customRules[index] = validate;
|
||||
|
||||
return {
|
||||
code: 'customRule' + index,
|
||||
validate: validate
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Checks if the schema is currently compiled
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema to compile
|
||||
* @param {Object} root root object
|
||||
* @param {String} baseId base schema ID
|
||||
* @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
|
||||
*/
|
||||
function checkCompiling(schema, root, baseId) {
|
||||
/* jshint validthis: true */
|
||||
var index = compIndex.call(this, schema, root, baseId);
|
||||
if (index >= 0) return { index: index, compiling: true };
|
||||
index = this._compilations.length;
|
||||
this._compilations[index] = {
|
||||
schema: schema,
|
||||
root: root,
|
||||
baseId: baseId
|
||||
};
|
||||
return { index: index, compiling: false };
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Removes the schema from the currently compiled list
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema to compile
|
||||
* @param {Object} root root object
|
||||
* @param {String} baseId base schema ID
|
||||
*/
|
||||
function endCompiling(schema, root, baseId) {
|
||||
/* jshint validthis: true */
|
||||
var i = compIndex.call(this, schema, root, baseId);
|
||||
if (i >= 0) this._compilations.splice(i, 1);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Index of schema compilation in the currently compiled list
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema to compile
|
||||
* @param {Object} root root object
|
||||
* @param {String} baseId base schema ID
|
||||
* @return {Integer} compilation index
|
||||
*/
|
||||
function compIndex(schema, root, baseId) {
|
||||
/* jshint validthis: true */
|
||||
for (var i=0; i<this._compilations.length; i++) {
|
||||
var c = this._compilations[i];
|
||||
if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
function defaultCode(i) {
|
||||
return 'var default' + i + ' = defaults[' + i + '];';
|
||||
}
|
||||
|
||||
|
||||
function refValCode(i, refVal) {
|
||||
return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];';
|
||||
}
|
||||
|
||||
|
||||
function customRuleCode(i) {
|
||||
return 'var customRule' + i + ' = customRules[' + i + '];';
|
||||
}
|
||||
|
||||
|
||||
function vars(arr, statement) {
|
||||
if (!arr.length) return '';
|
||||
var code = '';
|
||||
for (var i=0; i<arr.length; i++)
|
||||
code += statement(i, arr);
|
||||
return code;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* NIST secp384r1 aka p384.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { type H2CMethod } from './abstract/hash-to-curve.ts';
|
||||
import { p384 as p384n } from './nist.ts';
|
||||
/** @deprecated use `import { p384 } from '@noble/curves/nist.js';` */
|
||||
export declare const p384: typeof p384n;
|
||||
/** @deprecated use `import { p384 } from '@noble/curves/nist.js';` */
|
||||
export declare const secp384r1: typeof p384n;
|
||||
/** @deprecated use `import { p384_hasher } from '@noble/curves/nist.js';` */
|
||||
export declare const hashToCurve: H2CMethod<bigint>;
|
||||
/** @deprecated use `import { p384_hasher } from '@noble/curves/nist.js';` */
|
||||
export declare const encodeToCurve: H2CMethod<bigint>;
|
||||
//# sourceMappingURL=p384.d.ts.map
|
||||
@@ -0,0 +1,11 @@
|
||||
export type Options = [
|
||||
{
|
||||
ignoredTypeNames?: string[];
|
||||
checkUnknown?: boolean;
|
||||
}
|
||||
];
|
||||
export type MessageIds = 'baseArrayJoin' | 'baseToString';
|
||||
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<MessageIds, Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
|
||||
name: string;
|
||||
};
|
||||
export default _default;
|
||||
@@ -0,0 +1,60 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
const util_1 = require("../util");
|
||||
exports.default = (0, util_1.createRule)({
|
||||
name: 'no-namespace',
|
||||
meta: {
|
||||
type: 'suggestion',
|
||||
docs: {
|
||||
description: 'Disallow TypeScript namespaces',
|
||||
recommended: 'recommended',
|
||||
},
|
||||
messages: {
|
||||
moduleSyntaxIsPreferred: 'ES2015 module syntax is preferred over namespaces.',
|
||||
},
|
||||
schema: [
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
allowDeclarations: {
|
||||
type: 'boolean',
|
||||
description: 'Whether to allow `declare` with custom TypeScript namespaces.',
|
||||
},
|
||||
allowDefinitionFiles: {
|
||||
type: 'boolean',
|
||||
description: 'Whether to allow `declare` with custom TypeScript namespaces inside definition files.',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
defaultOptions: [
|
||||
{
|
||||
allowDeclarations: false,
|
||||
allowDefinitionFiles: true,
|
||||
},
|
||||
],
|
||||
create(context, [{ allowDeclarations, allowDefinitionFiles }]) {
|
||||
function isDeclaration(node) {
|
||||
if (node.type === utils_1.AST_NODE_TYPES.TSModuleDeclaration && node.declare) {
|
||||
return true;
|
||||
}
|
||||
return node.parent != null && isDeclaration(node.parent);
|
||||
}
|
||||
return {
|
||||
"TSModuleDeclaration[global!=true][id.type!='Literal']"(node) {
|
||||
if (node.parent.type === utils_1.AST_NODE_TYPES.TSModuleDeclaration ||
|
||||
(allowDefinitionFiles && (0, util_1.isDefinitionFile)(context.filename)) ||
|
||||
(allowDeclarations && isDeclaration(node))) {
|
||||
return;
|
||||
}
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'moduleSyntaxIsPreferred',
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
# @vitest/pretty-format
|
||||
|
||||
[](https://npmx.dev/package/@vitest/pretty-format)
|
||||
|
||||
Vitest's fork of Jest's [`pretty-format`](https://npmx.dev/package/pretty-format).
|
||||
|
||||
[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/pretty-format) | [Documentation](https://github.com/vitest-dev/vitest/blob/main/packages/pretty-format/USAGE.md)
|
||||
@@ -0,0 +1,6 @@
|
||||
import { Parser } from "../index.js";
|
||||
|
||||
export declare const parsers: {
|
||||
acorn: Parser;
|
||||
espree: Parser;
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
import crypto from 'crypto';
|
||||
|
||||
function sha1(bytes) {
|
||||
if (Array.isArray(bytes)) {
|
||||
bytes = Buffer.from(bytes);
|
||||
} else if (typeof bytes === 'string') {
|
||||
bytes = Buffer.from(bytes, 'utf8');
|
||||
}
|
||||
|
||||
return crypto.createHash('sha1').update(bytes).digest();
|
||||
}
|
||||
|
||||
export default sha1;
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"elementFlags.enum.d.ts","sourceRoot":"","sources":["../../src/enums/elementFlags.enum.ts"],"names":[],"mappings":"AAEA,oBAAY,YAAY;IACpB,IAAI,IAAI;IACR,QAAQ,IAAS;IACjB,QAAQ,IAAS;IACjB,IAAI,IAAS;IACb,QAAQ,IAAS;IACjB,KAAK,IAAsB;IAC3B,QAAQ,KAAkB;IAC1B,WAAW,KAA6B;IACxC,OAAO,KAAiC;CAC3C"}
|
||||
Reference in New Issue
Block a user