WIP: bootstrap and partial real Solana watcher implementation

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

View File

@@ -0,0 +1,22 @@
'use strict'
const { Writable } = require('stream')
const parentPort = require('worker_threads').parentPort
async function run (opts) {
return new Writable({
autoDestroy: true,
write (chunk, enc, cb) {
if (parentPort) {
parentPort.postMessage({
code: 'EVENT',
name: 'context',
args: opts.$context
})
}
cb()
}
})
}
module.exports = run

View File

@@ -0,0 +1,118 @@
"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.es5 = void 0;
const base_config_1 = require("./base-config");
const decorators_1 = require("./decorators");
const decorators_legacy_1 = require("./decorators.legacy");
exports.es5 = {
libs: [decorators_1.decorators, decorators_legacy_1.decorators_legacy],
variables: [
['Symbol', base_config_1.TYPE],
['PropertyKey', base_config_1.TYPE],
['PropertyDescriptor', base_config_1.TYPE],
['PropertyDescriptorMap', base_config_1.TYPE],
['Object', base_config_1.TYPE_VALUE],
['ObjectConstructor', base_config_1.TYPE],
['Function', base_config_1.TYPE_VALUE],
['FunctionConstructor', base_config_1.TYPE],
['ThisParameterType', base_config_1.TYPE],
['OmitThisParameter', base_config_1.TYPE],
['CallableFunction', base_config_1.TYPE],
['NewableFunction', base_config_1.TYPE],
['IArguments', base_config_1.TYPE],
['String', base_config_1.TYPE_VALUE],
['StringConstructor', base_config_1.TYPE],
['Boolean', base_config_1.TYPE_VALUE],
['BooleanConstructor', base_config_1.TYPE],
['Number', base_config_1.TYPE_VALUE],
['NumberConstructor', base_config_1.TYPE],
['TemplateStringsArray', base_config_1.TYPE],
['ImportMeta', base_config_1.TYPE],
['ImportCallOptions', base_config_1.TYPE],
['ImportAssertions', base_config_1.TYPE],
['ImportAttributes', base_config_1.TYPE],
['Math', base_config_1.TYPE_VALUE],
['Date', base_config_1.TYPE_VALUE],
['DateConstructor', base_config_1.TYPE],
['RegExpMatchArray', base_config_1.TYPE],
['RegExpExecArray', base_config_1.TYPE],
['RegExp', base_config_1.TYPE_VALUE],
['RegExpConstructor', base_config_1.TYPE],
['Error', base_config_1.TYPE_VALUE],
['ErrorConstructor', base_config_1.TYPE],
['EvalError', base_config_1.TYPE_VALUE],
['EvalErrorConstructor', base_config_1.TYPE],
['RangeError', base_config_1.TYPE_VALUE],
['RangeErrorConstructor', base_config_1.TYPE],
['ReferenceError', base_config_1.TYPE_VALUE],
['ReferenceErrorConstructor', base_config_1.TYPE],
['SyntaxError', base_config_1.TYPE_VALUE],
['SyntaxErrorConstructor', base_config_1.TYPE],
['TypeError', base_config_1.TYPE_VALUE],
['TypeErrorConstructor', base_config_1.TYPE],
['URIError', base_config_1.TYPE_VALUE],
['URIErrorConstructor', base_config_1.TYPE],
['JSON', base_config_1.TYPE_VALUE],
['ReadonlyArray', base_config_1.TYPE],
['ConcatArray', base_config_1.TYPE],
['Array', base_config_1.TYPE_VALUE],
['ArrayConstructor', base_config_1.TYPE],
['TypedPropertyDescriptor', base_config_1.TYPE],
['PromiseConstructorLike', base_config_1.TYPE],
['PromiseLike', base_config_1.TYPE],
['Promise', base_config_1.TYPE],
['Awaited', base_config_1.TYPE],
['ArrayLike', base_config_1.TYPE],
['Partial', base_config_1.TYPE],
['Required', base_config_1.TYPE],
['Readonly', base_config_1.TYPE],
['Pick', base_config_1.TYPE],
['Record', base_config_1.TYPE],
['Exclude', base_config_1.TYPE],
['Extract', base_config_1.TYPE],
['Omit', base_config_1.TYPE],
['NonNullable', base_config_1.TYPE],
['Parameters', base_config_1.TYPE],
['ConstructorParameters', base_config_1.TYPE],
['ReturnType', base_config_1.TYPE],
['InstanceType', base_config_1.TYPE],
['Uppercase', base_config_1.TYPE],
['Lowercase', base_config_1.TYPE],
['Capitalize', base_config_1.TYPE],
['Uncapitalize', base_config_1.TYPE],
['NoInfer', base_config_1.TYPE],
['ThisType', base_config_1.TYPE],
['WeakKeyTypes', base_config_1.TYPE],
['WeakKey', base_config_1.TYPE],
['ArrayBuffer', base_config_1.TYPE_VALUE],
['ArrayBufferTypes', base_config_1.TYPE],
['ArrayBufferLike', base_config_1.TYPE],
['ArrayBufferConstructor', base_config_1.TYPE],
['ArrayBufferView', base_config_1.TYPE],
['DataView', base_config_1.TYPE_VALUE],
['DataViewConstructor', base_config_1.TYPE],
['Int8Array', base_config_1.TYPE_VALUE],
['Int8ArrayConstructor', base_config_1.TYPE],
['Uint8Array', base_config_1.TYPE_VALUE],
['Uint8ArrayConstructor', base_config_1.TYPE],
['Uint8ClampedArray', base_config_1.TYPE_VALUE],
['Uint8ClampedArrayConstructor', base_config_1.TYPE],
['Int16Array', base_config_1.TYPE_VALUE],
['Int16ArrayConstructor', base_config_1.TYPE],
['Uint16Array', base_config_1.TYPE_VALUE],
['Uint16ArrayConstructor', base_config_1.TYPE],
['Int32Array', base_config_1.TYPE_VALUE],
['Int32ArrayConstructor', base_config_1.TYPE],
['Uint32Array', base_config_1.TYPE_VALUE],
['Uint32ArrayConstructor', base_config_1.TYPE],
['Float32Array', base_config_1.TYPE_VALUE],
['Float32ArrayConstructor', base_config_1.TYPE],
['Float64Array', base_config_1.TYPE_VALUE],
['Float64ArrayConstructor', base_config_1.TYPE],
['Intl', base_config_1.TYPE_VALUE],
],
};

View File

@@ -0,0 +1,34 @@
base64-js
=========
`base64-js` does basic base64 encoding/decoding in pure JS.
[![build status](https://secure.travis-ci.org/beatgammit/base64-js.png)](http://travis-ci.org/beatgammit/base64-js)
Many browsers already have base64 encoding/decoding functionality, but it is for text data, not all-purpose binary data.
Sometimes encoding/decoding binary data in the browser is useful, and that is what this module does.
## install
With [npm](https://npmjs.org) do:
`npm install base64-js` and `var base64js = require('base64-js')`
For use in web browsers do:
`<script src="base64js.min.js"></script>`
[Get supported base64-js with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-base64-js?utm_source=npm-base64-js&utm_medium=referral&utm_campaign=readme)
## methods
`base64js` has three exposed functions, `byteLength`, `toByteArray` and `fromByteArray`, which both take a single argument.
* `byteLength` - Takes a base64 string and returns length of byte array
* `toByteArray` - Takes a base64 string and returns a byte array
* `fromByteArray` - Takes a byte array and returns a base64 string
## license
MIT

View File

@@ -0,0 +1,16 @@
export declare const enum OptionKeys {
ArrayDestructuring = "arrayDestructuring",
ArrowParameter = "arrowParameter",
MemberVariableDeclaration = "memberVariableDeclaration",
ObjectDestructuring = "objectDestructuring",
Parameter = "parameter",
PropertyDeclaration = "propertyDeclaration",
VariableDeclaration = "variableDeclaration",
VariableDeclarationIgnoreFunction = "variableDeclarationIgnoreFunction"
}
export type Options = [Partial<Record<OptionKeys, boolean>>];
export type MessageIds = 'expectedTypedef' | 'expectedTypedefNamed';
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;

View File

@@ -0,0 +1 @@
{"version":3,"file":"hkdf.d.ts","sourceRoot":"","sources":["src/hkdf.ts"],"names":[],"mappings":"AAMA,OAAO,EAAkB,KAAK,KAAK,EAAS,KAAK,KAAK,EAAW,MAAM,YAAY,CAAC;AAEpF;;;;;;GAMG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,KAAK,GAAG,UAAU,CAOzE;AAKD;;;;;;GAMG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,KAAK,EAAE,MAAM,GAAE,MAAW,GAAG,UAAU,CA4B7F;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,IAAI,GACf,MAAM,KAAK,EACX,KAAK,KAAK,EACV,MAAM,KAAK,GAAG,SAAS,EACvB,MAAM,KAAK,GAAG,SAAS,EACvB,QAAQ,MAAM,KACb,UAAkE,CAAC"}

View File

@@ -0,0 +1,411 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bls = bls;
/**
* BLS != BLS.
* The file implements BLS (Boneh-Lynn-Shacham) signatures.
* Used in both BLS (Barreto-Lynn-Scott) and BN (Barreto-Naehrig)
* families of pairing-friendly curves.
* Consists of two curves: G1 and G2:
* - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4.
* - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1
* - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in
* Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not.
* Pairing is used to aggregate and verify signatures.
* There are two modes of operation:
* - Long signatures: X-byte keys + 2X-byte sigs (G1 keys + G2 sigs).
* - Short signatures: 2X-byte keys + X-byte sigs (G2 keys + G1 sigs).
* @module
**/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const utils_ts_1 = require("../utils.js");
const curve_ts_1 = require("./curve.js");
const hash_to_curve_ts_1 = require("./hash-to-curve.js");
const modular_ts_1 = require("./modular.js");
const weierstrass_ts_1 = require("./weierstrass.js");
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);
// Not used with BLS12-381 (no sequential `11` in X). Useful for other curves.
function NAfDecomposition(a) {
const res = [];
// a>1 because of marker bit
for (; a > _1n; a >>= _1n) {
if ((a & _1n) === _0n)
res.unshift(0);
else if ((a & _3n) === _3n) {
res.unshift(-1);
a += _1n;
}
else
res.unshift(1);
}
return res;
}
function aNonEmpty(arr) {
if (!Array.isArray(arr) || arr.length === 0)
throw new Error('expected non-empty array');
}
// This should be enough for bn254, no need to export full stuff?
function createBlsPairing(fields, G1, G2, params) {
const { Fp2, Fp12 } = fields;
const { twistType, ateLoopSize, xNegative, postPrecompute } = params;
// Applies sparse multiplication as line function
let lineFunction;
if (twistType === 'multiplicative') {
lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul014(f, c0, Fp2.mul(c1, Px), Fp2.mul(c2, Py));
}
else if (twistType === 'divisive') {
// NOTE: it should be [c0, c1, c2], but we use different order here to reduce complexity of
// precompute calculations.
lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul034(f, Fp2.mul(c2, Py), Fp2.mul(c1, Px), c0);
}
else
throw new Error('bls: unknown twist type');
const Fp2div2 = Fp2.div(Fp2.ONE, Fp2.mul(Fp2.ONE, _2n));
function pointDouble(ell, Rx, Ry, Rz) {
const t0 = Fp2.sqr(Ry); // Ry²
const t1 = Fp2.sqr(Rz); // Rz²
const t2 = Fp2.mulByB(Fp2.mul(t1, _3n)); // 3 * T1 * B
const t3 = Fp2.mul(t2, _3n); // 3 * T2
const t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0
const c0 = Fp2.sub(t2, t0); // T2 - T0 (i)
const c1 = Fp2.mul(Fp2.sqr(Rx), _3n); // 3 * Rx²
const c2 = Fp2.neg(t4); // -T4 (-h)
ell.push([c0, c1, c2]);
Rx = Fp2.mul(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), Fp2div2); // ((T0 - T3) * Rx * Ry) / 2
Ry = Fp2.sub(Fp2.sqr(Fp2.mul(Fp2.add(t0, t3), Fp2div2)), Fp2.mul(Fp2.sqr(t2), _3n)); // ((T0 + T3) / 2)² - 3 * T2²
Rz = Fp2.mul(t0, t4); // T0 * T4
return { Rx, Ry, Rz };
}
function pointAdd(ell, Rx, Ry, Rz, Qx, Qy) {
// Addition
const t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz
const t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz
const c0 = Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)); // T0 * Qx - T1 * Qy == Ry * Qx - Rx * Qy
const c1 = Fp2.neg(t0); // -T0 == Qy * Rz - Ry
const c2 = t1; // == Rx - Qx * Rz
ell.push([c0, c1, c2]);
const t2 = Fp2.sqr(t1); // T1²
const t3 = Fp2.mul(t2, t1); // T2 * T1
const t4 = Fp2.mul(t2, Rx); // T2 * Rx
const t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz)); // T3 - 2 * T4 + T0² * Rz
Rx = Fp2.mul(t1, t5); // T1 * T5
Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry
Rz = Fp2.mul(Rz, t3); // Rz * T3
return { Rx, Ry, Rz };
}
// Pre-compute coefficients for sparse multiplication
// Point addition and point double calculations is reused for coefficients
// pointAdd happens only if bit set, so wNAF is reasonable. Unfortunately we cannot combine
// add + double in windowed precomputes here, otherwise it would be single op (since X is static)
const ATE_NAF = NAfDecomposition(ateLoopSize);
const calcPairingPrecomputes = (0, utils_ts_1.memoized)((point) => {
const p = point;
const { x, y } = p.toAffine();
// prettier-ignore
const Qx = x, Qy = y, negQy = Fp2.neg(y);
// prettier-ignore
let Rx = Qx, Ry = Qy, Rz = Fp2.ONE;
const ell = [];
for (const bit of ATE_NAF) {
const cur = [];
({ Rx, Ry, Rz } = pointDouble(cur, Rx, Ry, Rz));
if (bit)
({ Rx, Ry, Rz } = pointAdd(cur, Rx, Ry, Rz, Qx, bit === -1 ? negQy : Qy));
ell.push(cur);
}
if (postPrecompute) {
const last = ell[ell.length - 1];
postPrecompute(Rx, Ry, Rz, Qx, Qy, pointAdd.bind(null, last));
}
return ell;
});
function millerLoopBatch(pairs, withFinalExponent = false) {
let f12 = Fp12.ONE;
if (pairs.length) {
const ellLen = pairs[0][0].length;
for (let i = 0; i < ellLen; i++) {
f12 = Fp12.sqr(f12); // This allows us to do sqr only one time for all pairings
// NOTE: we apply multiple pairings in parallel here
for (const [ell, Px, Py] of pairs) {
for (const [c0, c1, c2] of ell[i])
f12 = lineFunction(c0, c1, c2, f12, Px, Py);
}
}
}
if (xNegative)
f12 = Fp12.conjugate(f12);
return withFinalExponent ? Fp12.finalExponentiate(f12) : f12;
}
// Calculates product of multiple pairings
// This up to x2 faster than just `map(({g1, g2})=>pairing({g1,g2}))`
function pairingBatch(pairs, withFinalExponent = true) {
const res = [];
// Cache precomputed toAffine for all points
(0, curve_ts_1.normalizeZ)(G1, pairs.map(({ g1 }) => g1));
(0, curve_ts_1.normalizeZ)(G2, pairs.map(({ g2 }) => g2));
for (const { g1, g2 } of pairs) {
if (g1.is0() || g2.is0())
throw new Error('pairing is not available for ZERO point');
// This uses toAffine inside
g1.assertValidity();
g2.assertValidity();
const Qa = g1.toAffine();
res.push([calcPairingPrecomputes(g2), Qa.x, Qa.y]);
}
return millerLoopBatch(res, withFinalExponent);
}
// Calculates bilinear pairing
function pairing(Q, P, withFinalExponent = true) {
return pairingBatch([{ g1: Q, g2: P }], withFinalExponent);
}
return {
Fp12, // NOTE: we re-export Fp12 here because pairing results are Fp12!
millerLoopBatch,
pairing,
pairingBatch,
calcPairingPrecomputes,
};
}
function createBlsSig(blsPairing, PubCurve, SigCurve, SignatureCoder, isSigG1) {
const { Fp12, pairingBatch } = blsPairing;
function normPub(point) {
return point instanceof PubCurve.Point ? point : PubCurve.Point.fromHex(point);
}
function normSig(point) {
return point instanceof SigCurve.Point ? point : SigCurve.Point.fromHex(point);
}
function amsg(m) {
if (!(m instanceof SigCurve.Point))
throw new Error(`expected valid message hashed to ${!isSigG1 ? 'G2' : 'G1'} curve`);
return m;
}
// What matters here is what point pairing API accepts as G1 or G2, not actual size or names
const pair = !isSigG1
? (a, b) => ({ g1: a, g2: b })
: (a, b) => ({ g1: b, g2: a });
return {
// P = pk x G
getPublicKey(secretKey) {
// TODO: replace with
// const sec = PubCurve.Point.Fn.fromBytes(secretKey);
const sec = (0, weierstrass_ts_1._normFnElement)(PubCurve.Point.Fn, secretKey);
return PubCurve.Point.BASE.multiply(sec);
},
// S = pk x H(m)
sign(message, secretKey, unusedArg) {
if (unusedArg != null)
throw new Error('sign() expects 2 arguments');
// TODO: replace with
// PubCurve.Point.Fn.fromBytes(secretKey)
const sec = (0, weierstrass_ts_1._normFnElement)(PubCurve.Point.Fn, secretKey);
amsg(message).assertValidity();
return message.multiply(sec);
},
// Checks if pairing of public key & hash is equal to pairing of generator & signature.
// e(P, H(m)) == e(G, S)
// e(S, G) == e(H(m), P)
verify(signature, message, publicKey, unusedArg) {
if (unusedArg != null)
throw new Error('verify() expects 3 arguments');
signature = normSig(signature);
publicKey = normPub(publicKey);
const P = publicKey.negate();
const G = PubCurve.Point.BASE;
const Hm = amsg(message);
const S = signature;
// This code was changed in 1.9.x:
// Before it was G.negate() in G2, now it's always pubKey.negate
// e(P, -Q)===e(-P, Q)==e(P, Q)^-1. Negate can be done anywhere (as long it is done once per pair).
// We just moving sign, but since pairing is multiplicative, we doing X * X^-1 = 1
const exp = pairingBatch([pair(P, Hm), pair(G, S)]);
return Fp12.eql(exp, Fp12.ONE);
},
// https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407
// e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))
// TODO: maybe `{message: G2Hex, publicKey: G1Hex}[]` instead?
verifyBatch(signature, messages, publicKeys) {
aNonEmpty(messages);
if (publicKeys.length !== messages.length)
throw new Error('amount of public keys and messages should be equal');
const sig = normSig(signature);
const nMessages = messages;
const nPublicKeys = publicKeys.map(normPub);
// NOTE: this works only for exact same object
const messagePubKeyMap = new Map();
for (let i = 0; i < nPublicKeys.length; i++) {
const pub = nPublicKeys[i];
const msg = nMessages[i];
let keys = messagePubKeyMap.get(msg);
if (keys === undefined) {
keys = [];
messagePubKeyMap.set(msg, keys);
}
keys.push(pub);
}
const paired = [];
const G = PubCurve.Point.BASE;
try {
for (const [msg, keys] of messagePubKeyMap) {
const groupPublicKey = keys.reduce((acc, msg) => acc.add(msg));
paired.push(pair(groupPublicKey, msg));
}
paired.push(pair(G.negate(), sig));
return Fp12.eql(pairingBatch(paired), Fp12.ONE);
}
catch {
return false;
}
},
// Adds a bunch of public key points together.
// pk1 + pk2 + pk3 = pkA
aggregatePublicKeys(publicKeys) {
aNonEmpty(publicKeys);
publicKeys = publicKeys.map((pub) => normPub(pub));
const agg = publicKeys.reduce((sum, p) => sum.add(p), PubCurve.Point.ZERO);
agg.assertValidity();
return agg;
},
// Adds a bunch of signature points together.
// pk1 + pk2 + pk3 = pkA
aggregateSignatures(signatures) {
aNonEmpty(signatures);
signatures = signatures.map((sig) => normSig(sig));
const agg = signatures.reduce((sum, s) => sum.add(s), SigCurve.Point.ZERO);
agg.assertValidity();
return agg;
},
hash(messageBytes, DST) {
(0, utils_ts_1.abytes)(messageBytes);
const opts = DST ? { DST } : undefined;
return SigCurve.hashToCurve(messageBytes, opts);
},
Signature: SignatureCoder,
};
}
// G1_Point: ProjConstructor<bigint>, G2_Point: ProjConstructor<Fp2>,
function bls(CURVE) {
// Fields are specific for curve, so for now we'll need to pass them with opts
const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields;
// Point on G1 curve: (x, y)
const G1_ = (0, weierstrass_ts_1.weierstrassPoints)(CURVE.G1);
const G1 = Object.assign(G1_, (0, hash_to_curve_ts_1.createHasher)(G1_.Point, CURVE.G1.mapToCurve, {
...CURVE.htfDefaults,
...CURVE.G1.htfDefaults,
}));
// Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i)
const G2_ = (0, weierstrass_ts_1.weierstrassPoints)(CURVE.G2);
const G2 = Object.assign(G2_, (0, hash_to_curve_ts_1.createHasher)(G2_.Point, CURVE.G2.mapToCurve, {
...CURVE.htfDefaults,
...CURVE.G2.htfDefaults,
}));
const pairingRes = createBlsPairing(CURVE.fields, G1.Point, G2.Point, {
...CURVE.params,
postPrecompute: CURVE.postPrecompute,
});
const { millerLoopBatch, pairing, pairingBatch, calcPairingPrecomputes } = pairingRes;
const longSignatures = createBlsSig(pairingRes, G1, G2, CURVE.G2.Signature, false);
const shortSignatures = createBlsSig(pairingRes, G2, G1, CURVE.G1.ShortSignature, true);
const rand = CURVE.randomBytes || utils_ts_1.randomBytes;
const randomSecretKey = () => {
const length = (0, modular_ts_1.getMinHashLength)(Fr.ORDER);
return (0, modular_ts_1.mapHashToField)(rand(length), Fr.ORDER);
};
const utils = {
randomSecretKey,
randomPrivateKey: randomSecretKey,
calcPairingPrecomputes,
};
const { ShortSignature } = CURVE.G1;
const { Signature } = CURVE.G2;
function normP1Hash(point, htfOpts) {
return point instanceof G1.Point
? point
: shortSignatures.hash((0, utils_ts_1.ensureBytes)('point', point), htfOpts?.DST);
}
function normP2Hash(point, htfOpts) {
return point instanceof G2.Point
? point
: longSignatures.hash((0, utils_ts_1.ensureBytes)('point', point), htfOpts?.DST);
}
function getPublicKey(privateKey) {
return longSignatures.getPublicKey(privateKey).toBytes(true);
}
function getPublicKeyForShortSignatures(privateKey) {
return shortSignatures.getPublicKey(privateKey).toBytes(true);
}
function sign(message, privateKey, htfOpts) {
const Hm = normP2Hash(message, htfOpts);
const S = longSignatures.sign(Hm, privateKey);
return message instanceof G2.Point ? S : Signature.toBytes(S);
}
function signShortSignature(message, privateKey, htfOpts) {
const Hm = normP1Hash(message, htfOpts);
const S = shortSignatures.sign(Hm, privateKey);
return message instanceof G1.Point ? S : ShortSignature.toBytes(S);
}
function verify(signature, message, publicKey, htfOpts) {
const Hm = normP2Hash(message, htfOpts);
return longSignatures.verify(signature, Hm, publicKey);
}
function verifyShortSignature(signature, message, publicKey, htfOpts) {
const Hm = normP1Hash(message, htfOpts);
return shortSignatures.verify(signature, Hm, publicKey);
}
function aggregatePublicKeys(publicKeys) {
const agg = longSignatures.aggregatePublicKeys(publicKeys);
return publicKeys[0] instanceof G1.Point ? agg : agg.toBytes(true);
}
function aggregateSignatures(signatures) {
const agg = longSignatures.aggregateSignatures(signatures);
return signatures[0] instanceof G2.Point ? agg : Signature.toBytes(agg);
}
function aggregateShortSignatures(signatures) {
const agg = shortSignatures.aggregateSignatures(signatures);
return signatures[0] instanceof G1.Point ? agg : ShortSignature.toBytes(agg);
}
function verifyBatch(signature, messages, publicKeys, htfOpts) {
const Hm = messages.map((m) => normP2Hash(m, htfOpts));
return longSignatures.verifyBatch(signature, Hm, publicKeys);
}
G1.Point.BASE.precompute(4);
return {
longSignatures,
shortSignatures,
millerLoopBatch,
pairing,
pairingBatch,
verifyBatch,
fields: {
Fr,
Fp,
Fp2,
Fp6,
Fp12,
},
params: {
ateLoopSize: CURVE.params.ateLoopSize,
twistType: CURVE.params.twistType,
// deprecated
r: CURVE.params.r,
G1b: CURVE.G1.b,
G2b: CURVE.G2.b,
},
utils,
// deprecated
getPublicKey,
getPublicKeyForShortSignatures,
sign,
signShortSignature,
verify,
verifyShortSignature,
aggregatePublicKeys,
aggregateSignatures,
aggregateShortSignatures,
G1,
G2,
Signature,
ShortSignature,
};
}
//# sourceMappingURL=bls.js.map

View File

@@ -0,0 +1,99 @@
import { EventEmitter } from 'events'
import * as workerThreads from 'worker_threads'
interface ThreadStreamOptions {
/**
* The size (in bytes) of the buffer.
* Must be greater than 4 (i.e. it must at least fit a 4-byte utf-8 char).
*
* Default: `4 * 1024 * 1024` = `4194304`
*/
bufferSize?: number,
/**
* The path to the Worker's main script or module.
* Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with ./ or ../, or a WHATWG URL object using file: or data: protocol.
* When using a data: URL, the data is interpreted based on MIME type using the ECMAScript module loader.
*
* {@link workerThreads.Worker()}
*/
filename: string | URL,
/**
* If `true`, write data synchronously; otherwise write data asynchronously.
*
* Default: `false`.
*/
sync?: boolean,
/**
* {@link workerThreads.WorkerOptions.workerData}
*
* Default: `{}`
*/
workerData?: any,
/**
* {@link workerThreads.WorkerOptions}
*
* Default: `{}`
*/
workerOpts?: workerThreads.WorkerOptions
}
declare class ThreadStream extends EventEmitter {
/**
* @param {ThreadStreamOptions} opts
*/
constructor(opts: ThreadStreamOptions)
/**
* Write some data to the stream.
*
* **Please note that this method should not throw an {Error} if something goes wrong but emit an error event.**
* @param {string} data data to write.
* @returns {boolean} false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data or if it fails to write; otherwise true.
*/
write(data: string): boolean
/**
* Signal that no more data will be written.
*
* **Please note that this method should not throw an {Error} if something goes wrong but emit an error event.**
*
* Calling the {@link write()} method after calling {@link end()} will emit an error.
*/
end(): void
/**
* Flush the stream asynchronously.
*
* The callback is invoked once data has been consumed by the worker and the
* worker destination has acknowledged the flush.
*/
flush(cb?: (err?: Error) => void): void
/**
* Flush the stream synchronously.
* This method should be called in the shutdown phase to make sure that all data has been flushed.
*
* **Please note that this method will throw an {Error} if something goes wrong.**
*
* @throws {Error} if the stream is already flushing, if it fails to flush or if it takes more than 10 seconds to flush.
*/
flushSync(): void
/**
* Synchronously calls each of the listeners registered for the event named`eventName`, in the order they were registered, passing the supplied arguments
* to each.
*
* @param eventName the name of the event.
* @param args the arguments to be passed to the event handlers.
* @returns {boolean} `true` if the event had listeners, `false` otherwise.
*/
emit(eventName: string | symbol, ...args: any[]): boolean;
/**
* Post a message to the Worker with specified data and an optional list of transferable objects.
*
* @param eventName the name of the event, specifically 'message'.
* @param message message data to be sent to the Worker.
* @param transferList an optional list of transferable objects to be transferred to the Worker context.
* @returns {boolean} true if the event had listeners, false otherwise.
*/
emit(eventName: 'message', message: any, transferList?: workerThreads.TransferListItem[]): boolean
}
export = ThreadStream;

View File

@@ -0,0 +1 @@
{"version":3,"file":"fft.d.ts","sourceRoot":"","sources":["../src/abstract/fft.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAE3C,MAAM,WAAW,gBAAgB,CAAC,CAAC;IACjC,CAAC,KAAK,EAAE,MAAM,GAAG,CAAC,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1C,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC;CAClC;AASD,+CAA+C;AAC/C,wBAAgB,YAAY,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAG/C;AAED,wBAAgB,cAAc,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAIhD;AAED,wBAAgB,WAAW,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAK3D;AAED,gFAAgF;AAChF,wBAAgB,IAAI,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAGtC;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,gBAAgB,CAAC,GAAG,CAAC,EAAE,MAAM,EAAE,CAAC,GAAG,CAAC,CAchF;AAED,wBAAgB,sBAAsB,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,GAAG,CAAC,EAAE,CAE1D;AASD,MAAM,MAAM,YAAY,GAAG;IACzB,KAAK,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,EAAE,CAAC;IAClC,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAC5B,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAChC,KAAK,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAAC;IAChC,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB,CAAC;AACF,wFAAwF;AACxF,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,YAAY,CAiEpF;AAED,MAAM,MAAM,UAAU,CAAC,CAAC,IAAI,gBAAgB,CAAC,CAAC,CAAC,CAAC;AAEhD;;;;;GAKG;AACH,MAAM,MAAM,OAAO,CAAC,CAAC,EAAE,CAAC,IAAI;IAC1B,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;IACvB,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;IACvB,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC;IAC5B,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI;IAC3B,CAAC,EAAE,MAAM,CAAC;IACV,KAAK,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC;IACrB,GAAG,EAAE,OAAO,CAAC;IACb,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,GAAG,CAAC,EAAE,OAAO,CAAC;CACf,CAAC;AAEF,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,UAAU,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC;AAEvE;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,OAAO,GAAI,CAAC,EAAE,CAAC,EAAE,GAAG,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,UAAU,WAAW,CAAC,CAAC,CAAC,KAAG,WAAW,CAAC,CAAC,CA2CvF,CAAC;AAEF,MAAM,MAAM,UAAU,CAAC,CAAC,IAAI;IAC1B,MAAM,CAAC,CAAC,SAAS,UAAU,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,QAAQ,CAAC,EAAE,OAAO,EAAE,SAAS,CAAC,EAAE,OAAO,GAAG,CAAC,CAAC;IACvF,OAAO,CAAC,CAAC,SAAS,UAAU,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,QAAQ,CAAC,EAAE,OAAO,EAAE,SAAS,CAAC,EAAE,OAAO,GAAG,CAAC,CAAC;CACzF,CAAC;AAEF;;;GAGG;AACH,wBAAgB,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,YAAY,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,EAAE,MAAM,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,CAoCnF;AAED,MAAM,MAAM,YAAY,CAAC,CAAC,SAAS,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;AAEnF,MAAM,MAAM,MAAM,CAAC,CAAC,SAAS,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI;IAC/C,KAAK,EAAE,YAAY,CAAC;IACpB,MAAM,EAAE,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,MAAM,CAAC;IACzB,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC,CAAC;IACjC,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;IACvB,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;IACvB,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC3B,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;IACvB,QAAQ,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;IAC5B,KAAK,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,MAAM,KAAK,CAAC,CAAC;IACnC,KAAK,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;IAEnB,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,KAAK,CAAC,CAAC;IAC5B,QAAQ,EAAE;QACR,KAAK,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC,CAAC;QAC9B,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;KACzB,CAAC;IACF,QAAQ,EAAE;QACR,KAAK,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,OAAO,KAAK,CAAC,CAAC;QAC7C,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,EAAE,OAAO,KAAK,CAAC,CAAC;KACxC,CAAC;IAEF,SAAS,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,CAAC;CAC5B,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,IAAI,CAAC,CAAC,EACpB,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,EAChB,KAAK,EAAE,YAAY,EACnB,MAAM,CAAC,EAAE,SAAS,EAClB,GAAG,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC,EACnB,MAAM,CAAC,EAAE,MAAM,GACd,MAAM,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;AAClB,wBAAgB,IAAI,CAAC,CAAC,EAAE,CAAC,SAAS,UAAU,CAAC,CAAC,CAAC,EAC7C,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,EAChB,KAAK,EAAE,YAAY,EACnB,MAAM,EAAE,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC,EAC1B,GAAG,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC,EACnB,MAAM,CAAC,EAAE,MAAM,GACd,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1,13 @@
"use strict";
var _get_prototype_of = require("./_get_prototype_of.cjs");
function _super_prop_base(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = _get_prototype_of._(object);
if (object === null) break;
}
return object;
}
exports._ = _super_prop_base;

View File

@@ -0,0 +1,114 @@
import * as util from "../core/util.js";
const error = () => {
const Sizable = {
string: { unit: "کاراکتر", verb: "داشته باشد" },
file: { unit: "بایت", verb: "داشته باشد" },
array: { unit: "آیتم", verb: "داشته باشد" },
set: { unit: "آیتم", verb: "داشته باشد" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "ورودی",
email: "آدرس ایمیل",
url: "URL",
emoji: "ایموجی",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "تاریخ و زمان ایزو",
date: "تاریخ ایزو",
time: "زمان ایزو",
duration: "مدت زمان ایزو",
ipv4: "IPv4 آدرس",
ipv6: "IPv6 آدرس",
cidrv4: "IPv4 دامنه",
cidrv6: "IPv6 دامنه",
base64: "base64-encoded رشته",
base64url: "base64url-encoded رشته",
json_string: "JSON رشته",
e164: "E.164 عدد",
jwt: "JWT",
template_literal: "ورودی",
};
const TypeDictionary = {
nan: "NaN",
number: "عدد",
array: "آرایه",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
if (/^[A-Z]/.test(issue.expected)) {
return `ورودی نامعتبر: می‌بایست instanceof ${issue.expected} می‌بود، ${received} دریافت شد`;
}
return `ورودی نامعتبر: می‌بایست ${expected} می‌بود، ${received} دریافت شد`;
}
case "invalid_value":
if (issue.values.length === 1) {
return `ورودی نامعتبر: می‌بایست ${util.stringifyPrimitive(issue.values[0])} می‌بود`;
}
return `گزینه نامعتبر: می‌بایست یکی از ${util.joinValues(issue.values, "|")} می‌بود`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing) {
return `خیلی بزرگ: ${issue.origin ?? "مقدار"} باید ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عنصر"} باشد`;
}
return `خیلی بزرگ: ${issue.origin ?? "مقدار"} باید ${adj}${issue.maximum.toString()} باشد`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `خیلی کوچک: ${issue.origin} باید ${adj}${issue.minimum.toString()} ${sizing.unit} باشد`;
}
return `خیلی کوچک: ${issue.origin} باید ${adj}${issue.minimum.toString()} باشد`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with") {
return `رشته نامعتبر: باید با "${_issue.prefix}" شروع شود`;
}
if (_issue.format === "ends_with") {
return `رشته نامعتبر: باید با "${_issue.suffix}" تمام شود`;
}
if (_issue.format === "includes") {
return `رشته نامعتبر: باید شامل "${_issue.includes}" باشد`;
}
if (_issue.format === "regex") {
return `رشته نامعتبر: باید با الگوی ${_issue.pattern} مطابقت داشته باشد`;
}
return `${FormatDictionary[_issue.format] ?? issue.format} نامعتبر`;
}
case "not_multiple_of":
return `عدد نامعتبر: باید مضرب ${issue.divisor} باشد`;
case "unrecognized_keys":
return `کلید${issue.keys.length > 1 ? "های" : ""} ناشناس: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `کلید ناشناس در ${issue.origin}`;
case "invalid_union":
return `ورودی نامعتبر`;
case "invalid_element":
return `مقدار نامعتبر در ${issue.origin}`;
default:
return `ورودی نامعتبر`;
}
};
};
export default function () {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1,26 @@
"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.scripthost = void 0;
const base_config_1 = require("./base-config");
exports.scripthost = {
libs: [],
variables: [
['ActiveXObject', base_config_1.TYPE_VALUE],
['ITextWriter', base_config_1.TYPE],
['TextStreamBase', base_config_1.TYPE],
['TextStreamWriter', base_config_1.TYPE],
['TextStreamReader', base_config_1.TYPE],
['SafeArray', base_config_1.TYPE_VALUE],
['Enumerator', base_config_1.TYPE_VALUE],
['EnumeratorConstructor', base_config_1.TYPE],
['VBArray', base_config_1.TYPE_VALUE],
['VBArrayConstructor', base_config_1.TYPE],
['VarDate', base_config_1.TYPE_VALUE],
['DateConstructor', base_config_1.TYPE],
['Date', base_config_1.TYPE],
],
};

View File

@@ -0,0 +1,35 @@
{
"keys-while": {
"name": "keys-while",
"browser": "IE 10.0.0 (Windows 7 0.0.0)",
"suite": "iter",
"hz": 35966.149453114274,
"success": true,
"fastest": true,
"rme": 0.022718710100452157,
"rhz": 1,
"sampleSize": 170
},
"keys-for": {
"name": "keys-for",
"browser": "IE 10.0.0 (Windows 7 0.0.0)",
"suite": "iter",
"hz": 34156.64425441182,
"success": true,
"fastest": true,
"rme": 0.026098683427836902,
"rhz": 0.9496886593027886,
"sampleSize": 167
},
"incr-for": {
"name": "incr-for",
"browser": "IE 10.0.0 (Windows 7 0.0.0)",
"suite": "iter",
"hz": 14980.832916171697,
"success": true,
"fastest": false,
"rme": 0.029043619258269707,
"rhz": 0.416525904050441,
"sampleSize": 164
}
}

View File

@@ -0,0 +1,19 @@
import { TSESTree } from '@typescript-eslint/utils';
import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util';
declare const baseRule: import("@typescript-eslint/utils/ts-eslint").RuleModule<"unusedExpression", [{
allowShortCircuit?: boolean;
allowTaggedTemplates?: boolean;
allowTernary?: boolean;
}], unknown, {
ExpressionStatement(node: TSESTree.ExpressionStatement): void;
}>;
export type MessageIds = InferMessageIdsTypeFromRule<typeof baseRule>;
export type Options = InferOptionsTypeFromRule<typeof baseRule>;
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"unusedExpression", [{
allowShortCircuit?: boolean;
allowTaggedTemplates?: boolean;
allowTernary?: boolean;
}], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
name: string;
};
export default _default;

View File

@@ -0,0 +1 @@
{"version":3,"file":"symbolFlags.enum.js","sourceRoot":"","sources":["../../src/enums/symbolFlags.enum.ts"],"names":[],"mappings":"AAAA,iGAAiG;AAEjG,MAAM,CAAN,IAAY,WAqEX;AArED,WAAY,WAAW;IACnB,6CAAQ,CAAA;IACR,iFAA+B,CAAA;IAC/B,2EAA4B,CAAA;IAC5B,qDAAiB,CAAA;IACjB,yDAAmB,CAAA;IACnB,sDAAiB,CAAA;IACjB,gDAAc,CAAA;IACd,wDAAkB,CAAA;IAClB,yDAAkB,CAAA;IAClB,6DAAoB,CAAA;IACpB,6DAAoB,CAAA;IACpB,sEAAyB,CAAA;IACzB,8DAAqB,CAAA;IACrB,kEAAuB,CAAA;IACvB,oDAAgB,CAAA;IAChB,+DAAqB,CAAA;IACrB,+DAAqB,CAAA;IACrB,+DAAqB,CAAA;IACrB,4DAAmB,CAAA;IACnB,oEAAuB,CAAA;IACvB,4DAAmB,CAAA;IACnB,iEAAqB,CAAA;IACrB,qDAAe,CAAA;IACf,6DAAmB,CAAA;IACnB,+DAAoB,CAAA;IACpB,4DAAkB,CAAA;IAClB,8DAAmB,CAAA;IACnB,gEAAoB,CAAA;IACpB,uEAAuB,CAAA;IACvB,mFAA6B,CAAA;IAC7B,mFAA6B,CAAA;IAC7B,sEAAsB,CAAA;IACtB,mDAAiB,CAAA;IACjB,+CAA8B,CAAA;IAC9B,qDAAuD,CAAA;IACvD,oDAAqI,CAAA;IACrI,kDAAsF,CAAA;IACtF,0DAAgD,CAAA;IAChD,oDAAsC,CAAA;IACtC,yDAAoC,CAAA;IACpC,sGAAgE,CAAA;IAChE,gGAAmC,CAAA;IACnC,4EAAyB,CAAA;IACzB,yEAAiD,CAAA;IACjD,8EAAiC,CAAA;IACjC,0EAA4D,CAAA;IAC5D,oEAAsE,CAAA;IACtE,4EAA+C,CAAA;IAC/C,gFAAmE,CAAA;IACnE,4EAA+C,CAAA;IAC/C,gFAA6E,CAAA;IAC7E,mFAA8B,CAAA;IAC9B,sEAAgC,CAAA;IAChC,+EAAuD,CAAA;IACvD,+EAAuD,CAAA;IACvD,0EAAoC,CAAA;IACpC,oFAA6C,CAAA;IAC7C,4EAAwB,CAAA;IACxB,qEAAqB,CAAA;IACrB,mEAA0F,CAAA;IAC1F,mEAAsD,CAAA;IACtD,6DAAgD,CAAA;IAChD,6EAAwC,CAAA;IACxC,gEAA0C,CAAA;IAC1C,iGAA4D,CAAA;IAC5D,8GAAoE,CAAA;IACpE,mEAAoF,CAAA;IACpF,gFAAiF,CAAA;AACrF,CAAC,EArEW,WAAW,KAAX,WAAW,QAqEtB"}

View File

@@ -0,0 +1,68 @@
/**
* @fileoverview Disallow sparse arrays
* @author Nicholas C. Zakas
*/
"use strict";
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
docs: {
description: "Disallow sparse arrays",
recommended: true,
url: "https://eslint.org/docs/latest/rules/no-sparse-arrays",
},
schema: [],
messages: {
unexpectedSparseArray: "Unexpected comma in middle of array.",
},
},
create(context) {
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
return {
ArrayExpression(node) {
if (!node.elements.includes(null)) {
return;
}
const { sourceCode } = context;
let commaToken;
for (const [index, element] of node.elements.entries()) {
if (index === node.elements.length - 1 && element) {
return;
}
commaToken = sourceCode.getTokenAfter(
element ?? commaToken ?? sourceCode.getFirstToken(node),
astUtils.isCommaToken,
);
if (element) {
continue;
}
context.report({
node,
loc: commaToken.loc,
messageId: "unexpectedSparseArray",
});
}
},
};
},
};

View File

@@ -0,0 +1,59 @@
'use strict'
let list = {
comma(string) {
return list.split(string, [','], true)
},
space(string) {
let spaces = [' ', '\n', '\t']
return list.split(string, spaces)
},
split(string, separators, last) {
if (typeof string !== 'string') return []
let array = []
let current = ''
let split = false
let func = 0
let inQuote = false
let prevQuote = ''
let escape = false
for (let letter of string) {
if (escape) {
escape = false
} else if (letter === '\\') {
escape = true
} else if (inQuote) {
if (letter === prevQuote) {
inQuote = false
}
} else if (letter === '"' || letter === "'") {
inQuote = true
prevQuote = letter
} else if (letter === '(') {
func += 1
} else if (letter === ')') {
if (func > 0) func -= 1
} else if (func === 0) {
if (separators.includes(letter)) split = true
}
if (split) {
if (current !== '') array.push(current.trim())
current = ''
split = false
} else {
current += letter
}
}
if (last || current !== '') array.push(current.trim())
return array
}
}
module.exports = list
list.default = list

View File

@@ -0,0 +1,103 @@
'use strict';
var os = require('node:os');
var stdEnv = require('std-env');
var vite = require('vite');
const isNode = typeof process < "u" && typeof process.stdout < "u" && !process.versions?.deno && !globalThis.window;
const isDeno = typeof process < "u" && typeof process.stdout < "u" && process.versions?.deno !== void 0;
(isNode || isDeno) && process.platform === "win32";
(isNode || isDeno) && process.stdout?.isTTY && !stdEnv.isCI;
// if changed, update also jsdocs and docs
const defaultBrowserPort = 63315;
const defaultInclude = ["**/*.{test,spec}.?(c|m)[jt]s?(x)"];
const defaultExclude = ["**/node_modules/**", "**/.git/**"];
// These are the generic defaults for coverage. Providers may also set some provider specific defaults.
const coverageConfigDefaults = {
provider: "v8",
enabled: false,
clean: true,
cleanOnRerun: true,
reportsDirectory: "./coverage",
exclude: [],
reportOnFailure: false,
reporter: [
"text",
"html",
"clover",
"json"
],
allowExternal: false,
excludeAfterRemap: false,
processingConcurrency: Math.min(20, os.availableParallelism?.() ?? os.cpus().length),
ignoreClassMethods: [],
skipFull: false,
watermarks: {
statements: [50, 80],
functions: [50, 80],
branches: [50, 80],
lines: [50, 80]
}
};
const fakeTimersDefaults = {
loopLimit: 1e4,
shouldClearNativeTimers: true
};
const configDefaults = Object.freeze({
allowOnly: !stdEnv.isCI,
isolate: true,
watch: !stdEnv.isCI && process.stdin.isTTY && !stdEnv.isAgent,
globals: false,
environment: "node",
clearMocks: false,
restoreMocks: false,
mockReset: false,
unstubGlobals: false,
unstubEnvs: false,
include: defaultInclude,
exclude: defaultExclude,
teardownTimeout: 1e4,
forceRerunTriggers: ["**/package.json/**", "**/{vitest,vite}.config.*/**"],
update: false,
reporters: [],
silent: false,
hideSkippedTests: false,
api: false,
ui: false,
uiBase: "/__vitest__/",
open: !stdEnv.isCI,
css: { include: [] },
coverage: coverageConfigDefaults,
fakeTimers: fakeTimersDefaults,
maxConcurrency: 5,
dangerouslyIgnoreUnhandledErrors: false,
typecheck: {
checker: "tsc",
include: ["**/*.{test,spec}-d.?(c|m)[jt]s?(x)"],
exclude: defaultExclude
},
slowTestThreshold: 300,
disableConsoleIntercept: false,
detectAsyncLeaks: false
});
function defineConfig(config) {
return config;
}
function defineProject(config) {
return config;
}
Object.defineProperty(exports, "mergeConfig", {
enumerable: true,
get: function () { return vite.mergeConfig; }
});
exports.configDefaults = configDefaults;
exports.coverageConfigDefaults = coverageConfigDefaults;
exports.defaultBrowserPort = defaultBrowserPort;
exports.defaultExclude = defaultExclude;
exports.defaultInclude = defaultInclude;
exports.defineConfig = defineConfig;
exports.defineProject = defineProject;

View File

@@ -0,0 +1,362 @@
/**
* SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
*
* Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
* check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { sha256 } from '@noble/hashes/sha2.js';
import { randomBytes } from '@noble/hashes/utils.js';
import { createCurve, type CurveFnWithCreate } from './_shortw_utils.ts';
import type { CurveLengths } from './abstract/curve.ts';
import {
createHasher,
type H2CHasher,
type H2CMethod,
isogenyMap,
} from './abstract/hash-to-curve.ts';
import { Field, mapHashToField, mod, pow2 } from './abstract/modular.ts';
import {
_normFnElement,
type EndomorphismOpts,
mapToCurveSimpleSWU,
type WeierstrassPoint as PointType,
type WeierstrassOpts,
type WeierstrassPointCons,
} from './abstract/weierstrass.ts';
import type { Hex, PrivKey } from './utils.ts';
import {
bytesToNumberBE,
concatBytes,
ensureBytes,
inRange,
numberToBytesBE,
utf8ToBytes,
} from './utils.ts';
// Seems like generator was produced from some seed:
// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`
// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n
const secp256k1_CURVE: WeierstrassOpts<bigint> = {
p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
h: BigInt(1),
a: BigInt(0),
b: BigInt(7),
Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
};
const secp256k1_ENDO: EndomorphismOpts = {
beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
basises: [
[BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],
[BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],
],
};
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
const _2n = /* @__PURE__ */ BigInt(2);
/**
* √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
* (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
*/
function sqrtMod(y: bigint): bigint {
const P = secp256k1_CURVE.p;
// prettier-ignore
const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
// prettier-ignore
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
const b2 = (y * y * y) % P; // x^3, 11
const b3 = (b2 * b2 * y) % P; // x^7
const b6 = (pow2(b3, _3n, P) * b3) % P;
const b9 = (pow2(b6, _3n, P) * b3) % P;
const b11 = (pow2(b9, _2n, P) * b2) % P;
const b22 = (pow2(b11, _11n, P) * b11) % P;
const b44 = (pow2(b22, _22n, P) * b22) % P;
const b88 = (pow2(b44, _44n, P) * b44) % P;
const b176 = (pow2(b88, _88n, P) * b88) % P;
const b220 = (pow2(b176, _44n, P) * b44) % P;
const b223 = (pow2(b220, _3n, P) * b3) % P;
const t1 = (pow2(b223, _23n, P) * b22) % P;
const t2 = (pow2(t1, _6n, P) * b2) % P;
const root = pow2(t2, _2n, P);
if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error('Cannot find square root');
return root;
}
const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
/**
* secp256k1 curve, ECDSA and ECDH methods.
*
* Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
*
* @example
* ```js
* import { secp256k1 } from '@noble/curves/secp256k1';
* const { secretKey, publicKey } = secp256k1.keygen();
* const msg = new TextEncoder().encode('hello');
* const sig = secp256k1.sign(msg, secretKey);
* const isValid = secp256k1.verify(sig, msg, publicKey) === true;
* ```
*/
export const secp256k1: CurveFnWithCreate = createCurve(
{ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO },
sha256
);
// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
const TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};
function taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array {
let tagP = TAGGED_HASH_PREFIXES[tag];
if (tagP === undefined) {
const tagH = sha256(utf8ToBytes(tag));
tagP = concatBytes(tagH, tagH);
TAGGED_HASH_PREFIXES[tag] = tagP;
}
return sha256(concatBytes(tagP, ...messages));
}
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
const pointToBytes = (point: PointType<bigint>) => point.toBytes(true).slice(1);
const Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();
const hasEven = (y: bigint) => y % _2n === _0n;
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv: PrivKey) {
const { Fn, BASE } = Pointk1;
const d_ = _normFnElement(Fn, priv);
const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside
const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
return { scalar, bytes: pointToBytes(p) };
}
/**
* lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
* @returns valid point checked for being on-curve
*/
function lift_x(x: bigint): PointType<bigint> {
const Fp = Fpk1;
if (!Fp.isValidNot0(x)) throw new Error('invalid x: Fail if x ≥ p');
const xx = Fp.create(x * x);
const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.
let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().
// Return the unique point P such that x(P) = x and
// y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.
if (!hasEven(y)) y = Fp.neg(y);
const p = Pointk1.fromAffine({ x, y });
p.assertValidity();
return p;
}
const num = bytesToNumberBE;
/**
* Create tagged hash, convert it to bigint, reduce modulo-n.
*/
function challenge(...args: Uint8Array[]): bigint {
return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));
}
/**
* Schnorr public key is just `x` coordinate of Point as per BIP340.
*/
function schnorrGetPublicKey(secretKey: Hex): Uint8Array {
return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)
}
/**
* Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
* auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.
*/
function schnorrSign(message: Hex, secretKey: PrivKey, auxRand: Hex = randomBytes(32)): Uint8Array {
const { Fn } = Pointk1;
const m = ensureBytes('message', message);
const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder
const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
// Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G
const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);
const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
sig.set(rx, 0);
sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
// If Verify(bytes(P), m, sig) (see below) returns failure, abort
if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');
return sig;
}
/**
* Verifies Schnorr signature.
* Will swallow errors & return false except for initial type validation of arguments.
*/
function schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean {
const { Fn, BASE } = Pointk1;
const sig = ensureBytes('signature', signature, 64);
const m = ensureBytes('message', message);
const pub = ensureBytes('publicKey', publicKey, 32);
try {
const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails
const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
if (!inRange(r, _1n, secp256k1_CURVE.p)) return false;
const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
if (!inRange(s, _1n, secp256k1_CURVE.n)) return false;
// int(challenge(bytes(r)||bytes(P)||m))%n
const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
// R = s⋅G - e⋅P, where -eP == (n-e)P
const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
const { x, y } = R.toAffine();
// Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.
if (R.is0() || !hasEven(y) || x !== r) return false;
return true;
} catch (error) {
return false;
}
}
export type SecpSchnorr = {
keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };
getPublicKey: typeof schnorrGetPublicKey;
sign: typeof schnorrSign;
verify: typeof schnorrVerify;
Point: WeierstrassPointCons<bigint>;
utils: {
randomSecretKey: (seed?: Uint8Array) => Uint8Array;
pointToBytes: (point: PointType<bigint>) => Uint8Array;
lift_x: typeof lift_x;
taggedHash: typeof taggedHash;
/** @deprecated use `randomSecretKey` */
randomPrivateKey: (seed?: Uint8Array) => Uint8Array;
/** @deprecated use `utils` */
numberToBytesBE: typeof numberToBytesBE;
/** @deprecated use `utils` */
bytesToNumberBE: typeof bytesToNumberBE;
/** @deprecated use `modular` */
mod: typeof mod;
};
lengths: CurveLengths;
};
/**
* Schnorr signatures over secp256k1.
* https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
* @example
* ```js
* import { schnorr } from '@noble/curves/secp256k1';
* const { secretKey, publicKey } = schnorr.keygen();
* // const publicKey = schnorr.getPublicKey(secretKey);
* const msg = new TextEncoder().encode('hello');
* const sig = schnorr.sign(msg, secretKey);
* const isValid = schnorr.verify(sig, msg, publicKey);
* ```
*/
export const schnorr: SecpSchnorr = /* @__PURE__ */ (() => {
const size = 32;
const seedLength = 48;
const randomSecretKey = (seed = randomBytes(seedLength)): Uint8Array => {
return mapHashToField(seed, secp256k1_CURVE.n);
};
// TODO: remove
secp256k1.utils.randomSecretKey;
function keygen(seed?: Uint8Array) {
const secretKey = randomSecretKey(seed);
return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };
}
return {
keygen,
getPublicKey: schnorrGetPublicKey,
sign: schnorrSign,
verify: schnorrVerify,
Point: Pointk1,
utils: {
randomSecretKey: randomSecretKey,
randomPrivateKey: randomSecretKey,
taggedHash,
// TODO: remove
lift_x,
pointToBytes,
numberToBytesBE,
bytesToNumberBE,
mod,
},
lengths: {
secretKey: size,
publicKey: size,
publicKeyHasPrefix: false,
signature: size * 2,
seed: seedLength,
},
};
})();
const isoMap = /* @__PURE__ */ (() =>
isogenyMap(
Fpk1,
[
// xNum
[
'0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',
'0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',
'0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',
'0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',
],
// xDen
[
'0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',
'0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',
'0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
],
// yNum
[
'0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',
'0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',
'0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',
'0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',
],
// yDen
[
'0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',
'0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',
'0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',
'0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
],
].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]
))();
const mapSWU = /* @__PURE__ */ (() =>
mapToCurveSimpleSWU(Fpk1, {
A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),
B: BigInt('1771'),
Z: Fpk1.create(BigInt('-11')),
}))();
/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */
export const secp256k1_hasher: H2CHasher<bigint> = /* @__PURE__ */ (() =>
createHasher(
secp256k1.Point,
(scalars: bigint[]) => {
const { x, y } = mapSWU(Fpk1.create(scalars[0]));
return isoMap(x, y);
},
{
DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',
encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',
p: Fpk1.ORDER,
m: 1,
k: 128,
expand: 'xmd',
hash: sha256,
}
))();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const hashToCurve: H2CMethod<bigint> = /* @__PURE__ */ (() =>
secp256k1_hasher.hashToCurve)();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const encodeToCurve: H2CMethod<bigint> = /* @__PURE__ */ (() =>
secp256k1_hasher.encodeToCurve)();

View File

@@ -0,0 +1,14 @@
'use strict'
const { Writable } = require('stream')
async function run (opts) {
const stream = new Writable({
write (chunk, enc, cb) {
process.exit(1)
}
})
return stream
}
module.exports = run

View File

@@ -0,0 +1,812 @@
<a href="https://dotenvx.com/?utm_source=github&utm_medium=readme&utm_campaign=motdotla-dotenv&utm_content=banner"><img src="https://dotenvx.com/dotenv-banner.png" alt="dotenvx" /></a>
# dotenv [![NPM version](https://img.shields.io/npm/v/dotenv.svg?style=flat-square)](https://www.npmjs.com/package/dotenv) [![downloads](https://img.shields.io/npm/dw/dotenv)](https://www.npmjs.com/package/dotenv)
<img src="https://raw.githubusercontent.com/motdotla/dotenv/master/dotenv.svg" alt="dotenv" align="right" width="200" />
Dotenv is a zero-dependency module that loads environment variables from a `.env` file into [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env). Storing configuration in the environment separate from code is based on [The Twelve-Factor App](https://12factor.net/config) methodology.
[Watch the tutorial](https://www.youtube.com/watch?v=YtkZR0NFd1g)
&nbsp;
## Usage
Install it.
```sh
npm install dotenv --save
```
Create a `.env` file in the root of your project:
```ini
# .env
HELLO="Dotenv"
OPENAI_API_KEY="your-api-key-goes-here"
```
As early as possible in your application, import and configure dotenv:
```javascript
// index.js
require('dotenv').config()
// or import 'dotenv/config' // for esm
console.log(`Hello ${process.env.HELLO}`)
```
```sh
$ node index.js
◇ injected env (2) from .env
Hello Dotenv
```
That's it. `process.env` now has the keys and values you defined in your `.env` file.
&nbsp;
## Agent Usage
Install this repo as an agent skill package:
```sh
npx skills add motdotla/dotenv
```
```sh
# ask Claude or Codex to do things like:
set up dotenv
upgrade dotenv to dotenvx
```
&nbsp;
## Advanced
<details><summary>ES6</summary><br>
Import with [ES6](#how-do-i-use-dotenv-with-import):
```javascript
import 'dotenv/config'
```
ES6 import if you need to set config options:
```javascript
import dotenv from 'dotenv'
dotenv.config({ path: '/custom/path/to/.env' })
```
</details>
<details><summary>bun</summary><br>
```sh
bun add dotenv
```
</details>
<details><summary>yarn</summary><br>
```sh
yarn add dotenv
```
</details>
<details><summary>pnpm</summary><br>
```sh
pnpm add dotenv
```
</details>
<details><summary>Monorepos</summary><br>
For monorepos with a structure like `apps/backend/app.js`, put it the `.env` file in the root of the folder where your `app.js` process runs.
```ini
# app/backend/.env
S3_BUCKET="YOURS3BUCKET"
SECRET_KEY="YOURSECRETKEYGOESHERE"
```
</details>
<details><summary>Multiline Values</summary><br>
If you need multiline variables, for example private keys, those are now supported (`>= v15.0.0`) with line breaks:
```ini
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
...
Kh9NV...
...
-----END RSA PRIVATE KEY-----"
```
Alternatively, you can double quote strings and use the `\n` character:
```ini
PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nKh9NV...\n-----END RSA PRIVATE KEY-----\n"
```
</details>
<details><summary>Comments</summary><br>
Comments may be added to your file on their own line or inline:
```ini
# This is a comment
SECRET_KEY=YOURSECRETKEYGOESHERE # comment
SECRET_HASH="something-with-a-#-hash"
```
Comments begin where a `#` exists, so if your value contains a `#` please wrap it in quotes. This is a breaking change from `>= v15.0.0` and on.
</details>
<details><summary>Parsing</summary><br>
The engine which parses the contents of your file containing environment variables is available to use. It accepts a String or Buffer and will return an Object with the parsed keys and values.
```javascript
const dotenv = require('dotenv')
const buf = Buffer.from('BASIC=basic')
const config = dotenv.parse(buf) // will return an object
console.log(typeof config, config) // object { BASIC : 'basic' }
```
</details>
<details><summary>Preload</summary><br>
> Note: Consider using [`dotenvx`](https://github.com/dotenvx/dotenvx) instead of preloading. I am now doing (and recommending) so.
>
> It serves the same purpose (you do not need to require and load dotenv), adds better debugging, and works with ANY language, framework, or platform. [motdotla](https://not.la)
You can use the `--require` (`-r`) [command line option](https://nodejs.org/api/cli.html#-r---require-module) to preload dotenv. By doing this, you do not need to require and load dotenv in your application code.
```bash
$ node -r dotenv/config your_script.js
```
The configuration options below are supported as command line arguments in the format `dotenv_config_<option>=value`
```bash
$ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env dotenv_config_debug=true
```
Additionally, you can use environment variables to set configuration options. Command line arguments will precede these.
```bash
$ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js
```
```bash
$ DOTENV_CONFIG_ENCODING=latin1 DOTENV_CONFIG_DEBUG=true node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env
```
</details>
<details><summary>Variable Expansion</summary><br>
Use [dotenvx](https://github.com/dotenvx/dotenvx) for variable expansion.
Reference and expand variables already on your machine for use in your .env file.
```ini
# .env
USERNAME="username"
DATABASE_URL="postgres://${USERNAME}@localhost/my_database"
```
```js
// index.js
console.log('DATABASE_URL', process.env.DATABASE_URL)
```
```sh
$ dotenvx run --debug -- node index.js
⟐ injected env (2) from .env · dotenvx@1.59.1
DATABASE_URL postgres://username@localhost/my_database
```
</details>
<details><summary>Command Substitution</summary><br>
Use [dotenvx](https://github.com/dotenvx/dotenvx) for command substitution.
Add the output of a command to one of your variables in your .env file.
```ini
# .env
DATABASE_URL="postgres://$(whoami)@localhost/my_database"
```
```js
// index.js
console.log('DATABASE_URL', process.env.DATABASE_URL)
```
```sh
$ dotenvx run --debug -- node index.js
⟐ injected env (1) from .env · dotenvx@1.59.1
DATABASE_URL postgres://yourusername@localhost/my_database
```
</details>
<details><summary>Encryption</summary><br>
Use [dotenvx](https://github.com/dotenvx/dotenvx) for encryption.
Add encryption to your `.env` files with a single command.
```
$ dotenvx set HELLO Production -f .env.production
$ echo "console.log('Hello ' + process.env.HELLO)" > index.js
$ DOTENV_PRIVATE_KEY_PRODUCTION="<.env.production private key>" dotenvx run -- node index.js
⟐ injected env (2) from .env.production · dotenvx@1.59.1
Hello Production
```
[learn more](https://github.com/dotenvx/dotenvx?tab=readme-ov-file#encryption)
</details>
<details><summary>Multiple Environments</summary><br>
Use [dotenvx](https://github.com/dotenvx/dotenvx) to manage multiple environments.
Run any environment locally. Create a `.env.ENVIRONMENT` file and use `-f` to load it. It's straightforward, yet flexible.
```bash
$ echo "HELLO=production" > .env.production
$ echo "console.log('Hello ' + process.env.HELLO)" > index.js
$ dotenvx run -f=.env.production -- node index.js
Hello production
> ^^
```
or with multiple .env files
```bash
$ echo "HELLO=local" > .env.local
$ echo "HELLO=World" > .env
$ echo "console.log('Hello ' + process.env.HELLO)" > index.js
$ dotenvx run -f=.env.local -f=.env -- node index.js
Hello local
```
[more environment examples](https://dotenvx.com/docs/quickstart/environments?utm_source=github&utm_medium=readme&utm_campaign=motdotla-dotenv&utm_content=docs-environments)
</details>
<details><summary>Production</summary><br>
Use [dotenvx](https://github.com/dotenvx/dotenvx) for production deploys.
Create a `.env.production` file.
```sh
$ echo "HELLO=production" > .env.production
```
Encrypt it.
```sh
$ dotenvx encrypt -f .env.production
```
Set `DOTENV_PRIVATE_KEY_PRODUCTION` (found in `.env.keys`) on your server.
```
$ heroku config:set DOTENV_PRIVATE_KEY_PRODUCTION=value
```
Commit your `.env.production` file to code and deploy.
```
$ git add .env.production
$ git commit -m "encrypted .env.production"
$ git push heroku main
```
Dotenvx will decrypt and inject the secrets at runtime using `dotenvx run -- node index.js`.
</details>
<details><summary>Syncing</summary><br>
Use [dotenvx](https://github.com/dotenvx/dotenvx) to sync your .env files.
Encrypt them with `dotenvx encrypt -f .env` and safely include them in source control. Your secrets are securely synced with your git.
This still subscribes to the twelve-factor app rules by generating a decryption key separate from code.
</details>
<details><summary>More Examples</summary><br>
See [examples](https://github.com/dotenv-org/examples) of using dotenv with various frameworks, languages, and configurations.
* [nodejs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs)
* [nodejs (debug on)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs-debug)
* [nodejs (override on)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nodejs-override)
* [nodejs (processEnv override)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-custom-target)
* [esm](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-esm)
* [esm (preload)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-esm-preload)
* [typescript](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript)
* [typescript parse](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript-parse)
* [typescript config](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-typescript-config)
* [webpack](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-webpack)
* [webpack (plugin)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-webpack2)
* [react](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-react)
* [react (typescript)](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-react-typescript)
* [express](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-express)
* [nestjs](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-nestjs)
* [fastify](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-fastify)
</details>
&nbsp;
## FAQ
<details><summary>Should I commit my `.env` file?</summary><br/>
No.
Unless you encrypt it with [dotenvx](https://github.com/dotenvx/dotenvx). Then we recommend you do.
</details>
<details><summary>What about variable expansion?</summary><br/>
Use [dotenvx](https://github.com/dotenvx/dotenvx).
</details>
<details><summary>Should I have multiple `.env` files?</summary><br/>
We recommend creating one `.env` file per environment. Use `.env` for local/development, `.env.production` for production and so on. This still follows the twelve factor principles as each is attributed individually to its own environment. Avoid custom set ups that work in inheritance somehow (`.env.production` inherits values from `.env` for example). It is better to duplicate values if necessary across each `.env.environment` file.
> In a twelve-factor app, env vars are granular controls, each fully orthogonal to other env vars. They are never grouped together as “environments”, but instead are independently managed for each deploy. This is a model that scales up smoothly as the app naturally expands into more deploys over its lifetime.
>
> [The Twelve-Factor App](http://12factor.net/config)
Additionally, we recommend using [dotenvx](https://github.com/dotenvx/dotenvx) to encrypt and manage these.
</details>
<details><summary>How do I use dotenv with `import`?</summary><br/>
Simply..
```javascript
// index.mjs (ESM)
import 'dotenv/config' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
import express from 'express'
```
A little background..
> When you run a module containing an `import` declaration, the modules it imports are loaded first, then each module body is executed in a depth-first traversal of the dependency graph, avoiding cycles by skipping anything already executed.
>
> [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/)
What does this mean in plain language? It means you would think the following would work but it won't.
`errorReporter.mjs`:
```js
class Client {
constructor (apiKey) {
console.log('apiKey', apiKey)
this.apiKey = apiKey
}
}
export default new Client(process.env.API_KEY)
```
`index.mjs`:
```js
// Note: this is INCORRECT and will not work
import * as dotenv from 'dotenv'
dotenv.config()
import errorReporter from './errorReporter.mjs' // process.env.API_KEY will be blank!
```
`process.env.API_KEY` will be blank.
Instead, `index.mjs` should be written as..
```js
import 'dotenv/config'
import errorReporter from './errorReporter.mjs'
```
Does that make sense? It's a bit unintuitive, but it is how importing of ES6 modules work. Here is a [working example of this pitfall](https://github.com/dotenv-org/examples/tree/master/usage/dotenv-es6-import-pitfall).
There are two alternatives to this approach:
1. Preload with dotenvx: `dotenvx run -- node index.js` (_Note: you do not need to `import` dotenv with this approach_)
2. Create a separate file that will execute `config` first as outlined in [this comment on #133](https://github.com/motdotla/dotenv/issues/133#issuecomment-255298822)
</details>
<details><summary>Can I customize/write plugins for dotenv?</summary><br/>
Yes! `dotenv.config()` returns an object representing the parsed `.env` file. This gives you everything you need to continue setting values on `process.env`. For example:
```js
const dotenv = require('dotenv')
const variableExpansion = require('dotenv-expand')
const myEnv = dotenv.config()
variableExpansion(myEnv)
```
</details>
<details><summary>What rules does the parsing engine follow?</summary><br/>
The parsing engine currently supports the following rules:
- `BASIC=basic` becomes `{BASIC: 'basic'}`
- empty lines are skipped
- lines beginning with `#` are treated as comments
- `#` marks the beginning of a comment (unless when the value is wrapped in quotes)
- empty values become empty strings (`EMPTY=` becomes `{EMPTY: ''}`)
- inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`)
- whitespace is removed from both ends of unquoted values (see more on [`trim`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)) (`FOO= some value ` becomes `{FOO: 'some value'}`)
- single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`)
- single and double quoted values maintain whitespace from both ends (`FOO=" some value "` becomes `{FOO: ' some value '}`)
- double quoted values expand new lines (`MULTILINE="new\nline"` becomes
```
{MULTILINE: 'new
line'}
```
- backticks are supported (`` BACKTICK_KEY=`This has 'single' and "double" quotes inside of it.` ``)
</details>
<details><summary>What about syncing and securing .env files?</summary><br/>
Use [dotenvx](https://github.com/dotenvx/dotenvx) to unlock syncing encrypted .env files over git.
</details>
<details><summary>How do I specify config options with ES6 import?</summary><br/>
When using `import 'dotenv/config'`, you can't pass options directly. Here are a few ways to handle it.
**Option 1: Import and call `config()` yourself (Recommended)**
```javascript
// index.mjs
import dotenv from 'dotenv'
dotenv.config({
path: '/custom/path/to/.env',
debug: true
})
// Now import everything else
import express from 'express'
```
Because ES6 imports are hoisted, put the `dotenv` import and `config()` call at the very top, before any other imports that rely on `process.env`.
**Option 2: Use environment variables**
```bash
DOTENV_CONFIG_DEBUG=true DOTENV_CONFIG_PATH=/custom/path/to/.env node index.mjs
```
Then in your code you can keep the shorthand:
```javascript
import 'dotenv/config'
```
**Option 3: A tiny wrapper file**
Create `load-env.mjs`:
```javascript
import dotenv from 'dotenv'
dotenv.config({ path: '/custom/path/to/.env', debug: true })
```
Then in your main file:
```javascript
import './load-env.mjs'
import express from 'express'
```
Not the most elegant, but it works reliably when hoisting gets in the way.
</details>
<details><summary>What if I accidentally commit my `.env` file to code?</summary><br/>
Remove it, [remove git history](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/removing-sensitive-data-from-a-repository) and then install the [git pre-commit hook](https://github.com/dotenvx/dotenvx#pre-commit) to prevent this from ever happening again.
```
npm i -g @dotenvx/dotenvx
dotenvx precommit --install
```
</details>
<details><summary>What happens to environment variables that were already set?</summary><br/>
By default, we will never modify any environment variables that have already been set. In particular, if there is a variable in your `.env` file which collides with one that already exists in your environment, then that variable will be skipped.
If instead, you want to override `process.env` use the `override` option.
```javascript
require('dotenv').config({ override: true })
```
</details>
<details><summary>How can I prevent committing my `.env` file to a Docker build?</summary><br/>
Use the [docker prebuild hook](https://dotenvx.com/docs/features/prebuild?utm_source=github&utm_medium=readme&utm_campaign=motdotla-dotenv&utm_content=docs-prebuild).
```bash
# Dockerfile
...
RUN curl -fsS https://dotenvx.sh/ | sh
...
RUN dotenvx prebuild
CMD ["dotenvx", "run", "--", "node", "index.js"]
```
</details>
<details><summary>How come my environment variables are not showing up for React?</summary><br/>
Your React code is run in Webpack, where the `fs` module or even the `process` global itself are not accessible out-of-the-box. `process.env` can only be injected through Webpack configuration.
If you are using [`react-scripts`](https://www.npmjs.com/package/react-scripts), which is distributed through [`create-react-app`](https://create-react-app.dev/), it has dotenv built in but with a quirk. Preface your environment variables with `REACT_APP_`. See [this stack overflow](https://stackoverflow.com/questions/42182577/is-it-possible-to-use-dotenv-in-a-react-project) for more details.
If you are using other frameworks (e.g. Next.js, Gatsby...), you need to consult their documentation for how to inject environment variables into the client.
</details>
<details><summary>Why is the `.env` file not loading my environment variables successfully?</summary><br/>
Most likely your `.env` file is not in the correct place. [See this stack overflow](https://stackoverflow.com/questions/42335016/dotenv-file-is-not-loading-environment-variables).
Turn on debug mode and try again..
```js
require('dotenv').config({ debug: true })
```
You will receive a helpful error outputted to your console.
</details>
<details><summary>Why am I getting the error `Module not found: Error: Can't resolve 'crypto|os|path'`?</summary><br/>
You are using dotenv on the front-end and have not included a polyfill. Webpack < 5 used to include these for you. Do the following:
```bash
npm install node-polyfill-webpack-plugin
```
Configure your `webpack.config.js` to something like the following.
```js
require('dotenv').config()
const path = require('path');
const webpack = require('webpack')
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
module.exports = {
mode: 'development',
entry: './src/index.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
plugins: [
new NodePolyfillPlugin(),
new webpack.DefinePlugin({
'process.env': {
HELLO: JSON.stringify(process.env.HELLO)
}
}),
]
};
```
Alternatively, just use [dotenv-webpack](https://github.com/mrsteele/dotenv-webpack) which does this and more behind the scenes for you.
</details>
&nbsp;
## Docs
Dotenv exposes four functions:
* `config`
* `parse`
* `populate`
### Config
`config` will read your `.env` file, parse the contents, assign it to
[`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env),
and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed.
```js
const result = dotenv.config()
if (result.error) {
throw result.error
}
console.log(result.parsed)
```
You can additionally, pass options to `config`.
#### Options
##### path
Default: `path.resolve(process.cwd(), '.env')`
Specify a custom path if your file containing environment variables is located elsewhere.
```js
require('dotenv').config({ path: '/custom/path/to/.env' })
```
By default, `config` will look for a file called .env in the current working directory.
Pass in multiple files as an array, and they will be parsed in order and combined with `process.env` (or `option.processEnv`, if set). The first value set for a variable will win, unless the `options.override` flag is set, in which case the last value set will win. If a value already exists in `process.env` and the `options.override` flag is NOT set, no changes will be made to that value.
```js
require('dotenv').config({ path: ['.env.local', '.env'] })
```
##### quiet
Default: `false`
Suppress runtime logging message.
```js
// index.js
require('dotenv').config({ quiet: false }) // change to true to suppress
console.log(`Hello ${process.env.HELLO}`)
```
```ini
# .env
HELLO=World
```
```sh
$ node index.js
Hello World
```
##### encoding
Default: `utf8`
Specify the encoding of your file containing environment variables.
```js
require('dotenv').config({ encoding: 'latin1' })
```
##### debug
Default: `false`
Turn on logging to help debug why certain keys or values are not being set as you expect.
```js
require('dotenv').config({ debug: process.env.DEBUG })
```
##### override
Default: `false`
Override any environment variables that have already been set on your machine with values from your .env file(s). If multiple files have been provided in `option.path` the override will also be used as each file is combined with the next. Without `override` being set, the first value wins. With `override` set the last value wins.
```js
require('dotenv').config({ override: true })
```
##### processEnv
Default: `process.env`
Specify an object to write your environment variables to. Defaults to `process.env` environment variables.
```js
const myObject = {}
require('dotenv').config({ processEnv: myObject })
console.log(myObject) // values from .env
console.log(process.env) // this was not changed or written to
```
### Parse
The engine which parses the contents of your file containing environment
variables is available to use. It accepts a String or Buffer and will return
an Object with the parsed keys and values.
```js
const dotenv = require('dotenv')
const buf = Buffer.from('BASIC=basic')
const config = dotenv.parse(buf) // will return an object
console.log(typeof config, config) // object { BASIC : 'basic' }
```
#### Options
##### debug
Default: `false`
Turn on logging to help debug why certain keys or values are not being set as you expect.
```js
const dotenv = require('dotenv')
const buf = Buffer.from('hello world')
const opt = { debug: true }
const config = dotenv.parse(buf, opt)
// expect a debug message because the buffer is not in KEY=VAL form
```
### Populate
The engine which populates the contents of your .env file to `process.env` is available for use. It accepts a target, a source, and options. This is useful for power users who want to supply their own objects.
For example, customizing the source:
```js
const dotenv = require('dotenv')
const parsed = { HELLO: 'world' }
dotenv.populate(process.env, parsed)
console.log(process.env.HELLO) // world
```
For example, customizing the source AND target:
```js
const dotenv = require('dotenv')
const parsed = { HELLO: 'universe' }
const target = { HELLO: 'world' } // empty object
dotenv.populate(target, parsed, { override: true, debug: true })
console.log(target) // { HELLO: 'universe' }
```
#### options
##### Debug
Default: `false`
Turn on logging to help debug why certain keys or values are not being populated as you expect.
##### override
Default: `false`
Override any environment variables that have already been set.
&nbsp;
## CHANGELOG
See [CHANGELOG.md](CHANGELOG.md)
&nbsp;
## Who's using dotenv?
[These npm modules depend on it.](https://www.npmjs.com/browse/depended/dotenv)
Projects that expand it often use the [keyword "dotenv" on npm](https://www.npmjs.com/search?q=keywords:dotenv).

View File

@@ -0,0 +1,23 @@
function _class_apply_descriptor_destructure(receiver, descriptor) {
if (descriptor.set) {
if (!("__destrObj" in descriptor)) {
descriptor.__destrObj = {
set value(v) {
descriptor.set.call(receiver, v);
}
};
}
return descriptor.__destrObj;
} else {
if (!descriptor.writable) {
// This should only throw in strict mode, but class bodies are
// always strict and private fields can only be used inside
// class bodies.
throw new TypeError("attempted to set read only private field");
}
return descriptor;
}
}
export { _class_apply_descriptor_destructure as _ };

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,3 @@
# esbuild
This is the Linux 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details.

View File

@@ -0,0 +1,15 @@
'use strict'
const { Writable } = require('node:stream')
const fs = require('node:fs')
module.exports = (options) => {
const myTransportStream = new Writable({
autoDestroy: true,
write (chunk, enc, cb) {
// Bypass console.log() to avoid flakiness
fs.writeSync(1, chunk.toString())
cb()
}
})
return myTransportStream
}

View File

@@ -0,0 +1,137 @@
export type BuiltInMergeStrategy = $typests.BuiltInMergeStrategy;
export type BuiltInValidationStrategy = $typests.BuiltInValidationStrategy;
export type CustomMergeStrategy = $typests.CustomMergeStrategy;
export type CustomValidationStrategy = $typests.CustomValidationStrategy;
export type ObjectDefinition = $typests.ObjectDefinition;
export type PropertyDefinition = $typests.PropertyDefinition;
export type PropertyDefinitionWithSchema = $typests.PropertyDefinitionWithSchema;
export type PropertyDefinitionWithStrategies = $typests.PropertyDefinitionWithStrategies;
/**
* @fileoverview Merge Strategy
*/
/**
* Container class for several different merge strategies.
*/
export class MergeStrategy {
/**
* Merges two keys by overwriting the first with the second.
* @template TValue1 The type of the value from the first object key.
* @template TValue2 The type of the value from the second object key.
* @param {TValue1} value1 The value from the first object key.
* @param {TValue2} value2 The value from the second object key.
* @returns {TValue2} The second value.
*/
static overwrite<TValue1, TValue2>(value1: TValue1, value2: TValue2): TValue2;
/**
* Merges two keys by replacing the first with the second only if the
* second is defined.
* @template TValue1 The type of the value from the first object key.
* @template TValue2 The type of the value from the second object key.
* @param {TValue1} value1 The value from the first object key.
* @param {TValue2} value2 The value from the second object key.
* @returns {TValue1 | TValue2} The second value if it is defined.
*/
static replace<TValue1, TValue2>(value1: TValue1, value2: TValue2): TValue1 | TValue2;
/**
* Merges two properties by assigning properties from the second to the first.
* @template {Record<string | number | symbol, unknown> | undefined} TValue1 The type of the value from the first object key.
* @template {Record<string | number | symbol, unknown>} TValue2 The type of the value from the second object key.
* @param {TValue1} value1 The value from the first object key.
* @param {TValue2} value2 The value from the second object key.
* @returns {Omit<TValue1, keyof TValue2> & TValue2} A new object containing properties from both value1 and
* value2.
*/
static assign<TValue1 extends Record<string | number | symbol, unknown> | undefined, TValue2 extends Record<string | number | symbol, unknown>>(value1: TValue1, value2: TValue2): Omit<TValue1, keyof TValue2> & TValue2;
}
/**
* Represents an object validation/merging schema.
*/
export class ObjectSchema {
/**
* Creates a new instance.
* @param {ObjectDefinition} definitions The schema definitions.
* @throws {Error} When the definitions are missing or invalid.
*/
constructor(definitions: ObjectDefinition);
/**
* Determines if a strategy has been registered for the given object key.
* @param {string} key The object key to find a strategy for.
* @returns {boolean} True if the key has a strategy registered, false if not.
*/
hasKey(key: string): boolean;
/**
* Merges objects together to create a new object comprised of the keys
* of the all objects. Keys are merged based on the each key's merge
* strategy.
* @param {...Object} objects The objects to merge.
* @returns {Object} A new object with a mix of all objects' keys.
* @throws {TypeError} If any object is invalid.
*/
merge(...objects: any[]): any;
/**
* Validates an object's keys based on the validate strategy for each key.
* @param {Object} object The object to validate.
* @returns {void}
* @throws {Error} When the object is invalid.
*/
validate(object: any): void;
#private;
}
/**
* @fileoverview Validation Strategy
*/
/**
* Container class for several different validation strategies.
*/
export class ValidationStrategy {
/**
* Validates that a value is an array.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static array(value: unknown): void;
/**
* Validates that a value is a boolean.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static boolean(value: unknown): void;
/**
* Validates that a value is a number.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static number(value: unknown): void;
/**
* Validates that a value is an object.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static object(value: unknown): void;
/**
* Validates that a value is an object or null.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static "object?"(value: unknown): void;
/**
* Validates that a value is a string.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static string(value: unknown): void;
/**
* Validates that a value is a non-empty string.
* @param {unknown} value The value to validate.
* @returns {void}
* @throws {TypeError} If the value is invalid.
*/
static "string!"(value: unknown): void;
}
import type * as $typests from "./types.cts";

View File

@@ -0,0 +1,506 @@
'use strict';
var compileSchema = require('./compile')
, resolve = require('./compile/resolve')
, Cache = require('./cache')
, SchemaObject = require('./compile/schema_obj')
, stableStringify = require('fast-json-stable-stringify')
, formats = require('./compile/formats')
, rules = require('./compile/rules')
, $dataMetaSchema = require('./data')
, util = require('./compile/util');
module.exports = Ajv;
Ajv.prototype.validate = validate;
Ajv.prototype.compile = compile;
Ajv.prototype.addSchema = addSchema;
Ajv.prototype.addMetaSchema = addMetaSchema;
Ajv.prototype.validateSchema = validateSchema;
Ajv.prototype.getSchema = getSchema;
Ajv.prototype.removeSchema = removeSchema;
Ajv.prototype.addFormat = addFormat;
Ajv.prototype.errorsText = errorsText;
Ajv.prototype._addSchema = _addSchema;
Ajv.prototype._compile = _compile;
Ajv.prototype.compileAsync = require('./compile/async');
var customKeyword = require('./keyword');
Ajv.prototype.addKeyword = customKeyword.add;
Ajv.prototype.getKeyword = customKeyword.get;
Ajv.prototype.removeKeyword = customKeyword.remove;
Ajv.prototype.validateKeyword = customKeyword.validate;
var errorClasses = require('./compile/error_classes');
Ajv.ValidationError = errorClasses.Validation;
Ajv.MissingRefError = errorClasses.MissingRef;
Ajv.$dataMetaSchema = $dataMetaSchema;
var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';
var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ];
var META_SUPPORT_DATA = ['/properties'];
/**
* Creates validator instance.
* Usage: `Ajv(opts)`
* @param {Object} opts optional options
* @return {Object} ajv instance
*/
function Ajv(opts) {
if (!(this instanceof Ajv)) return new Ajv(opts);
opts = this._opts = util.copy(opts) || {};
setLogger(this);
this._schemas = {};
this._refs = {};
this._fragments = {};
this._formats = formats(opts.format);
this._cache = opts.cache || new Cache;
this._loadingSchemas = {};
this._compilations = [];
this.RULES = rules();
this._getId = chooseGetId(opts);
opts.loopRequired = opts.loopRequired || Infinity;
if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
if (opts.serialize === undefined) opts.serialize = stableStringify;
this._metaOpts = getMetaSchemaOptions(this);
if (opts.formats) addInitialFormats(this);
if (opts.keywords) addInitialKeywords(this);
addDefaultMetaSchema(this);
if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});
addInitialSchemas(this);
}
/**
* Validate data using schema
* Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.
* @this Ajv
* @param {String|Object} schemaKeyRef key, ref or schema object
* @param {Any} data to be validated
* @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
*/
function validate(schemaKeyRef, data) {
var v;
if (typeof schemaKeyRef == 'string') {
v = this.getSchema(schemaKeyRef);
if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
} else {
var schemaObj = this._addSchema(schemaKeyRef);
v = schemaObj.validate || this._compile(schemaObj);
}
var valid = v(data);
if (v.$async !== true) this.errors = v.errors;
return valid;
}
/**
* Create validating function for passed schema.
* @this Ajv
* @param {Object} schema schema object
* @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
* @return {Function} validating function
*/
function compile(schema, _meta) {
var schemaObj = this._addSchema(schema, undefined, _meta);
return schemaObj.validate || this._compile(schemaObj);
}
/**
* Adds schema to the instance.
* @this Ajv
* @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
* @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
* @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
* @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
* @return {Ajv} this for method chaining
*/
function addSchema(schema, key, _skipValidation, _meta) {
if (Array.isArray(schema)){
for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);
return this;
}
var id = this._getId(schema);
if (id !== undefined && typeof id != 'string')
throw new Error('schema id must be string');
key = resolve.normalizeId(key || id);
checkUnique(this, key);
this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
return this;
}
/**
* Add schema that will be used to validate other schemas
* options in META_IGNORE_OPTIONS are alway set to false
* @this Ajv
* @param {Object} schema schema object
* @param {String} key optional schema key
* @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
* @return {Ajv} this for method chaining
*/
function addMetaSchema(schema, key, skipValidation) {
this.addSchema(schema, key, skipValidation, true);
return this;
}
/**
* Validate schema
* @this Ajv
* @param {Object} schema schema to validate
* @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
* @return {Boolean} true if schema is valid
*/
function validateSchema(schema, throwOrLogError) {
var $schema = schema.$schema;
if ($schema !== undefined && typeof $schema != 'string')
throw new Error('$schema must be a string');
$schema = $schema || this._opts.defaultMeta || defaultMeta(this);
if (!$schema) {
this.logger.warn('meta-schema not available');
this.errors = null;
return true;
}
var valid = this.validate($schema, schema);
if (!valid && throwOrLogError) {
var message = 'schema is invalid: ' + this.errorsText();
if (this._opts.validateSchema == 'log') this.logger.error(message);
else throw new Error(message);
}
return valid;
}
function defaultMeta(self) {
var meta = self._opts.meta;
self._opts.defaultMeta = typeof meta == 'object'
? self._getId(meta) || meta
: self.getSchema(META_SCHEMA_ID)
? META_SCHEMA_ID
: undefined;
return self._opts.defaultMeta;
}
/**
* Get compiled schema from the instance by `key` or `ref`.
* @this Ajv
* @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
* @return {Function} schema validating function (with property `schema`).
*/
function getSchema(keyRef) {
var schemaObj = _getSchemaObj(this, keyRef);
switch (typeof schemaObj) {
case 'object': return schemaObj.validate || this._compile(schemaObj);
case 'string': return this.getSchema(schemaObj);
case 'undefined': return _getSchemaFragment(this, keyRef);
}
}
function _getSchemaFragment(self, ref) {
var res = resolve.schema.call(self, { schema: {} }, ref);
if (res) {
var schema = res.schema
, root = res.root
, baseId = res.baseId;
var v = compileSchema.call(self, schema, root, undefined, baseId);
self._fragments[ref] = new SchemaObject({
ref: ref,
fragment: true,
schema: schema,
root: root,
baseId: baseId,
validate: v
});
return v;
}
}
function _getSchemaObj(self, keyRef) {
keyRef = resolve.normalizeId(keyRef);
return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
}
/**
* Remove cached schema(s).
* If no parameter is passed all schemas but meta-schemas are removed.
* If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
* Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
* @this Ajv
* @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
* @return {Ajv} this for method chaining
*/
function removeSchema(schemaKeyRef) {
if (schemaKeyRef instanceof RegExp) {
_removeAllSchemas(this, this._schemas, schemaKeyRef);
_removeAllSchemas(this, this._refs, schemaKeyRef);
return this;
}
switch (typeof schemaKeyRef) {
case 'undefined':
_removeAllSchemas(this, this._schemas);
_removeAllSchemas(this, this._refs);
this._cache.clear();
return this;
case 'string':
var schemaObj = _getSchemaObj(this, schemaKeyRef);
if (schemaObj) this._cache.del(schemaObj.cacheKey);
delete this._schemas[schemaKeyRef];
delete this._refs[schemaKeyRef];
return this;
case 'object':
var serialize = this._opts.serialize;
var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
this._cache.del(cacheKey);
var id = this._getId(schemaKeyRef);
if (id) {
id = resolve.normalizeId(id);
delete this._schemas[id];
delete this._refs[id];
}
}
return this;
}
function _removeAllSchemas(self, schemas, regex) {
for (var keyRef in schemas) {
var schemaObj = schemas[keyRef];
if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
self._cache.del(schemaObj.cacheKey);
delete schemas[keyRef];
}
}
}
/* @this Ajv */
function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
if (typeof schema != 'object' && typeof schema != 'boolean')
throw new Error('schema should be object or boolean');
var serialize = this._opts.serialize;
var cacheKey = serialize ? serialize(schema) : schema;
var cached = this._cache.get(cacheKey);
if (cached) return cached;
shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;
var id = resolve.normalizeId(this._getId(schema));
if (id && shouldAddSchema) checkUnique(this, id);
var willValidate = this._opts.validateSchema !== false && !skipValidation;
var recursiveMeta;
if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))
this.validateSchema(schema, true);
var localRefs = resolve.ids.call(this, schema);
var schemaObj = new SchemaObject({
id: id,
schema: schema,
localRefs: localRefs,
cacheKey: cacheKey,
meta: meta
});
if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj;
this._cache.put(cacheKey, schemaObj);
if (willValidate && recursiveMeta) this.validateSchema(schema, true);
return schemaObj;
}
/* @this Ajv */
function _compile(schemaObj, root) {
if (schemaObj.compiling) {
schemaObj.validate = callValidate;
callValidate.schema = schemaObj.schema;
callValidate.errors = null;
callValidate.root = root ? root : callValidate;
if (schemaObj.schema.$async === true)
callValidate.$async = true;
return callValidate;
}
schemaObj.compiling = true;
var currentOpts;
if (schemaObj.meta) {
currentOpts = this._opts;
this._opts = this._metaOpts;
}
var v;
try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); }
catch(e) {
delete schemaObj.validate;
throw e;
}
finally {
schemaObj.compiling = false;
if (schemaObj.meta) this._opts = currentOpts;
}
schemaObj.validate = v;
schemaObj.refs = v.refs;
schemaObj.refVal = v.refVal;
schemaObj.root = v.root;
return v;
/* @this {*} - custom context, see passContext option */
function callValidate() {
/* jshint validthis: true */
var _validate = schemaObj.validate;
var result = _validate.apply(this, arguments);
callValidate.errors = _validate.errors;
return result;
}
}
function chooseGetId(opts) {
switch (opts.schemaId) {
case 'auto': return _get$IdOrId;
case 'id': return _getId;
default: return _get$Id;
}
}
/* @this Ajv */
function _getId(schema) {
if (schema.$id) this.logger.warn('schema $id ignored', schema.$id);
return schema.id;
}
/* @this Ajv */
function _get$Id(schema) {
if (schema.id) this.logger.warn('schema id ignored', schema.id);
return schema.$id;
}
function _get$IdOrId(schema) {
if (schema.$id && schema.id && schema.$id != schema.id)
throw new Error('schema $id is different from id');
return schema.$id || schema.id;
}
/**
* Convert array of error message objects to string
* @this Ajv
* @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
* @param {Object} options optional options with properties `separator` and `dataVar`.
* @return {String} human readable string with all errors descriptions
*/
function errorsText(errors, options) {
errors = errors || this.errors;
if (!errors) return 'No errors';
options = options || {};
var separator = options.separator === undefined ? ', ' : options.separator;
var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
var text = '';
for (var i=0; i<errors.length; i++) {
var e = errors[i];
if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
}
return text.slice(0, -separator.length);
}
/**
* Add custom format
* @this Ajv
* @param {String} name format name
* @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
* @return {Ajv} this for method chaining
*/
function addFormat(name, format) {
if (typeof format == 'string') format = new RegExp(format);
this._formats[name] = format;
return this;
}
function addDefaultMetaSchema(self) {
var $dataSchema;
if (self._opts.$data) {
$dataSchema = require('./refs/data.json');
self.addMetaSchema($dataSchema, $dataSchema.$id, true);
}
if (self._opts.meta === false) return;
var metaSchema = require('./refs/json-schema-draft-07.json');
if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
}
function addInitialSchemas(self) {
var optsSchemas = self._opts.schemas;
if (!optsSchemas) return;
if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);
else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key);
}
function addInitialFormats(self) {
for (var name in self._opts.formats) {
var format = self._opts.formats[name];
self.addFormat(name, format);
}
}
function addInitialKeywords(self) {
for (var name in self._opts.keywords) {
var keyword = self._opts.keywords[name];
self.addKeyword(name, keyword);
}
}
function checkUnique(self, id) {
if (self._schemas[id] || self._refs[id])
throw new Error('schema with key or id "' + id + '" already exists');
}
function getMetaSchemaOptions(self) {
var metaOpts = util.copy(self._opts);
for (var i=0; i<META_IGNORE_OPTIONS.length; i++)
delete metaOpts[META_IGNORE_OPTIONS[i]];
return metaOpts;
}
function setLogger(self) {
var logger = self._opts.logger;
if (logger === false) {
self.logger = {log: noop, warn: noop, error: noop};
} else {
if (logger === undefined) logger = console;
if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error))
throw new Error('logger must implement log, warn and error methods');
self.logger = logger;
}
}
function noop() {}