WIP: bootstrap and partial real Solana watcher implementation
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
import type { LibDefinition } from '../variable';
|
||||
export declare const es2025_collection: LibDefinition;
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/structs/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAE5C,OAAO,EACL,YAAY,EACZ,UAAU,EAKV,SAAS,EACT,gBAAgB,EAChB,mBAAmB,EACpB,MAAM,aAAa,CAAA;AAEpB;;GAEG;AAEH,wBAAgB,GAAG,IAAI,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,CAEvC;AAED;;;;;;GAMG;AAEH,wBAAgB,KAAK,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAA;AAC/E,wBAAgB,KAAK,IAAI,MAAM,CAAC,OAAO,EAAE,EAAE,SAAS,CAAC,CAAA;AAwBrD;;GAEG;AAEH,wBAAgB,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAI7C;AAED;;GAEG;AAEH,wBAAgB,OAAO,IAAI,MAAM,CAAC,OAAO,EAAE,IAAI,CAAC,CAI/C;AAED;;;;;GAKG;AAEH,wBAAgB,IAAI,IAAI,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,CAOzC;AAED;;;;;GAKG;AAEH,wBAAgB,KAAK,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,SAAS,CAAC,EAAE,EAC5D,MAAM,EAAE,CAAC,GACR,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE;KAAG,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;CAAE,CAAC,CAAA;AAC7C,wBAAgB,KAAK,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,SAAS,CAAC,EAAE,EAC5D,MAAM,EAAE,CAAC,GACR,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE;KAAG,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;CAAE,CAAC,CAAA;AAuB7C;;GAEG;AAEH,wBAAgB,IAAI,IAAI,MAAM,CAAC,QAAQ,EAAE,IAAI,CAAC,CAO7C;AAED;;GAEG;AAEH,wBAAgB,QAAQ,CAAC,CAAC,SAAS;IAAE,KAAK,GAAG,IAAI,EAAE,GAAG,GAAG,GAAG,CAAA;CAAE,EAC5D,KAAK,EAAE,CAAC,GACP,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAO/B;AAED;;GAEG;AAEH,wBAAgB,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAO9C;AAED;;GAEG;AAEH,wBAAgB,YAAY,CAAC,CAAC,SAAS,SAAS,EAAE,CAAC,SAAS,SAAS,EAAE,EACrE,OAAO,EAAE,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,GACjB,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,mBAAmB,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,IAAI,CAAC,CAoB3E;AAED;;GAEG;AAEH,wBAAgB,OAAO,CAAC,CAAC,SAAS,OAAO,EAAE,QAAQ,EAAE,CAAC,GAAG,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;AACrE,wBAAgB,OAAO,CAAC,CAAC,SAAS,MAAM,EAAE,QAAQ,EAAE,CAAC,GAAG,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;AACpE,wBAAgB,OAAO,CAAC,CAAC,SAAS,MAAM,EAAE,QAAQ,EAAE,CAAC,GAAG,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;AACpE,wBAAgB,OAAO,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,GAAG,MAAM,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;AAiBxD;;;GAGG;AAEH,wBAAgB,GAAG,IAAI,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,CAAA;AAC1D,wBAAgB,GAAG,CAAC,CAAC,EAAE,CAAC,EACtB,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC,EACd,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,GACf,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;AAyB1B;;GAEG;AAEH,wBAAgB,KAAK,IAAI,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,CAE3C;AAED;;GAEG;AAEH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC,CAMxE;AAED;;GAEG;AAEH,wBAAgB,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAO7C;AAED;;;;;GAKG;AAEH,wBAAgB,MAAM,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,CAAA;AAC/D,wBAAgB,MAAM,CAAC,CAAC,SAAS,YAAY,EAC3C,MAAM,EAAE,CAAC,GACR,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;AAkD3B;;GAEG;AAEH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,GAAG,SAAS,EAAE,CAAC,CAAC,CAO7E;AAED;;;;;GAKG;AAEH,wBAAgB,MAAM,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,EACxC,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC,EACd,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,GACf,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,CAAC,CAuB5B;AAED;;;;;GAKG;AAEH,wBAAgB,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAI7C;AAED;;;GAGG;AAEH,wBAAgB,GAAG,IAAI,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,CAAA;AACjD,wBAAgB,GAAG,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;AAwBhE;;GAEG;AAEH,wBAAgB,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAO7C;AAED;;;GAGG;AAEH,wBAAgB,KAAK,CAAC,CAAC,SAAS,SAAS,EAAE,CAAC,SAAS,SAAS,EAAE,EAC9D,OAAO,EAAE,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,GACjB,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,gBAAgB,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAyBlD;AAED;;;;;GAKG;AAEH,wBAAgB,IAAI,CAAC,CAAC,SAAS,YAAY,EACzC,MAAM,EAAE,CAAC,GACR,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAsB1B;AAED;;GAEG;AAEH,wBAAgB,KAAK,CAAC,CAAC,SAAS,SAAS,EAAE,CAAC,SAAS,SAAS,EAAE,EAC9D,OAAO,EAAE,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,GACjB,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,gBAAgB,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,CA4CtD;AAED;;GAEG;AAEH,wBAAgB,OAAO,IAAI,MAAM,CAAC,OAAO,EAAE,IAAI,CAAC,CAE/C"}
|
||||
@@ -0,0 +1,58 @@
|
||||
//TODO: handle reviver/dehydrate function like normal
|
||||
//and handle indentation, like normal.
|
||||
//if anyone needs this... please send pull request.
|
||||
|
||||
exports.stringify = function stringify (o) {
|
||||
if('undefined' == typeof o) return o
|
||||
|
||||
if(o && Buffer.isBuffer(o))
|
||||
return JSON.stringify(':base64:' + o.toString('base64'))
|
||||
|
||||
if(o && o.toJSON)
|
||||
o = o.toJSON()
|
||||
|
||||
if(o && 'object' === typeof o) {
|
||||
var s = ''
|
||||
var array = Array.isArray(o)
|
||||
s = array ? '[' : '{'
|
||||
var first = true
|
||||
|
||||
for(var k in o) {
|
||||
var ignore = 'function' == typeof o[k] || (!array && 'undefined' === typeof o[k])
|
||||
if(Object.hasOwnProperty.call(o, k) && !ignore) {
|
||||
if(!first)
|
||||
s += ','
|
||||
first = false
|
||||
if (array) {
|
||||
if(o[k] == undefined)
|
||||
s += 'null'
|
||||
else
|
||||
s += stringify(o[k])
|
||||
} else if (o[k] !== void(0)) {
|
||||
s += stringify(k) + ':' + stringify(o[k])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
s += array ? ']' : '}'
|
||||
|
||||
return s
|
||||
} else if ('string' === typeof o) {
|
||||
return JSON.stringify(/^:/.test(o) ? ':' + o : o)
|
||||
} else if ('undefined' === typeof o) {
|
||||
return 'null';
|
||||
} else
|
||||
return JSON.stringify(o)
|
||||
}
|
||||
|
||||
exports.parse = function (s) {
|
||||
return JSON.parse(s, function (key, value) {
|
||||
if('string' === typeof value) {
|
||||
if(/^:base64:/.test(value))
|
||||
return Buffer.from(value.substring(8), 'base64')
|
||||
else
|
||||
return /^:/.test(value) ? value.substring(1) : value
|
||||
}
|
||||
return value
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
"use strict";
|
||||
// THIS CODE WAS AUTOMATICALLY GENERATED
|
||||
// DO NOT EDIT THIS CODE BY HAND
|
||||
// SEE https://typescript-eslint.io/users/configs
|
||||
//
|
||||
// For developers working in the typescript-eslint monorepo:
|
||||
// You can regenerate it using `pnpm run generate-configs`
|
||||
module.exports = {
|
||||
extends: ['./configs/eslintrc/base', './configs/eslintrc/eslint-recommended'],
|
||||
rules: {
|
||||
'@typescript-eslint/await-thenable': 'error',
|
||||
'@typescript-eslint/no-array-delete': 'error',
|
||||
'@typescript-eslint/no-base-to-string': 'error',
|
||||
'@typescript-eslint/no-confusing-void-expression': 'error',
|
||||
'@typescript-eslint/no-deprecated': 'error',
|
||||
'@typescript-eslint/no-duplicate-type-constituents': 'error',
|
||||
'@typescript-eslint/no-floating-promises': 'error',
|
||||
'@typescript-eslint/no-for-in-array': 'error',
|
||||
'no-implied-eval': 'off',
|
||||
'@typescript-eslint/no-implied-eval': 'error',
|
||||
'@typescript-eslint/no-meaningless-void-operator': 'error',
|
||||
'@typescript-eslint/no-misused-promises': 'error',
|
||||
'@typescript-eslint/no-misused-spread': 'error',
|
||||
'@typescript-eslint/no-mixed-enums': 'error',
|
||||
'@typescript-eslint/no-redundant-type-constituents': 'error',
|
||||
'@typescript-eslint/no-unnecessary-boolean-literal-compare': 'error',
|
||||
'@typescript-eslint/no-unnecessary-condition': 'error',
|
||||
'@typescript-eslint/no-unnecessary-template-expression': 'error',
|
||||
'@typescript-eslint/no-unnecessary-type-arguments': 'error',
|
||||
'@typescript-eslint/no-unnecessary-type-assertion': 'error',
|
||||
'@typescript-eslint/no-unnecessary-type-conversion': 'error',
|
||||
'@typescript-eslint/no-unnecessary-type-parameters': 'error',
|
||||
'@typescript-eslint/no-unsafe-argument': 'error',
|
||||
'@typescript-eslint/no-unsafe-assignment': 'error',
|
||||
'@typescript-eslint/no-unsafe-call': 'error',
|
||||
'@typescript-eslint/no-unsafe-enum-comparison': 'error',
|
||||
'@typescript-eslint/no-unsafe-member-access': 'error',
|
||||
'@typescript-eslint/no-unsafe-return': 'error',
|
||||
'@typescript-eslint/no-unsafe-unary-minus': 'error',
|
||||
'@typescript-eslint/no-useless-default-assignment': 'error',
|
||||
'no-throw-literal': 'off',
|
||||
'@typescript-eslint/only-throw-error': 'error',
|
||||
'prefer-promise-reject-errors': 'off',
|
||||
'@typescript-eslint/prefer-promise-reject-errors': 'error',
|
||||
'@typescript-eslint/prefer-reduce-type-parameter': 'error',
|
||||
'@typescript-eslint/prefer-return-this-type': 'error',
|
||||
'@typescript-eslint/related-getter-setter-pairs': 'error',
|
||||
'require-await': 'off',
|
||||
'@typescript-eslint/require-await': 'error',
|
||||
'@typescript-eslint/restrict-plus-operands': [
|
||||
'error',
|
||||
{
|
||||
allowAny: false,
|
||||
allowBoolean: false,
|
||||
allowNullish: false,
|
||||
allowNumberAndString: false,
|
||||
allowRegExp: false,
|
||||
},
|
||||
],
|
||||
'@typescript-eslint/restrict-template-expressions': [
|
||||
'error',
|
||||
{
|
||||
allowAny: false,
|
||||
allowBoolean: false,
|
||||
allowNever: false,
|
||||
allowNullish: false,
|
||||
allowNumber: false,
|
||||
allowRegExp: false,
|
||||
},
|
||||
],
|
||||
'no-return-await': 'off',
|
||||
'@typescript-eslint/return-await': [
|
||||
'error',
|
||||
'error-handling-correctness-only',
|
||||
],
|
||||
'@typescript-eslint/unbound-method': 'error',
|
||||
'@typescript-eslint/use-unknown-in-catch-callback-variable': 'error',
|
||||
},
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"main": "../../cjs/_class_private_field_destructure.cjs",
|
||||
"module": "../../esm/_class_private_field_destructure.js"
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.BSIGMA = void 0;
|
||||
exports.G1s = G1s;
|
||||
exports.G2s = G2s;
|
||||
/**
|
||||
* Internal helpers for blake hash.
|
||||
* @module
|
||||
*/
|
||||
const utils_ts_1 = require("./utils.js");
|
||||
/**
|
||||
* Internal blake variable.
|
||||
* For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1].
|
||||
*/
|
||||
// prettier-ignore
|
||||
exports.BSIGMA = Uint8Array.from([
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
||||
14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
|
||||
11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
|
||||
7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
|
||||
9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
|
||||
2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
|
||||
12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,
|
||||
13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,
|
||||
6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,
|
||||
10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
||||
14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
|
||||
// Blake1, unused in others
|
||||
11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
|
||||
7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
|
||||
9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
|
||||
2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
|
||||
]);
|
||||
// Mixing function G splitted in two halfs
|
||||
function G1s(a, b, c, d, x) {
|
||||
a = (a + b + x) | 0;
|
||||
d = (0, utils_ts_1.rotr)(d ^ a, 16);
|
||||
c = (c + d) | 0;
|
||||
b = (0, utils_ts_1.rotr)(b ^ c, 12);
|
||||
return { a, b, c, d };
|
||||
}
|
||||
function G2s(a, b, c, d, x) {
|
||||
a = (a + b + x) | 0;
|
||||
d = (0, utils_ts_1.rotr)(d ^ a, 8);
|
||||
c = (c + d) | 0;
|
||||
b = (0, utils_ts_1.rotr)(b ^ c, 7);
|
||||
return { a, b, c, d };
|
||||
}
|
||||
//# sourceMappingURL=_blake.js.map
|
||||
@@ -0,0 +1,15 @@
|
||||
# Installation
|
||||
> `npm install --save @types/connect`
|
||||
|
||||
# Summary
|
||||
This package contains type definitions for connect (https://github.com/senchalabs/connect).
|
||||
|
||||
# Details
|
||||
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/connect.
|
||||
|
||||
### Additional Details
|
||||
* Last updated: Mon, 06 Nov 2023 22:41:05 GMT
|
||||
* Dependencies: [@types/node](https://npmjs.com/package/@types/node)
|
||||
|
||||
# Credits
|
||||
These definitions were written by [Maxime LUCE](https://github.com/SomaticIT), and [Evan Hahn](https://github.com/EvanHahn).
|
||||
@@ -0,0 +1 @@
|
||||
hello world
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
|
||||
// do not edit .js files directly - edit src/index.jst
|
||||
|
||||
|
||||
|
||||
module.exports = function equal(a, b) {
|
||||
if (a === b) return true;
|
||||
|
||||
if (a && b && typeof a == 'object' && typeof b == 'object') {
|
||||
if (a.constructor !== b.constructor) return false;
|
||||
|
||||
var length, i, keys;
|
||||
if (Array.isArray(a)) {
|
||||
length = a.length;
|
||||
if (length != b.length) return false;
|
||||
for (i = length; i-- !== 0;)
|
||||
if (!equal(a[i], b[i])) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
|
||||
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
|
||||
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
|
||||
|
||||
keys = Object.keys(a);
|
||||
length = keys.length;
|
||||
if (length !== Object.keys(b).length) return false;
|
||||
|
||||
for (i = length; i-- !== 0;)
|
||||
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
|
||||
|
||||
for (i = length; i-- !== 0;) {
|
||||
var key = keys[i];
|
||||
|
||||
if (!equal(a[key], b[key])) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// true if both NaN, false otherwise
|
||||
return a!==a && b!==b;
|
||||
};
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* @fileoverview Shared flags for ESLint.
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Typedefs
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* @typedef {Object} InactiveFlagData
|
||||
* @property {string} description Flag description
|
||||
* @property {string | null} [replacedBy] Can be either:
|
||||
* - An active flag (string) that enables the same feature.
|
||||
* - `null` if the feature is now enabled by default.
|
||||
* - Omitted if the feature has been abandoned.
|
||||
*/
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Exports
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The set of flags that change ESLint behavior with a description.
|
||||
* @type {Map<string, string>}
|
||||
*/
|
||||
const activeFlags = new Map([
|
||||
["test_only", "Used only for testing."],
|
||||
["test_only_2", "Used only for testing."],
|
||||
[
|
||||
"unstable_native_nodejs_ts_config",
|
||||
"Use native Node.js to load TypeScript configuration.",
|
||||
],
|
||||
]);
|
||||
|
||||
/**
|
||||
* The set of flags that used to be active.
|
||||
* @type {Map<string, InactiveFlagData>}
|
||||
*/
|
||||
const inactiveFlags = new Map([
|
||||
[
|
||||
"test_only_replaced",
|
||||
{
|
||||
description:
|
||||
"Used only for testing flags that have been replaced by other flags.",
|
||||
replacedBy: "test_only",
|
||||
},
|
||||
],
|
||||
[
|
||||
"test_only_enabled_by_default",
|
||||
{
|
||||
description:
|
||||
"Used only for testing flags whose features have been enabled by default.",
|
||||
replacedBy: null,
|
||||
},
|
||||
],
|
||||
[
|
||||
"test_only_abandoned",
|
||||
{
|
||||
description:
|
||||
"Used only for testing flags whose features have been abandoned.",
|
||||
},
|
||||
],
|
||||
]);
|
||||
|
||||
/**
|
||||
* Creates a message that describes the reason the flag is inactive.
|
||||
* @param {InactiveFlagData} inactiveFlagData Data for the inactive flag.
|
||||
* @returns {string} Message describing the reason the flag is inactive.
|
||||
*/
|
||||
function getInactivityReasonMessage({ replacedBy }) {
|
||||
if (typeof replacedBy === "undefined") {
|
||||
return "This feature has been abandoned.";
|
||||
}
|
||||
|
||||
if (typeof replacedBy === "string") {
|
||||
return `This flag has been renamed '${replacedBy}' to reflect its stabilization. Please use '${replacedBy}' instead.`;
|
||||
}
|
||||
|
||||
// null
|
||||
return "This feature is now enabled by default.";
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
activeFlags,
|
||||
inactiveFlags,
|
||||
getInactivityReasonMessage,
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,41 @@
|
||||
'use strict'
|
||||
|
||||
const test = require('node:test')
|
||||
const assert = require('node:assert')
|
||||
const { join } = require('node:path')
|
||||
const { fork } = require('node:child_process')
|
||||
const writer = require('flush-write-stream')
|
||||
|
||||
const { once } = require('./helper')
|
||||
const pino = require('..')
|
||||
|
||||
test('do not use SonicBoom is someone tampered with process.stdout.write', async () => {
|
||||
let actual = ''
|
||||
const child = fork(join(__dirname, 'fixtures', 'stdout-hack-protection.js'), { silent: true })
|
||||
|
||||
child.stdout.pipe(writer((s, enc, cb) => {
|
||||
actual += s
|
||||
cb()
|
||||
}))
|
||||
await once(child, 'close')
|
||||
assert.equal(actual.match(/^hack/) != null, true)
|
||||
})
|
||||
|
||||
test('do not use SonicBoom is someone has passed process.stdout to pino', async () => {
|
||||
const logger = pino(process.stdout)
|
||||
assert.equal(logger[pino.symbols.streamSym], process.stdout)
|
||||
})
|
||||
|
||||
test('do not crash if process.stdout has no fd', async (t) => {
|
||||
const fd = process.stdout.fd
|
||||
delete process.stdout.fd
|
||||
t.after(function () { process.stdout.fd = fd })
|
||||
pino()
|
||||
})
|
||||
|
||||
test('use fd=1 if process.stdout has no fd in pino.destination() (worker case)', async (t) => {
|
||||
const fd = process.stdout.fd
|
||||
delete process.stdout.fd
|
||||
t.after(function () { process.stdout.fd = fd })
|
||||
pino.destination()
|
||||
})
|
||||
@@ -0,0 +1,2 @@
|
||||
import type { LibDefinition } from '../variable';
|
||||
export declare const es2015_proxy: LibDefinition;
|
||||
@@ -0,0 +1,363 @@
|
||||
/**
|
||||
* @fileoverview A rule to disallow using `this`/`super` before `super()`.
|
||||
* @author Toru Nagashima
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Checks whether or not a given node is a constructor.
|
||||
* @param {ASTNode} node A node to check. This node type is one of
|
||||
* `Program`, `FunctionDeclaration`, `FunctionExpression`, and
|
||||
* `ArrowFunctionExpression`.
|
||||
* @returns {boolean} `true` if the node is a constructor.
|
||||
*/
|
||||
function isConstructorFunction(node) {
|
||||
return (
|
||||
node.type === "FunctionExpression" &&
|
||||
node.parent.type === "MethodDefinition" &&
|
||||
node.parent.kind === "constructor"
|
||||
);
|
||||
}
|
||||
|
||||
/*
|
||||
* Information for each code path segment.
|
||||
* - superCalled: The flag which shows `super()` called in all code paths.
|
||||
* - invalidNodes: The array of invalid ThisExpression and Super nodes.
|
||||
*/
|
||||
/**
|
||||
*
|
||||
*/
|
||||
class SegmentInfo {
|
||||
/**
|
||||
* Indicates whether `super()` is called in all code paths.
|
||||
* @type {boolean}
|
||||
*/
|
||||
superCalled = false;
|
||||
|
||||
/**
|
||||
* The array of invalid ThisExpression and Super nodes.
|
||||
* @type {ASTNode[]}
|
||||
*/
|
||||
invalidNodes = [];
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "problem",
|
||||
|
||||
docs: {
|
||||
description:
|
||||
"Disallow `this`/`super` before calling `super()` in constructors",
|
||||
recommended: true,
|
||||
url: "https://eslint.org/docs/latest/rules/no-this-before-super",
|
||||
},
|
||||
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
noBeforeSuper: "'{{kind}}' is not allowed before 'super()'.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
/*
|
||||
* Information for each constructor.
|
||||
* - upper: Information of the upper constructor.
|
||||
* - hasExtends: A flag which shows whether the owner class has a valid
|
||||
* `extends` part.
|
||||
* - scope: The scope of the owner class.
|
||||
* - codePath: The code path of this constructor.
|
||||
*/
|
||||
let funcInfo = null;
|
||||
|
||||
/** @type {Record<string, SegmentInfo>} */
|
||||
let segInfoMap = Object.create(null);
|
||||
|
||||
/**
|
||||
* Gets whether or not `super()` is called in a given code path segment.
|
||||
* @param {CodePathSegment} segment A code path segment to get.
|
||||
* @returns {boolean} `true` if `super()` is called.
|
||||
*/
|
||||
function isCalled(segment) {
|
||||
return !segment.reachable || segInfoMap[segment.id]?.superCalled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether or not this is in a constructor.
|
||||
* @returns {boolean} `true` if this is in a constructor.
|
||||
*/
|
||||
function isInConstructorOfDerivedClass() {
|
||||
return Boolean(
|
||||
funcInfo && funcInfo.isConstructor && funcInfo.hasExtends,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if every segment in a set has been called.
|
||||
* @param {Set<CodePathSegment>} segments The segments to search.
|
||||
* @returns {boolean} True if every segment has been called; false otherwise.
|
||||
*/
|
||||
function isEverySegmentCalled(segments) {
|
||||
for (const segment of segments) {
|
||||
if (!isCalled(segment)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether or not this is before `super()` is called.
|
||||
* @returns {boolean} `true` if this is before `super()` is called.
|
||||
*/
|
||||
function isBeforeCallOfSuper() {
|
||||
return (
|
||||
isInConstructorOfDerivedClass() &&
|
||||
!isEverySegmentCalled(funcInfo.currentSegments)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a given node as invalid.
|
||||
* @param {ASTNode} node A node to set as invalid. This is one of
|
||||
* a ThisExpression and a Super.
|
||||
* @returns {void}
|
||||
*/
|
||||
function setInvalid(node) {
|
||||
const segments = funcInfo.currentSegments;
|
||||
|
||||
for (const segment of segments) {
|
||||
if (segment.reachable) {
|
||||
segInfoMap[segment.id].invalidNodes.push(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the current segment as `super` was called.
|
||||
* @returns {void}
|
||||
*/
|
||||
function setSuperCalled() {
|
||||
const segments = funcInfo.currentSegments;
|
||||
|
||||
for (const segment of segments) {
|
||||
if (segment.reachable) {
|
||||
segInfoMap[segment.id].superCalled = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
/**
|
||||
* Adds information of a constructor into the stack.
|
||||
* @param {CodePath} codePath A code path which was started.
|
||||
* @param {ASTNode} node The current node.
|
||||
* @returns {void}
|
||||
*/
|
||||
onCodePathStart(codePath, node) {
|
||||
if (isConstructorFunction(node)) {
|
||||
// Class > ClassBody > MethodDefinition > FunctionExpression
|
||||
const classNode = node.parent.parent.parent;
|
||||
|
||||
funcInfo = {
|
||||
upper: funcInfo,
|
||||
isConstructor: true,
|
||||
hasExtends: Boolean(
|
||||
classNode.superClass &&
|
||||
!astUtils.isNullOrUndefined(classNode.superClass),
|
||||
),
|
||||
codePath,
|
||||
currentSegments: new Set(),
|
||||
};
|
||||
} else {
|
||||
funcInfo = {
|
||||
upper: funcInfo,
|
||||
isConstructor: false,
|
||||
hasExtends: false,
|
||||
codePath,
|
||||
currentSegments: new Set(),
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Removes the top of stack item.
|
||||
*
|
||||
* And this traverses all segments of this code path then reports every
|
||||
* invalid node.
|
||||
* @param {CodePath} codePath A code path which was ended.
|
||||
* @returns {void}
|
||||
*/
|
||||
onCodePathEnd(codePath) {
|
||||
const isDerivedClass = funcInfo.hasExtends;
|
||||
|
||||
funcInfo = funcInfo.upper;
|
||||
if (!isDerivedClass) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* A collection of nodes to avoid duplicate reports.
|
||||
* @type {Set<ASTNode>}
|
||||
*/
|
||||
const reported = new Set();
|
||||
|
||||
codePath.traverseSegments((segment, controller) => {
|
||||
const info = segInfoMap[segment.id];
|
||||
const invalidNodes = info.invalidNodes.filter(
|
||||
/*
|
||||
* Avoid duplicate reports.
|
||||
* When there is a `finally`, invalidNodes may contain already reported node.
|
||||
*/
|
||||
node => !reported.has(node),
|
||||
);
|
||||
|
||||
for (const invalidNode of invalidNodes) {
|
||||
reported.add(invalidNode);
|
||||
|
||||
context.report({
|
||||
messageId: "noBeforeSuper",
|
||||
node: invalidNode,
|
||||
data: {
|
||||
kind:
|
||||
invalidNode.type === "Super"
|
||||
? "super"
|
||||
: "this",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (info.superCalled) {
|
||||
controller.skip();
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Initialize information of a given code path segment.
|
||||
* @param {CodePathSegment} segment A code path segment to initialize.
|
||||
* @returns {void}
|
||||
*/
|
||||
onCodePathSegmentStart(segment) {
|
||||
funcInfo.currentSegments.add(segment);
|
||||
|
||||
if (!isInConstructorOfDerivedClass()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Initialize info.
|
||||
segInfoMap[segment.id] = {
|
||||
superCalled:
|
||||
segment.prevSegments.length > 0 &&
|
||||
segment.prevSegments.every(isCalled),
|
||||
invalidNodes: [],
|
||||
};
|
||||
},
|
||||
|
||||
onUnreachableCodePathSegmentStart(segment) {
|
||||
funcInfo.currentSegments.add(segment);
|
||||
},
|
||||
|
||||
onUnreachableCodePathSegmentEnd(segment) {
|
||||
funcInfo.currentSegments.delete(segment);
|
||||
},
|
||||
|
||||
onCodePathSegmentEnd(segment) {
|
||||
funcInfo.currentSegments.delete(segment);
|
||||
},
|
||||
|
||||
/**
|
||||
* Update information of the code path segment when a code path was
|
||||
* looped.
|
||||
* @param {CodePathSegment} fromSegment The code path segment of the
|
||||
* end of a loop.
|
||||
* @param {CodePathSegment} toSegment A code path segment of the head
|
||||
* of a loop.
|
||||
* @returns {void}
|
||||
*/
|
||||
onCodePathSegmentLoop(fromSegment, toSegment) {
|
||||
if (!isInConstructorOfDerivedClass()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Update information inside of the loop.
|
||||
funcInfo.codePath.traverseSegments(
|
||||
{ first: toSegment, last: fromSegment },
|
||||
(segment, controller) => {
|
||||
const info =
|
||||
segInfoMap[segment.id] ?? new SegmentInfo();
|
||||
|
||||
if (info.superCalled) {
|
||||
controller.skip();
|
||||
} else if (
|
||||
segment.prevSegments.length > 0 &&
|
||||
segment.prevSegments.every(isCalled)
|
||||
) {
|
||||
info.superCalled = true;
|
||||
}
|
||||
|
||||
segInfoMap[segment.id] = info;
|
||||
},
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* Reports if this is before `super()`.
|
||||
* @param {ASTNode} node A target node.
|
||||
* @returns {void}
|
||||
*/
|
||||
ThisExpression(node) {
|
||||
if (isBeforeCallOfSuper()) {
|
||||
setInvalid(node);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Reports if this is before `super()`.
|
||||
* @param {ASTNode} node A target node.
|
||||
* @returns {void}
|
||||
*/
|
||||
Super(node) {
|
||||
if (!astUtils.isCallee(node) && isBeforeCallOfSuper()) {
|
||||
setInvalid(node);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Marks `super()` called.
|
||||
* @param {ASTNode} node A target node.
|
||||
* @returns {void}
|
||||
*/
|
||||
"CallExpression:exit"(node) {
|
||||
if (node.callee.type === "Super" && isBeforeCallOfSuper()) {
|
||||
setSuperCalled();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Resets state.
|
||||
* @returns {void}
|
||||
*/
|
||||
"Program:exit"() {
|
||||
segInfoMap = Object.create(null);
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,459 @@
|
||||
/**
|
||||
* Edwards448 (not Ed448-Goldilocks) curve with following addons:
|
||||
* - X448 ECDH
|
||||
* - Decaf cofactor elimination
|
||||
* - Elligator hash-to-group / point indistinguishability
|
||||
* Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
import { shake256 } from '@noble/hashes/sha3.js';
|
||||
import { abytes, concatBytes, createHasher as wrapConstructor } from '@noble/hashes/utils.js';
|
||||
import { pippenger } from "./abstract/curve.js";
|
||||
import { edwards, PrimeEdwardsPoint, twistedEdwards, } from "./abstract/edwards.js";
|
||||
import { _DST_scalar, createHasher, expand_message_xof, } from "./abstract/hash-to-curve.js";
|
||||
import { Field, FpInvertBatch, isNegativeLE, mod, pow2 } from "./abstract/modular.js";
|
||||
import { montgomery } from "./abstract/montgomery.js";
|
||||
import { asciiToBytes, bytesToNumberLE, ensureBytes, equalBytes } from "./utils.js";
|
||||
// edwards448 curve
|
||||
// a = 1n
|
||||
// d = Fp.neg(39081n)
|
||||
// Finite field 2n**448n - 2n**224n - 1n
|
||||
// Subgroup order
|
||||
// 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n
|
||||
const ed448_CURVE = {
|
||||
p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffff'),
|
||||
n: BigInt('0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffff7cca23e9c44edb49aed63690216cc2728dc58f552378c292ab5844f3'),
|
||||
h: BigInt(4),
|
||||
a: BigInt(1),
|
||||
d: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffff6756'),
|
||||
Gx: BigInt('0x4f1970c66bed0ded221d15a622bf36da9e146570470f1767ea6de324a3d3a46412ae1af72ab66511433b80e18b00938e2626a82bc70cc05e'),
|
||||
Gy: BigInt('0x693f46716eb6bc248876203756c9c7624bea73736ca3984087789c1e05a0c2d73ad3ff1ce67c39c4fdbd132c4ed7c8ad9808795bf230fa14'),
|
||||
};
|
||||
// E448 NIST curve is identical to edwards448, except for:
|
||||
// d = 39082/39081
|
||||
// Gx = 3/2
|
||||
const E448_CURVE = Object.assign({}, ed448_CURVE, {
|
||||
d: BigInt('0xd78b4bdc7f0daf19f24f38c29373a2ccad46157242a50f37809b1da3412a12e79ccc9c81264cfe9ad080997058fb61c4243cc32dbaa156b9'),
|
||||
Gx: BigInt('0x79a70b2b70400553ae7c9df416c792c61128751ac92969240c25a07d728bdc93e21f7787ed6972249de732f38496cd11698713093e9c04fc'),
|
||||
Gy: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffff80000000000000000000000000000000000000000000000000000001'),
|
||||
});
|
||||
const shake256_114 = /* @__PURE__ */ wrapConstructor(() => shake256.create({ dkLen: 114 }));
|
||||
const shake256_64 = /* @__PURE__ */ wrapConstructor(() => shake256.create({ dkLen: 64 }));
|
||||
// prettier-ignore
|
||||
const _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4), _11n = BigInt(11);
|
||||
// prettier-ignore
|
||||
const _22n = BigInt(22), _44n = BigInt(44), _88n = BigInt(88), _223n = BigInt(223);
|
||||
// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4.
|
||||
// Used for efficient square root calculation.
|
||||
// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1]
|
||||
function ed448_pow_Pminus3div4(x) {
|
||||
const P = ed448_CURVE.p;
|
||||
const b2 = (x * x * x) % P;
|
||||
const b3 = (b2 * b2 * x) % P;
|
||||
const b6 = (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 b222 = (pow2(b220, _2n, P) * b2) % P;
|
||||
const b223 = (pow2(b222, _1n, P) * x) % P;
|
||||
return (pow2(b223, _223n, P) * b222) % P;
|
||||
}
|
||||
function adjustScalarBytes(bytes) {
|
||||
// Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0,
|
||||
bytes[0] &= 252; // 0b11111100
|
||||
// and the most significant bit of the last byte to 1.
|
||||
bytes[55] |= 128; // 0b10000000
|
||||
// NOTE: is NOOP for 56 bytes scalars (X25519/X448)
|
||||
bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits)
|
||||
return bytes;
|
||||
}
|
||||
// Constant-time ratio of u to v. Allows to combine inversion and square root u/√v.
|
||||
// Uses algo from RFC8032 5.1.3.
|
||||
function uvRatio(u, v) {
|
||||
const P = ed448_CURVE.p;
|
||||
// https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3
|
||||
// To compute the square root of (u/v), the first step is to compute the
|
||||
// candidate root x = (u/v)^((p+1)/4). This can be done using the
|
||||
// following trick, to use a single modular powering for both the
|
||||
// inversion of v and the square root:
|
||||
// x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p)
|
||||
const u2v = mod(u * u * v, P); // u²v
|
||||
const u3v = mod(u2v * u, P); // u³v
|
||||
const u5v3 = mod(u3v * u2v * v, P); // u⁵v³
|
||||
const root = ed448_pow_Pminus3div4(u5v3);
|
||||
const x = mod(u3v * root, P);
|
||||
// Verify that root is exists
|
||||
const x2 = mod(x * x, P); // x²
|
||||
// If vx² = u, the recovered x-coordinate is x. Otherwise, no
|
||||
// square root exists, and the decoding fails.
|
||||
return { isValid: mod(x2 * v, P) === u, value: x };
|
||||
}
|
||||
// Finite field 2n**448n - 2n**224n - 1n
|
||||
// The value fits in 448 bits, but we use 456-bit (57-byte) elements because of bitflags.
|
||||
// - ed25519 fits in 255 bits, allowing using last 1 byte for specifying bit flag of point negation.
|
||||
// - ed448 fits in 448 bits. We can't use last 1 byte: we can only use a bit 224 in the middle.
|
||||
const Fp = /* @__PURE__ */ (() => Field(ed448_CURVE.p, { BITS: 456, isLE: true }))();
|
||||
const Fn = /* @__PURE__ */ (() => Field(ed448_CURVE.n, { BITS: 456, isLE: true }))();
|
||||
// decaf448 uses 448-bit (56-byte) keys
|
||||
const Fp448 = /* @__PURE__ */ (() => Field(ed448_CURVE.p, { BITS: 448, isLE: true }))();
|
||||
const Fn448 = /* @__PURE__ */ (() => Field(ed448_CURVE.n, { BITS: 448, isLE: true }))();
|
||||
// SHAKE256(dom4(phflag,context)||x, 114)
|
||||
function dom4(data, ctx, phflag) {
|
||||
if (ctx.length > 255)
|
||||
throw new Error('context must be smaller than 255, got: ' + ctx.length);
|
||||
return concatBytes(asciiToBytes('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);
|
||||
}
|
||||
// const ed448_eddsa_opts = { adjustScalarBytes, domain: dom4 };
|
||||
// const ed448_Point = edwards(ed448_CURVE, { Fp, Fn, uvRatio });
|
||||
const ED448_DEF = /* @__PURE__ */ (() => ({
|
||||
...ed448_CURVE,
|
||||
Fp,
|
||||
Fn,
|
||||
nBitLength: Fn.BITS,
|
||||
hash: shake256_114,
|
||||
adjustScalarBytes,
|
||||
domain: dom4,
|
||||
uvRatio,
|
||||
}))();
|
||||
/**
|
||||
* ed448 EdDSA curve and methods.
|
||||
* @example
|
||||
* import { ed448 } from '@noble/curves/ed448';
|
||||
* const { secretKey, publicKey } = ed448.keygen();
|
||||
* const msg = new TextEncoder().encode('hello');
|
||||
* const sig = ed448.sign(msg, secretKey);
|
||||
* const isValid = ed448.verify(sig, msg, publicKey);
|
||||
*/
|
||||
export const ed448 = twistedEdwards(ED448_DEF);
|
||||
// There is no ed448ctx, since ed448 supports ctx by default
|
||||
/** Prehashed version of ed448. Accepts already-hashed messages in sign() and verify(). */
|
||||
export const ed448ph = /* @__PURE__ */ (() => twistedEdwards({
|
||||
...ED448_DEF,
|
||||
prehash: shake256_64,
|
||||
}))();
|
||||
/**
|
||||
* E448 curve, defined by NIST.
|
||||
* E448 != edwards448 used in ed448.
|
||||
* E448 is birationally equivalent to edwards448.
|
||||
*/
|
||||
export const E448 = edwards(E448_CURVE);
|
||||
/**
|
||||
* ECDH using curve448 aka x448.
|
||||
* x448 has 56-byte keys as per RFC 7748, while
|
||||
* ed448 has 57-byte keys as per RFC 8032.
|
||||
*/
|
||||
export const x448 = /* @__PURE__ */ (() => {
|
||||
const P = ed448_CURVE.p;
|
||||
return montgomery({
|
||||
P,
|
||||
type: 'x448',
|
||||
powPminus2: (x) => {
|
||||
const Pminus3div4 = ed448_pow_Pminus3div4(x);
|
||||
const Pminus3 = pow2(Pminus3div4, _2n, P);
|
||||
return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2
|
||||
},
|
||||
adjustScalarBytes,
|
||||
});
|
||||
})();
|
||||
// Hash To Curve Elligator2 Map
|
||||
const ELL2_C1 = /* @__PURE__ */ (() => (Fp.ORDER - BigInt(3)) / BigInt(4))(); // 1. c1 = (q - 3) / 4 # Integer arithmetic
|
||||
const ELL2_J = /* @__PURE__ */ BigInt(156326);
|
||||
function map_to_curve_elligator2_curve448(u) {
|
||||
let tv1 = Fp.sqr(u); // 1. tv1 = u^2
|
||||
let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1
|
||||
tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0
|
||||
let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1
|
||||
let x1n = Fp.neg(ELL2_J); // 5. x1n = -J
|
||||
let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2
|
||||
let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3
|
||||
let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd
|
||||
gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd
|
||||
gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2
|
||||
gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2
|
||||
let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2
|
||||
tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd
|
||||
tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3
|
||||
let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4)
|
||||
y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4)
|
||||
let x2n = Fp.mul(x1n, Fp.neg(tv1)); // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd
|
||||
let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u
|
||||
y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1)
|
||||
tv2 = Fp.sqr(y1); // 20. tv2 = y1^2
|
||||
tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd
|
||||
let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1
|
||||
let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2
|
||||
let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2
|
||||
let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y
|
||||
y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3)
|
||||
return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1)
|
||||
}
|
||||
function map_to_curve_elligator2_edwards448(u) {
|
||||
let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u)
|
||||
let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2
|
||||
let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2
|
||||
let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2
|
||||
let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2
|
||||
let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2
|
||||
let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2
|
||||
let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2
|
||||
xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2
|
||||
xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd
|
||||
xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn
|
||||
xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4
|
||||
tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2
|
||||
tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2
|
||||
let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2
|
||||
let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2
|
||||
tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4
|
||||
let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2
|
||||
tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn
|
||||
let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4
|
||||
let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2
|
||||
yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4
|
||||
yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2
|
||||
tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2
|
||||
tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2
|
||||
tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd
|
||||
tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2
|
||||
tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1
|
||||
let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1
|
||||
tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2
|
||||
yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4
|
||||
tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd
|
||||
let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0
|
||||
xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e)
|
||||
xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e)
|
||||
yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e)
|
||||
yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e)
|
||||
const inv = FpInvertBatch(Fp, [xEd, yEd], true); // batch division
|
||||
return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd)
|
||||
}
|
||||
/** Hashing / encoding to ed448 points / field. RFC 9380 methods. */
|
||||
export const ed448_hasher = /* @__PURE__ */ (() => createHasher(ed448.Point, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), {
|
||||
DST: 'edwards448_XOF:SHAKE256_ELL2_RO_',
|
||||
encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_',
|
||||
p: Fp.ORDER,
|
||||
m: 1,
|
||||
k: 224,
|
||||
expand: 'xof',
|
||||
hash: shake256,
|
||||
}))();
|
||||
// 1-d
|
||||
const ONE_MINUS_D = /* @__PURE__ */ BigInt('39082');
|
||||
// 1-2d
|
||||
const ONE_MINUS_TWO_D = /* @__PURE__ */ BigInt('78163');
|
||||
// √(-d)
|
||||
const SQRT_MINUS_D = /* @__PURE__ */ BigInt('98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214');
|
||||
// 1 / √(-d)
|
||||
const INVSQRT_MINUS_D = /* @__PURE__ */ BigInt('315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716');
|
||||
// Calculates 1/√(number)
|
||||
const invertSqrt = (number) => uvRatio(_1n, number);
|
||||
/**
|
||||
* Elligator map for hash-to-curve of decaf448.
|
||||
* Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-C)
|
||||
* and [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-element-derivation-2).
|
||||
*/
|
||||
function calcElligatorDecafMap(r0) {
|
||||
const { d } = ed448_CURVE;
|
||||
const P = Fp.ORDER;
|
||||
const mod = (n) => Fp.create(n);
|
||||
const r = mod(-(r0 * r0)); // 1
|
||||
const u0 = mod(d * (r - _1n)); // 2
|
||||
const u1 = mod((u0 + _1n) * (u0 - r)); // 3
|
||||
const { isValid: was_square, value: v } = uvRatio(ONE_MINUS_TWO_D, mod((r + _1n) * u1)); // 4
|
||||
let v_prime = v; // 5
|
||||
if (!was_square)
|
||||
v_prime = mod(r0 * v);
|
||||
let sgn = _1n; // 6
|
||||
if (!was_square)
|
||||
sgn = mod(-_1n);
|
||||
const s = mod(v_prime * (r + _1n)); // 7
|
||||
let s_abs = s;
|
||||
if (isNegativeLE(s, P))
|
||||
s_abs = mod(-s);
|
||||
const s2 = s * s;
|
||||
const W0 = mod(s_abs * _2n); // 8
|
||||
const W1 = mod(s2 + _1n); // 9
|
||||
const W2 = mod(s2 - _1n); // 10
|
||||
const W3 = mod(v_prime * s * (r - _1n) * ONE_MINUS_TWO_D + sgn); // 11
|
||||
return new ed448.Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));
|
||||
}
|
||||
function decaf448_map(bytes) {
|
||||
abytes(bytes, 112);
|
||||
const skipValidation = true;
|
||||
// Note: Similar to the field element decoding described in
|
||||
// [RFC7748], and unlike the field element decoding described in
|
||||
// Section 5.3.1, non-canonical values are accepted.
|
||||
const r1 = Fp448.create(Fp448.fromBytes(bytes.subarray(0, 56), skipValidation));
|
||||
const R1 = calcElligatorDecafMap(r1);
|
||||
const r2 = Fp448.create(Fp448.fromBytes(bytes.subarray(56, 112), skipValidation));
|
||||
const R2 = calcElligatorDecafMap(r2);
|
||||
return new _DecafPoint(R1.add(R2));
|
||||
}
|
||||
/**
|
||||
* Each ed448/EdwardsPoint has 4 different equivalent points. This can be
|
||||
* a source of bugs for protocols like ring signatures. Decaf was created to solve this.
|
||||
* Decaf point operates in X:Y:Z:T extended coordinates like EdwardsPoint,
|
||||
* but it should work in its own namespace: do not combine those two.
|
||||
* See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).
|
||||
*/
|
||||
class _DecafPoint extends PrimeEdwardsPoint {
|
||||
constructor(ep) {
|
||||
super(ep);
|
||||
}
|
||||
static fromAffine(ap) {
|
||||
return new _DecafPoint(ed448.Point.fromAffine(ap));
|
||||
}
|
||||
assertSame(other) {
|
||||
if (!(other instanceof _DecafPoint))
|
||||
throw new Error('DecafPoint expected');
|
||||
}
|
||||
init(ep) {
|
||||
return new _DecafPoint(ep);
|
||||
}
|
||||
/** @deprecated use `import { decaf448_hasher } from '@noble/curves/ed448.js';` */
|
||||
static hashToCurve(hex) {
|
||||
return decaf448_map(ensureBytes('decafHash', hex, 112));
|
||||
}
|
||||
static fromBytes(bytes) {
|
||||
abytes(bytes, 56);
|
||||
const { d } = ed448_CURVE;
|
||||
const P = Fp.ORDER;
|
||||
const mod = (n) => Fp448.create(n);
|
||||
const s = Fp448.fromBytes(bytes);
|
||||
// 1. Check that s_bytes is the canonical encoding of a field element, or else abort.
|
||||
// 2. Check that s is non-negative, or else abort
|
||||
if (!equalBytes(Fn448.toBytes(s), bytes) || isNegativeLE(s, P))
|
||||
throw new Error('invalid decaf448 encoding 1');
|
||||
const s2 = mod(s * s); // 1
|
||||
const u1 = mod(_1n + s2); // 2
|
||||
const u1sq = mod(u1 * u1);
|
||||
const u2 = mod(u1sq - _4n * d * s2); // 3
|
||||
const { isValid, value: invsqrt } = invertSqrt(mod(u2 * u1sq)); // 4
|
||||
let u3 = mod((s + s) * invsqrt * u1 * SQRT_MINUS_D); // 5
|
||||
if (isNegativeLE(u3, P))
|
||||
u3 = mod(-u3);
|
||||
const x = mod(u3 * invsqrt * u2 * INVSQRT_MINUS_D); // 6
|
||||
const y = mod((_1n - s2) * invsqrt * u1); // 7
|
||||
const t = mod(x * y); // 8
|
||||
if (!isValid)
|
||||
throw new Error('invalid decaf448 encoding 2');
|
||||
return new _DecafPoint(new ed448.Point(x, y, _1n, t));
|
||||
}
|
||||
/**
|
||||
* Converts decaf-encoded string to decaf point.
|
||||
* Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode-2).
|
||||
* @param hex Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding
|
||||
*/
|
||||
static fromHex(hex) {
|
||||
return _DecafPoint.fromBytes(ensureBytes('decafHex', hex, 56));
|
||||
}
|
||||
/** @deprecated use `import { pippenger } from '@noble/curves/abstract/curve.js';` */
|
||||
static msm(points, scalars) {
|
||||
return pippenger(_DecafPoint, Fn, points, scalars);
|
||||
}
|
||||
/**
|
||||
* Encodes decaf point to Uint8Array.
|
||||
* Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode-2).
|
||||
*/
|
||||
toBytes() {
|
||||
const { X, Z, T } = this.ep;
|
||||
const P = Fp.ORDER;
|
||||
const mod = (n) => Fp.create(n);
|
||||
const u1 = mod(mod(X + T) * mod(X - T)); // 1
|
||||
const x2 = mod(X * X);
|
||||
const { value: invsqrt } = invertSqrt(mod(u1 * ONE_MINUS_D * x2)); // 2
|
||||
let ratio = mod(invsqrt * u1 * SQRT_MINUS_D); // 3
|
||||
if (isNegativeLE(ratio, P))
|
||||
ratio = mod(-ratio);
|
||||
const u2 = mod(INVSQRT_MINUS_D * ratio * Z - T); // 4
|
||||
let s = mod(ONE_MINUS_D * invsqrt * X * u2); // 5
|
||||
if (isNegativeLE(s, P))
|
||||
s = mod(-s);
|
||||
return Fn448.toBytes(s);
|
||||
}
|
||||
/**
|
||||
* Compare one point to another.
|
||||
* Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals-2).
|
||||
*/
|
||||
equals(other) {
|
||||
this.assertSame(other);
|
||||
const { X: X1, Y: Y1 } = this.ep;
|
||||
const { X: X2, Y: Y2 } = other.ep;
|
||||
// (x1 * y2 == y1 * x2)
|
||||
return Fp.create(X1 * Y2) === Fp.create(Y1 * X2);
|
||||
}
|
||||
is0() {
|
||||
return this.equals(_DecafPoint.ZERO);
|
||||
}
|
||||
}
|
||||
// The following gymnastics is done because typescript strips comments otherwise
|
||||
// prettier-ignore
|
||||
_DecafPoint.BASE =
|
||||
/* @__PURE__ */ (() => new _DecafPoint(ed448.Point.BASE).multiplyUnsafe(_2n))();
|
||||
// prettier-ignore
|
||||
_DecafPoint.ZERO =
|
||||
/* @__PURE__ */ (() => new _DecafPoint(ed448.Point.ZERO))();
|
||||
// prettier-ignore
|
||||
_DecafPoint.Fp =
|
||||
/* @__PURE__ */ (() => Fp448)();
|
||||
// prettier-ignore
|
||||
_DecafPoint.Fn =
|
||||
/* @__PURE__ */ (() => Fn448)();
|
||||
export const decaf448 = { Point: _DecafPoint };
|
||||
/** Hashing to decaf448 points / field. RFC 9380 methods. */
|
||||
export const decaf448_hasher = {
|
||||
hashToCurve(msg, options) {
|
||||
const DST = options?.DST || 'decaf448_XOF:SHAKE256_D448MAP_RO_';
|
||||
return decaf448_map(expand_message_xof(msg, DST, 112, 224, shake256));
|
||||
},
|
||||
// Warning: has big modulo bias of 2^-64.
|
||||
// RFC is invalid. RFC says "use 64-byte xof", while for 2^-112 bias
|
||||
// it must use 84-byte xof (56+56/2), not 64.
|
||||
hashToScalar(msg, options = { DST: _DST_scalar }) {
|
||||
// Can't use `Fn448.fromBytes()`. 64-byte input => 56-byte field element
|
||||
const xof = expand_message_xof(msg, options.DST, 64, 256, shake256);
|
||||
return Fn448.create(bytesToNumberLE(xof));
|
||||
},
|
||||
};
|
||||
// export const decaf448_oprf: OPRF = createORPF({
|
||||
// name: 'decaf448-SHAKE256',
|
||||
// Point: DecafPoint,
|
||||
// hash: (msg: Uint8Array) => shake256(msg, { dkLen: 64 }),
|
||||
// hashToGroup: decaf448_hasher.hashToCurve,
|
||||
// hashToScalar: decaf448_hasher.hashToScalar,
|
||||
// });
|
||||
/**
|
||||
* Weird / bogus points, useful for debugging.
|
||||
* Unlike ed25519, there is no ed448 generator point which can produce full T subgroup.
|
||||
* Instead, there is a Klein four-group, which spans over 2 independent 2-torsion points:
|
||||
* (0, 1), (0, -1), (-1, 0), (1, 0).
|
||||
*/
|
||||
export const ED448_TORSION_SUBGROUP = [
|
||||
'010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
|
||||
'fefffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffff00',
|
||||
'000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
|
||||
'000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080',
|
||||
];
|
||||
/** @deprecated use `decaf448.Point` */
|
||||
export const DecafPoint = _DecafPoint;
|
||||
/** @deprecated use `import { ed448_hasher } from '@noble/curves/ed448.js';` */
|
||||
export const hashToCurve = /* @__PURE__ */ (() => ed448_hasher.hashToCurve)();
|
||||
/** @deprecated use `import { ed448_hasher } from '@noble/curves/ed448.js';` */
|
||||
export const encodeToCurve = /* @__PURE__ */ (() => ed448_hasher.encodeToCurve)();
|
||||
/** @deprecated use `import { decaf448_hasher } from '@noble/curves/ed448.js';` */
|
||||
export const hashToDecaf448 = /* @__PURE__ */ (() => decaf448_hasher.hashToCurve)();
|
||||
/** @deprecated use `import { decaf448_hasher } from '@noble/curves/ed448.js';` */
|
||||
export const hash_to_decaf448 = /* @__PURE__ */ (() => decaf448_hasher.hashToCurve)();
|
||||
/** @deprecated use `ed448.utils.toMontgomery` */
|
||||
export function edwardsToMontgomeryPub(edwardsPub) {
|
||||
return ed448.utils.toMontgomery(ensureBytes('pub', edwardsPub));
|
||||
}
|
||||
/** @deprecated use `ed448.utils.toMontgomery` */
|
||||
export const edwardsToMontgomery = edwardsToMontgomeryPub;
|
||||
//# sourceMappingURL=ed448.js.map
|
||||
@@ -0,0 +1,2 @@
|
||||
import { _ as queries, a as and, c as exprInterpreter, d as include, f as interpreter, g as or, h as not, i as filterVitePlugins, l as id, m as moduleType, n as makeIdFiltersToMatchWithQuery, o as code, p as interpreterImpl, r as prefixRegex, s as exclude, t as exactRegex, u as importerId, v as query } from "../filter-B_mD-HGz.mjs";
|
||||
export { and, code, exactRegex, exclude, exprInterpreter, filterVitePlugins, id, importerId, include, interpreter, interpreterImpl, makeIdFiltersToMatchWithQuery, moduleType, not, or, prefixRegex, queries, query };
|
||||
@@ -0,0 +1,7 @@
|
||||
"use strict";
|
||||
|
||||
function _identity(x) {
|
||||
return x;
|
||||
}
|
||||
|
||||
exports._ = _identity;
|
||||
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* @fileoverview Rule to disallow certain object properties
|
||||
* @author Will Klein & Eli White
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "suggestion",
|
||||
|
||||
docs: {
|
||||
description: "Disallow certain properties on certain objects",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/latest/rules/no-restricted-properties",
|
||||
},
|
||||
|
||||
schema: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "object",
|
||||
properties: {
|
||||
object: {
|
||||
type: "string",
|
||||
},
|
||||
property: {
|
||||
type: "string",
|
||||
},
|
||||
allowObjects: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "string",
|
||||
},
|
||||
uniqueItems: true,
|
||||
},
|
||||
allowProperties: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "string",
|
||||
},
|
||||
uniqueItems: true,
|
||||
},
|
||||
message: {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
anyOf: [
|
||||
{
|
||||
required: ["object"],
|
||||
},
|
||||
{
|
||||
required: ["property"],
|
||||
},
|
||||
],
|
||||
not: {
|
||||
anyOf: [
|
||||
{ required: ["allowObjects", "object"] },
|
||||
{ required: ["allowProperties", "property"] },
|
||||
],
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
uniqueItems: true,
|
||||
},
|
||||
|
||||
defaultOptions: [],
|
||||
|
||||
messages: {
|
||||
restrictedObjectProperty:
|
||||
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
|
||||
"'{{objectName}}.{{propertyName}}' is restricted from being used.{{allowedPropertiesMessage}}{{message}}",
|
||||
restrictedProperty:
|
||||
// eslint-disable-next-line eslint-plugin/report-message-format -- Custom message might not end in a period
|
||||
"'{{propertyName}}' is restricted from being used.{{allowedObjectsMessage}}{{message}}",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const restrictedCalls = context.options;
|
||||
|
||||
if (restrictedCalls.length === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const restrictedProperties = new Map();
|
||||
const globallyRestrictedObjects = new Map();
|
||||
const globallyRestrictedProperties = new Map();
|
||||
|
||||
restrictedCalls.forEach(option => {
|
||||
const objectName = option.object;
|
||||
const propertyName = option.property;
|
||||
|
||||
if (typeof objectName === "undefined") {
|
||||
globallyRestrictedProperties.set(propertyName, {
|
||||
allowObjects: option.allowObjects,
|
||||
message: option.message,
|
||||
});
|
||||
} else if (typeof propertyName === "undefined") {
|
||||
globallyRestrictedObjects.set(objectName, {
|
||||
allowProperties: option.allowProperties,
|
||||
message: option.message,
|
||||
});
|
||||
} else {
|
||||
if (!restrictedProperties.has(objectName)) {
|
||||
restrictedProperties.set(objectName, new Map());
|
||||
}
|
||||
|
||||
restrictedProperties.get(objectName).set(propertyName, {
|
||||
message: option.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Checks if a name is in the allowed list.
|
||||
* @param {string} name The name to check
|
||||
* @param {string[]} [allowedList] The list of allowed names
|
||||
* @returns {boolean} True if the name is allowed, false otherwise
|
||||
*/
|
||||
function isAllowed(name, allowedList) {
|
||||
if (!allowedList) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return allowedList.includes(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to see whether a property access is restricted, and reports it if so.
|
||||
* @param {ASTNode} node The node to report
|
||||
* @param {string} objectName The name of the object
|
||||
* @param {string} propertyName The name of the property
|
||||
* @returns {undefined}
|
||||
*/
|
||||
function checkPropertyAccess(node, objectName, propertyName) {
|
||||
if (propertyName === null) {
|
||||
return;
|
||||
}
|
||||
const matchedObject = restrictedProperties.get(objectName);
|
||||
const matchedObjectProperty = matchedObject
|
||||
? matchedObject.get(propertyName)
|
||||
: globallyRestrictedObjects.get(objectName);
|
||||
const globalMatchedProperty =
|
||||
globallyRestrictedProperties.get(propertyName);
|
||||
|
||||
if (
|
||||
matchedObjectProperty &&
|
||||
!isAllowed(propertyName, matchedObjectProperty.allowProperties)
|
||||
) {
|
||||
const message = matchedObjectProperty.message
|
||||
? ` ${matchedObjectProperty.message}`
|
||||
: "";
|
||||
const allowedPropertiesMessage =
|
||||
matchedObjectProperty.allowProperties
|
||||
? ` Only these properties are allowed: ${matchedObjectProperty.allowProperties.join(", ")}.`
|
||||
: "";
|
||||
|
||||
context.report({
|
||||
node,
|
||||
messageId: "restrictedObjectProperty",
|
||||
data: {
|
||||
objectName,
|
||||
propertyName,
|
||||
message,
|
||||
allowedPropertiesMessage,
|
||||
},
|
||||
});
|
||||
} else if (
|
||||
globalMatchedProperty &&
|
||||
!isAllowed(objectName, globalMatchedProperty.allowObjects)
|
||||
) {
|
||||
const message = globalMatchedProperty.message
|
||||
? ` ${globalMatchedProperty.message}`
|
||||
: "";
|
||||
const allowedObjectsMessage = globalMatchedProperty.allowObjects
|
||||
? ` Property '${propertyName}' is only allowed on these objects: ${globalMatchedProperty.allowObjects.join(", ")}.`
|
||||
: "";
|
||||
|
||||
context.report({
|
||||
node,
|
||||
messageId: "restrictedProperty",
|
||||
data: {
|
||||
propertyName,
|
||||
message,
|
||||
allowedObjectsMessage,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
MemberExpression(node) {
|
||||
checkPropertyAccess(
|
||||
node,
|
||||
node.object && node.object.name,
|
||||
astUtils.getStaticPropertyName(node),
|
||||
);
|
||||
},
|
||||
ObjectPattern(node) {
|
||||
let objectName = null;
|
||||
|
||||
if (node.parent.type === "VariableDeclarator") {
|
||||
if (
|
||||
node.parent.init &&
|
||||
node.parent.init.type === "Identifier"
|
||||
) {
|
||||
objectName = node.parent.init.name;
|
||||
}
|
||||
} else if (
|
||||
node.parent.type === "AssignmentExpression" ||
|
||||
node.parent.type === "AssignmentPattern"
|
||||
) {
|
||||
if (node.parent.right.type === "Identifier") {
|
||||
objectName = node.parent.right.name;
|
||||
}
|
||||
}
|
||||
|
||||
node.properties.forEach(property => {
|
||||
checkPropertyAccess(
|
||||
node,
|
||||
objectName,
|
||||
astUtils.getStaticPropertyName(property),
|
||||
);
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
var unsupportedIterableToArray = require("./unsupportedIterableToArray.js");
|
||||
function _createForOfIteratorHelperLoose(r, e) {
|
||||
var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
|
||||
if (t) return (t = t.call(r)).next.bind(t);
|
||||
if (Array.isArray(r) || (t = unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
|
||||
t && (r = t);
|
||||
var o = 0;
|
||||
return function () {
|
||||
return o >= r.length ? {
|
||||
done: !0
|
||||
} : {
|
||||
done: !1,
|
||||
value: r[o++]
|
||||
};
|
||||
};
|
||||
}
|
||||
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
||||
}
|
||||
module.exports = _createForOfIteratorHelperLoose, module.exports.__esModule = true, module.exports["default"] = module.exports;
|
||||
@@ -0,0 +1,444 @@
|
||||
'use strict';
|
||||
|
||||
/** Highest positive signed 32-bit float value */
|
||||
const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
|
||||
|
||||
/** Bootstring parameters */
|
||||
const base = 36;
|
||||
const tMin = 1;
|
||||
const tMax = 26;
|
||||
const skew = 38;
|
||||
const damp = 700;
|
||||
const initialBias = 72;
|
||||
const initialN = 128; // 0x80
|
||||
const delimiter = '-'; // '\x2D'
|
||||
|
||||
/** Regular expressions */
|
||||
const regexPunycode = /^xn--/;
|
||||
const regexNonASCII = /[^\0-\x7F]/; // Note: U+007F DEL is excluded too.
|
||||
const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
|
||||
|
||||
/** Error messages */
|
||||
const errors = {
|
||||
'overflow': 'Overflow: input needs wider integers to process',
|
||||
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
|
||||
'invalid-input': 'Invalid input'
|
||||
};
|
||||
|
||||
/** Convenience shortcuts */
|
||||
const baseMinusTMin = base - tMin;
|
||||
const floor = Math.floor;
|
||||
const stringFromCharCode = String.fromCharCode;
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
/**
|
||||
* A generic error utility function.
|
||||
* @private
|
||||
* @param {String} type The error type.
|
||||
* @returns {Error} Throws a `RangeError` with the applicable error message.
|
||||
*/
|
||||
function error(type) {
|
||||
throw new RangeError(errors[type]);
|
||||
}
|
||||
|
||||
/**
|
||||
* A generic `Array#map` utility function.
|
||||
* @private
|
||||
* @param {Array} array The array to iterate over.
|
||||
* @param {Function} callback The function that gets called for every array
|
||||
* item.
|
||||
* @returns {Array} A new array of values returned by the callback function.
|
||||
*/
|
||||
function map(array, callback) {
|
||||
const result = [];
|
||||
let length = array.length;
|
||||
while (length--) {
|
||||
result[length] = callback(array[length]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* A simple `Array#map`-like wrapper to work with domain name strings or email
|
||||
* addresses.
|
||||
* @private
|
||||
* @param {String} domain The domain name or email address.
|
||||
* @param {Function} callback The function that gets called for every
|
||||
* character.
|
||||
* @returns {String} A new string of characters returned by the callback
|
||||
* function.
|
||||
*/
|
||||
function mapDomain(domain, callback) {
|
||||
const parts = domain.split('@');
|
||||
let result = '';
|
||||
if (parts.length > 1) {
|
||||
// In email addresses, only the domain name should be punycoded. Leave
|
||||
// the local part (i.e. everything up to `@`) intact.
|
||||
result = parts[0] + '@';
|
||||
domain = parts[1];
|
||||
}
|
||||
// Avoid `split(regex)` for IE8 compatibility. See #17.
|
||||
domain = domain.replace(regexSeparators, '\x2E');
|
||||
const labels = domain.split('.');
|
||||
const encoded = map(labels, callback).join('.');
|
||||
return result + encoded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an array containing the numeric code points of each Unicode
|
||||
* character in the string. While JavaScript uses UCS-2 internally,
|
||||
* this function will convert a pair of surrogate halves (each of which
|
||||
* UCS-2 exposes as separate characters) into a single code point,
|
||||
* matching UTF-16.
|
||||
* @see `punycode.ucs2.encode`
|
||||
* @see <https://mathiasbynens.be/notes/javascript-encoding>
|
||||
* @memberOf punycode.ucs2
|
||||
* @name decode
|
||||
* @param {String} string The Unicode input string (UCS-2).
|
||||
* @returns {Array} The new array of code points.
|
||||
*/
|
||||
function ucs2decode(string) {
|
||||
const output = [];
|
||||
let counter = 0;
|
||||
const length = string.length;
|
||||
while (counter < length) {
|
||||
const value = string.charCodeAt(counter++);
|
||||
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
|
||||
// It's a high surrogate, and there is a next character.
|
||||
const extra = string.charCodeAt(counter++);
|
||||
if ((extra & 0xFC00) == 0xDC00) { // Low surrogate.
|
||||
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
|
||||
} else {
|
||||
// It's an unmatched surrogate; only append this code unit, in case the
|
||||
// next code unit is the high surrogate of a surrogate pair.
|
||||
output.push(value);
|
||||
counter--;
|
||||
}
|
||||
} else {
|
||||
output.push(value);
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a string based on an array of numeric code points.
|
||||
* @see `punycode.ucs2.decode`
|
||||
* @memberOf punycode.ucs2
|
||||
* @name encode
|
||||
* @param {Array} codePoints The array of numeric code points.
|
||||
* @returns {String} The new Unicode string (UCS-2).
|
||||
*/
|
||||
const ucs2encode = codePoints => String.fromCodePoint(...codePoints);
|
||||
|
||||
/**
|
||||
* Converts a basic code point into a digit/integer.
|
||||
* @see `digitToBasic()`
|
||||
* @private
|
||||
* @param {Number} codePoint The basic numeric code point value.
|
||||
* @returns {Number} The numeric value of a basic code point (for use in
|
||||
* representing integers) in the range `0` to `base - 1`, or `base` if
|
||||
* the code point does not represent a value.
|
||||
*/
|
||||
const basicToDigit = function(codePoint) {
|
||||
if (codePoint >= 0x30 && codePoint < 0x3A) {
|
||||
return 26 + (codePoint - 0x30);
|
||||
}
|
||||
if (codePoint >= 0x41 && codePoint < 0x5B) {
|
||||
return codePoint - 0x41;
|
||||
}
|
||||
if (codePoint >= 0x61 && codePoint < 0x7B) {
|
||||
return codePoint - 0x61;
|
||||
}
|
||||
return base;
|
||||
};
|
||||
|
||||
/**
|
||||
* Converts a digit/integer into a basic code point.
|
||||
* @see `basicToDigit()`
|
||||
* @private
|
||||
* @param {Number} digit The numeric value of a basic code point.
|
||||
* @returns {Number} The basic code point whose value (when used for
|
||||
* representing integers) is `digit`, which needs to be in the range
|
||||
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
|
||||
* used; else, the lowercase form is used. The behavior is undefined
|
||||
* if `flag` is non-zero and `digit` has no uppercase form.
|
||||
*/
|
||||
const digitToBasic = function(digit, flag) {
|
||||
// 0..25 map to ASCII a..z or A..Z
|
||||
// 26..35 map to ASCII 0..9
|
||||
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
|
||||
};
|
||||
|
||||
/**
|
||||
* Bias adaptation function as per section 3.4 of RFC 3492.
|
||||
* https://tools.ietf.org/html/rfc3492#section-3.4
|
||||
* @private
|
||||
*/
|
||||
const adapt = function(delta, numPoints, firstTime) {
|
||||
let k = 0;
|
||||
delta = firstTime ? floor(delta / damp) : delta >> 1;
|
||||
delta += floor(delta / numPoints);
|
||||
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
|
||||
delta = floor(delta / baseMinusTMin);
|
||||
}
|
||||
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
|
||||
};
|
||||
|
||||
/**
|
||||
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
|
||||
* symbols.
|
||||
* @memberOf punycode
|
||||
* @param {String} input The Punycode string of ASCII-only symbols.
|
||||
* @returns {String} The resulting string of Unicode symbols.
|
||||
*/
|
||||
const decode = function(input) {
|
||||
// Don't use UCS-2.
|
||||
const output = [];
|
||||
const inputLength = input.length;
|
||||
let i = 0;
|
||||
let n = initialN;
|
||||
let bias = initialBias;
|
||||
|
||||
// Handle the basic code points: let `basic` be the number of input code
|
||||
// points before the last delimiter, or `0` if there is none, then copy
|
||||
// the first basic code points to the output.
|
||||
|
||||
let basic = input.lastIndexOf(delimiter);
|
||||
if (basic < 0) {
|
||||
basic = 0;
|
||||
}
|
||||
|
||||
for (let j = 0; j < basic; ++j) {
|
||||
// if it's not a basic code point
|
||||
if (input.charCodeAt(j) >= 0x80) {
|
||||
error('not-basic');
|
||||
}
|
||||
output.push(input.charCodeAt(j));
|
||||
}
|
||||
|
||||
// Main decoding loop: start just after the last delimiter if any basic code
|
||||
// points were copied; start at the beginning otherwise.
|
||||
|
||||
for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
|
||||
|
||||
// `index` is the index of the next character to be consumed.
|
||||
// Decode a generalized variable-length integer into `delta`,
|
||||
// which gets added to `i`. The overflow checking is easier
|
||||
// if we increase `i` as we go, then subtract off its starting
|
||||
// value at the end to obtain `delta`.
|
||||
const oldi = i;
|
||||
for (let w = 1, k = base; /* no condition */; k += base) {
|
||||
|
||||
if (index >= inputLength) {
|
||||
error('invalid-input');
|
||||
}
|
||||
|
||||
const digit = basicToDigit(input.charCodeAt(index++));
|
||||
|
||||
if (digit >= base) {
|
||||
error('invalid-input');
|
||||
}
|
||||
if (digit > floor((maxInt - i) / w)) {
|
||||
error('overflow');
|
||||
}
|
||||
|
||||
i += digit * w;
|
||||
const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
|
||||
|
||||
if (digit < t) {
|
||||
break;
|
||||
}
|
||||
|
||||
const baseMinusT = base - t;
|
||||
if (w > floor(maxInt / baseMinusT)) {
|
||||
error('overflow');
|
||||
}
|
||||
|
||||
w *= baseMinusT;
|
||||
|
||||
}
|
||||
|
||||
const out = output.length + 1;
|
||||
bias = adapt(i - oldi, out, oldi == 0);
|
||||
|
||||
// `i` was supposed to wrap around from `out` to `0`,
|
||||
// incrementing `n` each time, so we'll fix that now:
|
||||
if (floor(i / out) > maxInt - n) {
|
||||
error('overflow');
|
||||
}
|
||||
|
||||
n += floor(i / out);
|
||||
i %= out;
|
||||
|
||||
// Insert `n` at position `i` of the output.
|
||||
output.splice(i++, 0, n);
|
||||
|
||||
}
|
||||
|
||||
return String.fromCodePoint(...output);
|
||||
};
|
||||
|
||||
/**
|
||||
* Converts a string of Unicode symbols (e.g. a domain name label) to a
|
||||
* Punycode string of ASCII-only symbols.
|
||||
* @memberOf punycode
|
||||
* @param {String} input The string of Unicode symbols.
|
||||
* @returns {String} The resulting Punycode string of ASCII-only symbols.
|
||||
*/
|
||||
const encode = function(input) {
|
||||
const output = [];
|
||||
|
||||
// Convert the input in UCS-2 to an array of Unicode code points.
|
||||
input = ucs2decode(input);
|
||||
|
||||
// Cache the length.
|
||||
const inputLength = input.length;
|
||||
|
||||
// Initialize the state.
|
||||
let n = initialN;
|
||||
let delta = 0;
|
||||
let bias = initialBias;
|
||||
|
||||
// Handle the basic code points.
|
||||
for (const currentValue of input) {
|
||||
if (currentValue < 0x80) {
|
||||
output.push(stringFromCharCode(currentValue));
|
||||
}
|
||||
}
|
||||
|
||||
const basicLength = output.length;
|
||||
let handledCPCount = basicLength;
|
||||
|
||||
// `handledCPCount` is the number of code points that have been handled;
|
||||
// `basicLength` is the number of basic code points.
|
||||
|
||||
// Finish the basic string with a delimiter unless it's empty.
|
||||
if (basicLength) {
|
||||
output.push(delimiter);
|
||||
}
|
||||
|
||||
// Main encoding loop:
|
||||
while (handledCPCount < inputLength) {
|
||||
|
||||
// All non-basic code points < n have been handled already. Find the next
|
||||
// larger one:
|
||||
let m = maxInt;
|
||||
for (const currentValue of input) {
|
||||
if (currentValue >= n && currentValue < m) {
|
||||
m = currentValue;
|
||||
}
|
||||
}
|
||||
|
||||
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
|
||||
// but guard against overflow.
|
||||
const handledCPCountPlusOne = handledCPCount + 1;
|
||||
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
|
||||
error('overflow');
|
||||
}
|
||||
|
||||
delta += (m - n) * handledCPCountPlusOne;
|
||||
n = m;
|
||||
|
||||
for (const currentValue of input) {
|
||||
if (currentValue < n && ++delta > maxInt) {
|
||||
error('overflow');
|
||||
}
|
||||
if (currentValue === n) {
|
||||
// Represent delta as a generalized variable-length integer.
|
||||
let q = delta;
|
||||
for (let k = base; /* no condition */; k += base) {
|
||||
const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
|
||||
if (q < t) {
|
||||
break;
|
||||
}
|
||||
const qMinusT = q - t;
|
||||
const baseMinusT = base - t;
|
||||
output.push(
|
||||
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
|
||||
);
|
||||
q = floor(qMinusT / baseMinusT);
|
||||
}
|
||||
|
||||
output.push(stringFromCharCode(digitToBasic(q, 0)));
|
||||
bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength);
|
||||
delta = 0;
|
||||
++handledCPCount;
|
||||
}
|
||||
}
|
||||
|
||||
++delta;
|
||||
++n;
|
||||
|
||||
}
|
||||
return output.join('');
|
||||
};
|
||||
|
||||
/**
|
||||
* Converts a Punycode string representing a domain name or an email address
|
||||
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
|
||||
* it doesn't matter if you call it on a string that has already been
|
||||
* converted to Unicode.
|
||||
* @memberOf punycode
|
||||
* @param {String} input The Punycoded domain name or email address to
|
||||
* convert to Unicode.
|
||||
* @returns {String} The Unicode representation of the given Punycode
|
||||
* string.
|
||||
*/
|
||||
const toUnicode = function(input) {
|
||||
return mapDomain(input, function(string) {
|
||||
return regexPunycode.test(string)
|
||||
? decode(string.slice(4).toLowerCase())
|
||||
: string;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Converts a Unicode string representing a domain name or an email address to
|
||||
* Punycode. Only the non-ASCII parts of the domain name will be converted,
|
||||
* i.e. it doesn't matter if you call it with a domain that's already in
|
||||
* ASCII.
|
||||
* @memberOf punycode
|
||||
* @param {String} input The domain name or email address to convert, as a
|
||||
* Unicode string.
|
||||
* @returns {String} The Punycode representation of the given domain name or
|
||||
* email address.
|
||||
*/
|
||||
const toASCII = function(input) {
|
||||
return mapDomain(input, function(string) {
|
||||
return regexNonASCII.test(string)
|
||||
? 'xn--' + encode(string)
|
||||
: string;
|
||||
});
|
||||
};
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
/** Define the public API */
|
||||
const punycode = {
|
||||
/**
|
||||
* A string representing the current Punycode.js version number.
|
||||
* @memberOf punycode
|
||||
* @type String
|
||||
*/
|
||||
'version': '2.3.1',
|
||||
/**
|
||||
* An object of methods to convert from JavaScript's internal character
|
||||
* representation (UCS-2) to Unicode code points, and back.
|
||||
* @see <https://mathiasbynens.be/notes/javascript-encoding>
|
||||
* @memberOf punycode
|
||||
* @type Object
|
||||
*/
|
||||
'ucs2': {
|
||||
'decode': ucs2decode,
|
||||
'encode': ucs2encode
|
||||
},
|
||||
'decode': decode,
|
||||
'encode': encode,
|
||||
'toASCII': toASCII,
|
||||
'toUnicode': toUnicode
|
||||
};
|
||||
|
||||
export { ucs2decode, ucs2encode, decode, encode, toASCII, toUnicode };
|
||||
export default punycode;
|
||||
@@ -0,0 +1,3 @@
|
||||
import { URISchemeHandler } from "../uri";
|
||||
declare const handler: URISchemeHandler;
|
||||
export default handler;
|
||||
@@ -0,0 +1,200 @@
|
||||
export { A as AutomockedModule, b as AutospiedModule, a as ManualMockedModule, M as MockerRegistry, R as RedirectedModule } from './chunk-registry.js';
|
||||
|
||||
function mockObject(options, object, mockExports = {}) {
|
||||
const finalizers = new Array();
|
||||
const refs = new RefTracker();
|
||||
const define = (container, key, value) => {
|
||||
try {
|
||||
container[key] = value;
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
const createMock = (currentValue) => {
|
||||
if (!options.createMockInstance) {
|
||||
throw new Error("[@vitest/mocker] `createMockInstance` is not defined. This is a Vitest error. Please open a new issue with reproduction.");
|
||||
}
|
||||
const createMockInstance = options.createMockInstance;
|
||||
const prototypeMembers = currentValue.prototype ? collectFunctionProperties(currentValue.prototype) : [];
|
||||
return createMockInstance({
|
||||
name: currentValue.name,
|
||||
prototypeMembers,
|
||||
originalImplementation: options.type === "autospy" ? currentValue : undefined,
|
||||
keepMembersImplementation: options.type === "autospy"
|
||||
});
|
||||
};
|
||||
const mockPropertiesOf = (container, newContainer) => {
|
||||
const containerType = getType(container);
|
||||
const isModule = containerType === "Module" || !!container.__esModule;
|
||||
for (const { key: property, descriptor } of getAllMockableProperties(container, isModule, options.globalConstructors)) {
|
||||
// Modules define their exports as getters. We want to process those.
|
||||
if (!isModule && descriptor.get) {
|
||||
try {
|
||||
if (options.type === "autospy") {
|
||||
Object.defineProperty(newContainer, property, descriptor);
|
||||
} else {
|
||||
Object.defineProperty(newContainer, property, {
|
||||
configurable: descriptor.configurable,
|
||||
enumerable: descriptor.enumerable,
|
||||
get: () => {},
|
||||
set: descriptor.set ? () => {} : undefined
|
||||
});
|
||||
}
|
||||
} catch {}
|
||||
continue;
|
||||
}
|
||||
// Skip special read-only props, we don't want to mess with those.
|
||||
if (isReadonlyProp(container[property], property)) {
|
||||
continue;
|
||||
}
|
||||
const value = container[property];
|
||||
// Special handling of references we've seen before to prevent infinite
|
||||
// recursion in circular objects.
|
||||
const refId = refs.getId(value);
|
||||
if (refId !== undefined) {
|
||||
finalizers.push(() => define(newContainer, property, refs.getMockedValue(refId)));
|
||||
continue;
|
||||
}
|
||||
const type = getType(value);
|
||||
if (Array.isArray(value)) {
|
||||
if (options.type === "automock") {
|
||||
define(newContainer, property, []);
|
||||
} else {
|
||||
const array = value.map((value) => {
|
||||
if (value && typeof value === "object") {
|
||||
const newObject = {};
|
||||
mockPropertiesOf(value, newObject);
|
||||
return newObject;
|
||||
}
|
||||
if (typeof value === "function") {
|
||||
return createMock(value);
|
||||
}
|
||||
return value;
|
||||
});
|
||||
define(newContainer, property, array);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const isFunction = type.includes("Function") && typeof value === "function";
|
||||
if ((!isFunction || value._isMockFunction) && type !== "Object" && type !== "Module") {
|
||||
define(newContainer, property, value);
|
||||
continue;
|
||||
}
|
||||
if (options.type === "autospy" && type === "Module") {
|
||||
// Replace with clean object to recursively autospy exported module objects:
|
||||
// export * as ns from "./ns"
|
||||
// or
|
||||
// import * as ns from "./ns"
|
||||
// export { ns }
|
||||
const exports$1 = Object.create(null);
|
||||
Object.defineProperty(exports$1, Symbol.toStringTag, {
|
||||
value: "Module",
|
||||
configurable: true,
|
||||
writable: true
|
||||
});
|
||||
try {
|
||||
newContainer[property] = exports$1;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
} else if (!define(newContainer, property, isFunction || options.type === "autospy" ? value : {})) {
|
||||
continue;
|
||||
}
|
||||
if (isFunction) {
|
||||
const mock = createMock(newContainer[property]);
|
||||
newContainer[property] = mock;
|
||||
}
|
||||
refs.track(value, newContainer[property]);
|
||||
mockPropertiesOf(value, newContainer[property]);
|
||||
}
|
||||
};
|
||||
const mockedObject = mockExports;
|
||||
mockPropertiesOf(object, mockedObject);
|
||||
// Plug together refs
|
||||
for (const finalizer of finalizers) {
|
||||
finalizer();
|
||||
}
|
||||
return mockedObject;
|
||||
}
|
||||
class RefTracker {
|
||||
idMap = new Map();
|
||||
mockedValueMap = new Map();
|
||||
getId(value) {
|
||||
return this.idMap.get(value);
|
||||
}
|
||||
getMockedValue(id) {
|
||||
return this.mockedValueMap.get(id);
|
||||
}
|
||||
track(originalValue, mockedValue) {
|
||||
const newId = this.idMap.size;
|
||||
this.idMap.set(originalValue, newId);
|
||||
this.mockedValueMap.set(newId, mockedValue);
|
||||
return newId;
|
||||
}
|
||||
}
|
||||
function getType(value) {
|
||||
return Object.prototype.toString.apply(value).slice(8, -1);
|
||||
}
|
||||
function isReadonlyProp(object, prop) {
|
||||
if (prop === "arguments" || prop === "caller" || prop === "callee" || prop === "name" || prop === "length") {
|
||||
const typeName = getType(object);
|
||||
return typeName === "Function" || typeName === "AsyncFunction" || typeName === "GeneratorFunction" || typeName === "AsyncGeneratorFunction";
|
||||
}
|
||||
if (prop === "source" || prop === "global" || prop === "ignoreCase" || prop === "multiline") {
|
||||
return getType(object) === "RegExp";
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function getAllMockableProperties(obj, isModule, constructors) {
|
||||
const { Map, Object, Function, RegExp, Array } = constructors;
|
||||
const allProps = new Map();
|
||||
let curr = obj;
|
||||
do {
|
||||
// we don't need properties from these
|
||||
if (curr === Object.prototype || curr === Function.prototype || curr === RegExp.prototype) {
|
||||
break;
|
||||
}
|
||||
collectOwnProperties(curr, (key) => {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(curr, key);
|
||||
if (descriptor) {
|
||||
allProps.set(key, {
|
||||
key,
|
||||
descriptor
|
||||
});
|
||||
}
|
||||
});
|
||||
} while (curr = Object.getPrototypeOf(curr));
|
||||
// default is not specified in ownKeys, if module is interoped
|
||||
if (isModule && !allProps.has("default") && "default" in obj) {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(obj, "default");
|
||||
if (descriptor) {
|
||||
allProps.set("default", {
|
||||
key: "default",
|
||||
descriptor
|
||||
});
|
||||
}
|
||||
}
|
||||
return Array.from(allProps.values());
|
||||
}
|
||||
function collectOwnProperties(obj, collector) {
|
||||
const collect = typeof collector === "function" ? collector : (key) => collector.add(key);
|
||||
Object.getOwnPropertyNames(obj).forEach(collect);
|
||||
Object.getOwnPropertySymbols(obj).forEach(collect);
|
||||
}
|
||||
function collectFunctionProperties(prototype) {
|
||||
const properties = new Set();
|
||||
collectOwnProperties(prototype, (prop) => {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(prototype, prop);
|
||||
if (!descriptor || descriptor.get) {
|
||||
return;
|
||||
}
|
||||
const type = getType(descriptor.value);
|
||||
if (type.includes("Function") && !isReadonlyProp(descriptor.value, prop)) {
|
||||
properties.add(prop);
|
||||
}
|
||||
});
|
||||
return Array.from(properties);
|
||||
}
|
||||
|
||||
export { mockObject };
|
||||
@@ -0,0 +1,794 @@
|
||||
declare module "node:diagnostics_channel" {
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
/**
|
||||
* Check if there are active subscribers to the named channel. This is helpful if
|
||||
* the message you want to send might be expensive to prepare.
|
||||
*
|
||||
* This API is optional but helpful when trying to publish messages from very
|
||||
* performance-sensitive code.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* if (diagnostics_channel.hasSubscribers('my-channel')) {
|
||||
* // There are subscribers, prepare and publish message
|
||||
* }
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param name The channel name
|
||||
* @return If there are active subscribers
|
||||
*/
|
||||
function hasSubscribers(name: string | symbol): boolean;
|
||||
/**
|
||||
* This is the primary entry-point for anyone wanting to publish to a named
|
||||
* channel. It produces a channel object which is optimized to reduce overhead at
|
||||
* publish time as much as possible.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param name The channel name
|
||||
* @return The named channel object
|
||||
*/
|
||||
// eslint-disable-next-line @definitelytyped/no-unnecessary-generics
|
||||
function channel<ContextType = any, StoreType = ContextType>(
|
||||
name: string | symbol,
|
||||
): Channel<ContextType, StoreType>;
|
||||
type ChannelListener = (message: unknown, name: string | symbol) => void;
|
||||
/**
|
||||
* Register a message handler to subscribe to this channel. This message handler
|
||||
* will be run synchronously whenever a message is published to the channel. Any
|
||||
* errors thrown in the message handler will trigger an `'uncaughtException'`.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* diagnostics_channel.subscribe('my-channel', (message, name) => {
|
||||
* // Received data
|
||||
* });
|
||||
* ```
|
||||
* @since v18.7.0, v16.17.0
|
||||
* @param name The channel name
|
||||
* @param onMessage The handler to receive channel messages
|
||||
*/
|
||||
function subscribe(name: string | symbol, onMessage: ChannelListener): void;
|
||||
/**
|
||||
* Remove a message handler previously registered to this channel with {@link subscribe}.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* function onMessage(message, name) {
|
||||
* // Received data
|
||||
* }
|
||||
*
|
||||
* diagnostics_channel.subscribe('my-channel', onMessage);
|
||||
*
|
||||
* diagnostics_channel.unsubscribe('my-channel', onMessage);
|
||||
* ```
|
||||
* @since v18.7.0, v16.17.0
|
||||
* @param name The channel name
|
||||
* @param onMessage The previous subscribed handler to remove
|
||||
* @return `true` if the handler was found, `false` otherwise.
|
||||
*/
|
||||
function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean;
|
||||
/**
|
||||
* Creates a `TracingChannel` wrapper for the given `TracingChannel Channels`. If a name is given, the corresponding tracing
|
||||
* channels will be created in the form of `tracing:${name}:${eventType}` where `eventType` corresponds to the types of `TracingChannel Channels`.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channelsByName = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* // or...
|
||||
*
|
||||
* const channelsByCollection = diagnostics_channel.tracingChannel({
|
||||
* start: diagnostics_channel.channel('tracing:my-channel:start'),
|
||||
* end: diagnostics_channel.channel('tracing:my-channel:end'),
|
||||
* asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'),
|
||||
* asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'),
|
||||
* error: diagnostics_channel.channel('tracing:my-channel:error'),
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param nameOrChannels Channel name or object containing all the `TracingChannel Channels`
|
||||
* @return Collection of channels to trace with
|
||||
*/
|
||||
function tracingChannel<ContextType extends object = object, StoreType = ContextType>(
|
||||
nameOrChannels: string | TracingChannelCollection<ContextType, StoreType>,
|
||||
): TracingChannel<ContextType, StoreType>;
|
||||
/**
|
||||
* Creates a {@link BoundedChannel} wrapper for the given channels. If a name is
|
||||
* given, the corresponding channels will be created in the form of
|
||||
* `tracing:${name}:${eventType}` where `eventType` is `start` or `end`.
|
||||
*
|
||||
* A `BoundedChannel` is a simplified version of {@link TracingChannel} that only
|
||||
* traces synchronous operations. It only has `start` and `end` events, without
|
||||
* `asyncStart`, `asyncEnd`, or `error` events, making it suitable for tracing
|
||||
* operations that don't involve asynchronous continuations or error handling.
|
||||
*
|
||||
* ```js
|
||||
* import { boundedChannel, channel } from 'node:diagnostics_channel';
|
||||
*
|
||||
* const wc = boundedChannel('my-operation');
|
||||
*
|
||||
* // or...
|
||||
*
|
||||
* const wc2 = boundedChannel({
|
||||
* start: channel('tracing:my-operation:start'),
|
||||
* end: channel('tracing:my-operation:end'),
|
||||
* });
|
||||
* ```
|
||||
* @since v26.1.0
|
||||
* @experimental
|
||||
* @param nameOrChannels Channel name or
|
||||
* object containing all the [BoundedChannel Channels](https://nodejs.org/docs/latest-v26.x/api/diagnostics_channel.html#boundedchannel-channels)
|
||||
*/
|
||||
function boundedChannel<ContextType extends object = object, StoreType = ContextType>(
|
||||
nameOrChannels: string | BoundedChannelCollection<ContextType, StoreType>,
|
||||
): BoundedChannel<ContextType, StoreType>;
|
||||
/**
|
||||
* The class `Channel` represents an individual named channel within the data
|
||||
* pipeline. It is used to track subscribers and to publish messages when there
|
||||
* are subscribers present. It exists as a separate object to avoid channel
|
||||
* lookups at publish time, enabling very fast publish speeds and allowing
|
||||
* for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly
|
||||
* with `new Channel(name)` is not supported.
|
||||
* @since v15.1.0, v14.17.0
|
||||
*/
|
||||
class Channel<ContextType = any, StoreType = ContextType> {
|
||||
private constructor();
|
||||
readonly name: string | symbol;
|
||||
/**
|
||||
* Check if there are active subscribers to this channel. This is helpful if
|
||||
* the message you want to send might be expensive to prepare.
|
||||
*
|
||||
* This API is optional but helpful when trying to publish messages from very
|
||||
* performance-sensitive code.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* if (channel.hasSubscribers) {
|
||||
* // There are subscribers, prepare and publish message
|
||||
* }
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
*/
|
||||
readonly hasSubscribers: boolean;
|
||||
/**
|
||||
* Publish a message to any subscribers to the channel. This will trigger
|
||||
* message handlers synchronously so they will execute within the same context.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* channel.publish({
|
||||
* some: 'message',
|
||||
* });
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param message The message to send to the channel subscribers
|
||||
*/
|
||||
publish(message: unknown): void;
|
||||
/**
|
||||
* Register a message handler to subscribe to this channel. This message handler
|
||||
* will be run synchronously whenever a message is published to the channel. Any
|
||||
* errors thrown in the message handler will trigger an `'uncaughtException'`.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* channel.subscribe((message, name) => {
|
||||
* // Received data
|
||||
* });
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param onMessage The handler to receive channel messages
|
||||
*/
|
||||
subscribe(onMessage: ChannelListener): void;
|
||||
/**
|
||||
* Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* function onMessage(message, name) {
|
||||
* // Received data
|
||||
* }
|
||||
*
|
||||
* channel.subscribe(onMessage);
|
||||
*
|
||||
* channel.unsubscribe(onMessage);
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param onMessage The previous subscribed handler to remove
|
||||
* @return `true` if the handler was found, `false` otherwise.
|
||||
*/
|
||||
unsubscribe(onMessage: ChannelListener): void;
|
||||
/**
|
||||
* When `channel.runStores(context, ...)` is called, the given context data
|
||||
* will be applied to any store bound to the channel. If the store has already been
|
||||
* bound the previous `transform` function will be replaced with the new one.
|
||||
* The `transform` function may be omitted to set the given context data as the
|
||||
* context directly.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
* import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
*
|
||||
* const store = new AsyncLocalStorage();
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* channel.bindStore(store, (data) => {
|
||||
* return { data };
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param store The store to which to bind the context data
|
||||
* @param transform Transform context data before setting the store context
|
||||
*/
|
||||
bindStore(store: AsyncLocalStorage<StoreType>, transform?: (context: ContextType) => StoreType): void;
|
||||
/**
|
||||
* Remove a message handler previously registered to this channel with `channel.bindStore(store)`.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
* import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
*
|
||||
* const store = new AsyncLocalStorage();
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* channel.bindStore(store);
|
||||
* channel.unbindStore(store);
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param store The store to unbind from the channel.
|
||||
* @return `true` if the store was found, `false` otherwise.
|
||||
*/
|
||||
unbindStore(store: AsyncLocalStorage<StoreType>): boolean;
|
||||
/**
|
||||
* Applies the given data to any AsyncLocalStorage instances bound to the channel
|
||||
* for the duration of the given function, then publishes to the channel within
|
||||
* the scope of that data is applied to the stores.
|
||||
*
|
||||
* If a transform function was given to `channel.bindStore(store)` it will be
|
||||
* applied to transform the message data before it becomes the context value for
|
||||
* the store. The prior storage context is accessible from within the transform
|
||||
* function in cases where context linking is required.
|
||||
*
|
||||
* The context applied to the store should be accessible in any async code which
|
||||
* continues from execution which began during the given function, however
|
||||
* there are some situations in which `context loss` may occur.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
* import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
*
|
||||
* const store = new AsyncLocalStorage();
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* channel.bindStore(store, (message) => {
|
||||
* const parent = store.getStore();
|
||||
* return new Span(message, parent);
|
||||
* });
|
||||
* channel.runStores({ some: 'message' }, () => {
|
||||
* store.getStore(); // Span({ some: 'message' })
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param context Message to send to subscribers and bind to stores
|
||||
* @param fn Handler to run within the entered storage context
|
||||
* @param thisArg The receiver to be used for the function call.
|
||||
* @param args Optional arguments to pass to the function.
|
||||
*/
|
||||
runStores<ThisArg = any, Args extends any[] = any[], Result = any>(
|
||||
context: ContextType,
|
||||
fn: (this: ThisArg, ...args: Args) => Result,
|
||||
thisArg?: ThisArg,
|
||||
...args: Args
|
||||
): Result;
|
||||
/**
|
||||
* Creates a disposable scope that binds the given data to any AsyncLocalStorage
|
||||
* instances bound to the channel and publishes it to subscribers. The scope
|
||||
* automatically restores the previous storage contexts when disposed.
|
||||
*
|
||||
* This method enables the use of JavaScript's explicit resource management
|
||||
* (`using` syntax with `Symbol.dispose`) to manage store contexts without
|
||||
* closure wrapping.
|
||||
*
|
||||
* ```js
|
||||
* import { channel } from 'node:diagnostics_channel';
|
||||
* import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
*
|
||||
* const store = new AsyncLocalStorage();
|
||||
* const ch = channel('my-channel');
|
||||
*
|
||||
* ch.bindStore(store, (message) => {
|
||||
* return { ...message, timestamp: Date.now() };
|
||||
* });
|
||||
*
|
||||
* {
|
||||
* using scope = ch.withStoreScope({ request: 'data' });
|
||||
* // Store is entered, data is published
|
||||
* console.log(store.getStore()); // { request: 'data', timestamp: ... }
|
||||
* }
|
||||
* // Store is automatically restored on scope exit
|
||||
* ```
|
||||
* @since v26.1.0
|
||||
* @experimental
|
||||
*/
|
||||
withStoreScope(data: ContextType): RunStoresScope;
|
||||
}
|
||||
/**
|
||||
* The class `RunStoresScope` represents a disposable scope created by
|
||||
* `channel.withStoreScope(data)`. It manages the lifecycle of store
|
||||
* contexts and ensures they are properly restored when the scope exits.
|
||||
*
|
||||
* The scope must be used with the `using` syntax to ensure proper disposal.
|
||||
* @since v26.1.0
|
||||
* @experimental
|
||||
*/
|
||||
interface RunStoresScope extends Disposable {}
|
||||
interface TracingChannelSubscribers<ContextType extends object> {
|
||||
start: (message: ContextType) => void;
|
||||
end: (
|
||||
message: ContextType & {
|
||||
error?: unknown;
|
||||
result?: unknown;
|
||||
},
|
||||
) => void;
|
||||
asyncStart: (
|
||||
message: ContextType & {
|
||||
error?: unknown;
|
||||
result?: unknown;
|
||||
},
|
||||
) => void;
|
||||
asyncEnd: (
|
||||
message: ContextType & {
|
||||
error?: unknown;
|
||||
result?: unknown;
|
||||
},
|
||||
) => void;
|
||||
error: (
|
||||
message: ContextType & {
|
||||
error: unknown;
|
||||
},
|
||||
) => void;
|
||||
}
|
||||
interface TracingChannelCollection<ContextType extends object = object, StoreType = ContextType> {
|
||||
start: Channel<ContextType, StoreType>;
|
||||
end: Channel<ContextType, StoreType>;
|
||||
asyncStart: Channel<ContextType, StoreType>;
|
||||
asyncEnd: Channel<ContextType, StoreType>;
|
||||
error: Channel<ContextType, StoreType>;
|
||||
}
|
||||
/**
|
||||
* The class `TracingChannel` is a collection of `TracingChannel Channels` which
|
||||
* together express a single traceable action. It is used to formalize and
|
||||
* simplify the process of producing events for tracing application flow. {@link tracingChannel} is used to construct a `TracingChannel`. As with `Channel` it is recommended to create and reuse a
|
||||
* single `TracingChannel` at the top-level of the file rather than creating them
|
||||
* dynamically.
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
*/
|
||||
interface TracingChannel<ContextType extends object = object, StoreType = ContextType>
|
||||
extends TracingChannelCollection<ContextType, StoreType>
|
||||
{
|
||||
/**
|
||||
* Helper to subscribe a collection of functions to the corresponding channels.
|
||||
* This is the same as calling `channel.subscribe(onMessage)` on each channel
|
||||
* individually.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* channels.subscribe({
|
||||
* start(message) {
|
||||
* // Handle start message
|
||||
* },
|
||||
* end(message) {
|
||||
* // Handle end message
|
||||
* },
|
||||
* asyncStart(message) {
|
||||
* // Handle asyncStart message
|
||||
* },
|
||||
* asyncEnd(message) {
|
||||
* // Handle asyncEnd message
|
||||
* },
|
||||
* error(message) {
|
||||
* // Handle error message
|
||||
* },
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param subscribers Set of `TracingChannel Channels` subscribers
|
||||
*/
|
||||
subscribe(subscribers: NodeJS.PartialOptions<TracingChannelSubscribers<ContextType>>): void;
|
||||
/**
|
||||
* Helper to unsubscribe a collection of functions from the corresponding channels.
|
||||
* This is the same as calling `channel.unsubscribe(onMessage)` on each channel
|
||||
* individually.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* channels.unsubscribe({
|
||||
* start(message) {
|
||||
* // Handle start message
|
||||
* },
|
||||
* end(message) {
|
||||
* // Handle end message
|
||||
* },
|
||||
* asyncStart(message) {
|
||||
* // Handle asyncStart message
|
||||
* },
|
||||
* asyncEnd(message) {
|
||||
* // Handle asyncEnd message
|
||||
* },
|
||||
* error(message) {
|
||||
* // Handle error message
|
||||
* },
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param subscribers Set of `TracingChannel Channels` subscribers
|
||||
* @return `true` if all handlers were successfully unsubscribed, and `false` otherwise.
|
||||
*/
|
||||
unsubscribe(subscribers: NodeJS.PartialOptions<TracingChannelSubscribers<ContextType>>): void;
|
||||
/**
|
||||
* Trace a synchronous function call. This will always produce a `start event` and `end event` around the execution and may produce an `error event` if the given function throws an error.
|
||||
* This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all
|
||||
* events should have any bound stores set to match this trace context.
|
||||
*
|
||||
* To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions
|
||||
* which are added after the trace begins will not receive future events from that trace, only future traces will be seen.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* channels.traceSync(() => {
|
||||
* // Do something
|
||||
* }, {
|
||||
* some: 'thing',
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param fn Function to wrap a trace around
|
||||
* @param context Shared object to correlate events through
|
||||
* @param thisArg The receiver to be used for the function call
|
||||
* @param args Optional arguments to pass to the function
|
||||
* @return The return value of the given function
|
||||
*/
|
||||
traceSync<ThisArg = any, Args extends any[] = any[], Result = any>(
|
||||
fn: (this: ThisArg, ...args: Args) => Result,
|
||||
context?: ContextType,
|
||||
thisArg?: ThisArg,
|
||||
...args: Args
|
||||
): Result;
|
||||
/**
|
||||
* Trace an asynchronous function call which returns a `Promise` or
|
||||
* [thenable object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables). This will always produce a [`start` event](https://nodejs.org/docs/latest-v26.x/api/diagnostics_channel.html#startevent) and
|
||||
* [`end` event](https://nodejs.org/docs/latest-v26.x/api/diagnostics_channel.html#endevent) around the synchronous portion of the function execution, and
|
||||
* will produce an [`asyncStart` event](https://nodejs.org/docs/latest-v26.x/api/diagnostics_channel.html#asyncstartevent) and [`asyncEnd` event](https://nodejs.org/docs/latest-v26.x/api/diagnostics_channel.html#asyncendevent) when the
|
||||
* returned promise is resolved or rejected. It may also produce an
|
||||
* [`error` event](https://nodejs.org/docs/latest-v26.x/api/diagnostics_channel.html#errorevent) if the given function throws an error or the returned promise
|
||||
* is rejected. This will run the given function using
|
||||
* [`channel.runStores(context, ...)`](https://nodejs.org/docs/latest-v26.x/api/diagnostics_channel.html##channelrunstorescontext-fn-thisarg-args) on the `start` channel which ensures all
|
||||
* events should have any bound stores set to match this trace context.
|
||||
*
|
||||
* If the value returned by `fn` is not a Promise or thenable, then it will be
|
||||
* returned with a warning, and no `asyncStart` or `asyncEnd` events will be
|
||||
* produced.
|
||||
*
|
||||
* To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions
|
||||
* which are added after the trace begins will not receive future events from that trace, only future traces will be seen.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* channels.tracePromise(async () => {
|
||||
* // Do something
|
||||
* }, {
|
||||
* some: 'thing',
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param fn Function to wrap a trace around
|
||||
* @param context Shared object to correlate trace events through
|
||||
* @param thisArg The receiver to be used for the function call
|
||||
* @param args Optional arguments to pass to the function
|
||||
* @returns The return value of the given function, or the result of
|
||||
* calling `.then(...)` on the return value if the tracing channel has active
|
||||
* subscribers. If the return value is not a Promise or thenable, then
|
||||
* it is returned as-is and a warning is emitted.
|
||||
*/
|
||||
tracePromise<ThisArg = any, Args extends any[] = any[], Result extends PromiseLike<unknown> = any>(
|
||||
fn: (this: ThisArg, ...args: Args) => Result,
|
||||
context?: ContextType,
|
||||
thisArg?: ThisArg,
|
||||
...args: Args
|
||||
): Result;
|
||||
/**
|
||||
* Trace a callback-receiving function call. This will always produce a `start event` and `end event` around the synchronous portion of the
|
||||
* function execution, and will produce a `asyncStart event` and `asyncEnd event` around the callback execution. It may also produce an `error event` if the given function throws an error or
|
||||
* the returned
|
||||
* promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all
|
||||
* events should have any bound stores set to match this trace context.
|
||||
*
|
||||
* The `position` will be -1 by default to indicate the final argument should
|
||||
* be used as the callback.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* channels.traceCallback((arg1, callback) => {
|
||||
* // Do something
|
||||
* callback(null, 'result');
|
||||
* }, 1, {
|
||||
* some: 'thing',
|
||||
* }, thisArg, arg1, callback);
|
||||
* ```
|
||||
*
|
||||
* The callback will also be run with `channel.runStores(context, ...)` which
|
||||
* enables context loss recovery in some cases.
|
||||
*
|
||||
* To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions
|
||||
* which are added after the trace begins will not receive future events from that trace, only future traces will be seen.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
* import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
* const myStore = new AsyncLocalStorage();
|
||||
*
|
||||
* // The start channel sets the initial store data to something
|
||||
* // and stores that store data value on the trace context object
|
||||
* channels.start.bindStore(myStore, (data) => {
|
||||
* const span = new Span(data);
|
||||
* data.span = span;
|
||||
* return span;
|
||||
* });
|
||||
*
|
||||
* // Then asyncStart can restore from that data it stored previously
|
||||
* channels.asyncStart.bindStore(myStore, (data) => {
|
||||
* return data.span;
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param fn callback using function to wrap a trace around
|
||||
* @param position Zero-indexed argument position of expected callback
|
||||
* @param context Shared object to correlate trace events through
|
||||
* @param thisArg The receiver to be used for the function call
|
||||
* @param args Optional arguments to pass to the function
|
||||
* @return The return value of the given function
|
||||
*/
|
||||
traceCallback<ThisArg = any, Args extends any[] = any[], Result = any>(
|
||||
fn: (this: ThisArg, ...args: Args) => Result,
|
||||
position?: number,
|
||||
context?: ContextType,
|
||||
thisArg?: ThisArg,
|
||||
...args: Args
|
||||
): Result;
|
||||
/**
|
||||
* `true` if any of the individual channels has a subscriber, `false` if not.
|
||||
*
|
||||
* This is a helper method available on a {@link TracingChannel} instance to check
|
||||
* if any of the [TracingChannel Channels](https://nodejs.org/api/diagnostics_channel.html#tracingchannel-channels) have subscribers.
|
||||
* A `true` is returned if any of them have at least one subscriber, a `false` is returned otherwise.
|
||||
*
|
||||
* ```js
|
||||
* const diagnostics_channel = require('node:diagnostics_channel');
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* if (channels.hasSubscribers) {
|
||||
* // Do something
|
||||
* }
|
||||
* ```
|
||||
* @since v22.0.0, v20.13.0
|
||||
*/
|
||||
readonly hasSubscribers: boolean;
|
||||
}
|
||||
interface BoundedChannelSubscribers<ContextType extends object> {
|
||||
start: (message: ContextType) => void;
|
||||
end: (message: ContextType) => void;
|
||||
}
|
||||
interface BoundedChannelCollection<ContextType extends object = object, StoreType = ContextType> {
|
||||
start: Channel<ContextType, StoreType>;
|
||||
end: Channel<ContextType, StoreType>;
|
||||
}
|
||||
/**
|
||||
* The class `BoundedChannel` is a simplified version of {@link TracingChannel} that
|
||||
* only traces synchronous operations. It consists of two channels (`start` and
|
||||
* `end`) instead of five, omitting the `asyncStart`, `asyncEnd`, and `error`
|
||||
* events. This makes it suitable for tracing operations that don't involve
|
||||
* asynchronous continuations or error handling.
|
||||
*
|
||||
* Like `TracingChannel`, it is recommended to create and reuse a single
|
||||
* `BoundedChannel` at the top-level of the file rather than creating them
|
||||
* dynamically.
|
||||
* @since v26.1.0
|
||||
* @experimental
|
||||
*/
|
||||
interface BoundedChannel<ContextType extends object = object, StoreType = ContextType>
|
||||
extends BoundedChannelCollection<ContextType, StoreType>
|
||||
{
|
||||
/**
|
||||
* Check if any of the `start` or `end` channels have subscribers.
|
||||
*
|
||||
* ```js
|
||||
* import { boundedChannel } from 'node:diagnostics_channel';
|
||||
*
|
||||
* const wc = boundedChannel('my-operation');
|
||||
*
|
||||
* if (wc.hasSubscribers) {
|
||||
* // There are subscribers, perform traced operation
|
||||
* }
|
||||
* ```
|
||||
* @since v26.1.0
|
||||
*/
|
||||
readonly hasSubscribers: boolean;
|
||||
/**
|
||||
* Subscribe to the bounded channel events. This is equivalent to calling
|
||||
* [`channel.subscribe(onMessage)`][] on each channel individually.
|
||||
*
|
||||
* ```mjs
|
||||
* import { boundedChannel } from 'node:diagnostics_channel';
|
||||
*
|
||||
* const wc = boundedChannel('my-operation');
|
||||
*
|
||||
* wc.subscribe({
|
||||
* start(message) {
|
||||
* // Handle start
|
||||
* },
|
||||
* end(message) {
|
||||
* // Handle end
|
||||
* },
|
||||
* });
|
||||
* ```
|
||||
* @since v26.1.0
|
||||
* @param handlers Set of channel subscribers
|
||||
*/
|
||||
subscribe(handlers: NodeJS.PartialOptions<BoundedChannelSubscribers<ContextType>>): void;
|
||||
/**
|
||||
* Unsubscribe from the bounded channel events. This is equivalent to calling
|
||||
* [`channel.unsubscribe(onMessage)`][] on each channel individually.
|
||||
*
|
||||
* ```js
|
||||
* import { boundedChannel } from 'node:diagnostics_channel';
|
||||
*
|
||||
* const wc = boundedChannel('my-operation');
|
||||
*
|
||||
* const handlers = {
|
||||
* start(message) {},
|
||||
* end(message) {},
|
||||
* };
|
||||
*
|
||||
* wc.subscribe(handlers);
|
||||
* wc.unsubscribe(handlers);
|
||||
* ```
|
||||
* @since v26.1.0
|
||||
* @param handlers Set of channel subscribers
|
||||
* @returns `true` if all handlers were successfully unsubscribed,
|
||||
* `false` otherwise.
|
||||
*/
|
||||
unsubscribe(handlers: NodeJS.PartialOptions<BoundedChannelSubscribers<ContextType>>): boolean;
|
||||
/**
|
||||
* Trace a synchronous function call. This will produce a `start` event and `end`
|
||||
* event around the execution. This runs the given function using
|
||||
* [`channel.runStores(context, ...)`][] on the `start` channel which ensures all
|
||||
* events have any bound stores set to match this trace context.
|
||||
*
|
||||
* ```js
|
||||
* import { boundedChannel } from 'node:diagnostics_channel';
|
||||
*
|
||||
* const wc = boundedChannel('my-operation');
|
||||
*
|
||||
* const result = wc.run({ operationId: '123' }, () => {
|
||||
* // Perform operation
|
||||
* return 42;
|
||||
* });
|
||||
* ```
|
||||
* @since v26.1.0
|
||||
* @param context Shared object to correlate events through
|
||||
* @param fn Function to wrap a trace around
|
||||
* @param thisArg The receiver to be used for the function call
|
||||
* @param args Optional arguments to pass to the function
|
||||
* @returns The return value of the given function
|
||||
*/
|
||||
run<ThisArg = any, Args extends any[] = any[], Result = any>(
|
||||
fn: (this: ThisArg, ...args: Args) => Result,
|
||||
context?: ContextType,
|
||||
thisArg?: ThisArg,
|
||||
...args: Args
|
||||
): Result;
|
||||
/**
|
||||
* Create a disposable scope for tracing a synchronous operation using JavaScript's
|
||||
* explicit resource management (`using` syntax). The scope automatically publishes
|
||||
* `start` and `end` events, enters bound stores, and handles cleanup when disposed.
|
||||
*
|
||||
* ```js
|
||||
* import { boundedChannel } from 'node:diagnostics_channel';
|
||||
*
|
||||
* const wc = boundedChannel('my-operation');
|
||||
*
|
||||
* const context = { operationId: '123' };
|
||||
* {
|
||||
* using scope = wc.withScope(context);
|
||||
* // Stores are entered, start event is published
|
||||
*
|
||||
* // Perform work and set result on context
|
||||
* context.result = 42;
|
||||
* }
|
||||
* // End event is published, stores are restored automatically
|
||||
* ```
|
||||
* @since v26.1.0
|
||||
* @param context Shared object to correlate events through
|
||||
* @returns Disposable scope object
|
||||
*/
|
||||
withScope(context: ContextType): BoundedChannelScope;
|
||||
}
|
||||
/**
|
||||
* The class `BoundedChannelScope` represents a disposable scope created by
|
||||
* `boundedChannel.withScope(context)`. It manages the lifecycle of a traced
|
||||
* operation, automatically publishing events and managing store contexts.
|
||||
*
|
||||
* The scope must be used with the `using` syntax to ensure proper disposal.
|
||||
*
|
||||
* ```js
|
||||
* import { boundedChannel } from 'node:diagnostics_channel';
|
||||
*
|
||||
* const wc = boundedChannel('my-operation');
|
||||
*
|
||||
* const context = {};
|
||||
* {
|
||||
* using scope = wc.withScope(context);
|
||||
* // Start event is published, stores are entered
|
||||
* context.result = performOperation();
|
||||
* // End event is automatically published at end of block
|
||||
* }
|
||||
* ```
|
||||
* @since v26.1.0
|
||||
* @experimental
|
||||
*/
|
||||
interface BoundedChannelScope extends Disposable {}
|
||||
}
|
||||
declare module "diagnostics_channel" {
|
||||
export * from "node:diagnostics_channel";
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
"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.es2021_weakref = void 0;
|
||||
const base_config_1 = require("./base-config");
|
||||
const es2015_symbol_wellknown_1 = require("./es2015.symbol.wellknown");
|
||||
exports.es2021_weakref = {
|
||||
libs: [es2015_symbol_wellknown_1.es2015_symbol_wellknown],
|
||||
variables: [
|
||||
['WeakRef', base_config_1.TYPE_VALUE],
|
||||
['WeakRefConstructor', base_config_1.TYPE],
|
||||
['FinalizationRegistry', base_config_1.TYPE_VALUE],
|
||||
['FinalizationRegistryConstructor', base_config_1.TYPE],
|
||||
],
|
||||
};
|
||||
Reference in New Issue
Block a user