WIP: bootstrap and partial real Solana watcher implementation
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
import type {
|
||||
ClassicConfig,
|
||||
FlatConfig,
|
||||
} from '@typescript-eslint/utils/ts-eslint';
|
||||
|
||||
import type rules from './rules';
|
||||
|
||||
declare const cjsExport: {
|
||||
configs: Record<string, ClassicConfig.Config>;
|
||||
meta: FlatConfig.PluginMeta;
|
||||
rules: typeof rules;
|
||||
};
|
||||
export = cjsExport;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,20 @@
|
||||
"use strict";
|
||||
|
||||
function _defineProperties(target, props) {
|
||||
for (var i = 0; i < props.length; i++) {
|
||||
var descriptor = props[i];
|
||||
descriptor.enumerable = descriptor.enumerable || false;
|
||||
descriptor.configurable = true;
|
||||
|
||||
if ("value" in descriptor) descriptor.writable = true;
|
||||
|
||||
Object.defineProperty(target, descriptor.key, descriptor);
|
||||
}
|
||||
}
|
||||
function _create_class(Constructor, protoProps, staticProps) {
|
||||
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
|
||||
if (staticProps) _defineProperties(Constructor, staticProps);
|
||||
|
||||
return Constructor;
|
||||
}
|
||||
exports._ = _create_class;
|
||||
@@ -0,0 +1,428 @@
|
||||
# Commander.js
|
||||
|
||||
|
||||
[](http://travis-ci.org/tj/commander.js)
|
||||
[](https://www.npmjs.org/package/commander)
|
||||
[](https://npmcharts.com/compare/commander?minimal=true)
|
||||
[](https://packagephobia.now.sh/result?p=commander)
|
||||
[](https://gitter.im/tj/commander.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander).
|
||||
[API documentation](http://tj.github.com/commander.js/)
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
$ npm install commander
|
||||
|
||||
## Option parsing
|
||||
|
||||
Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.
|
||||
|
||||
```js
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var program = require('commander');
|
||||
|
||||
program
|
||||
.version('0.1.0')
|
||||
.option('-p, --peppers', 'Add peppers')
|
||||
.option('-P, --pineapple', 'Add pineapple')
|
||||
.option('-b, --bbq-sauce', 'Add bbq sauce')
|
||||
.option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
|
||||
.parse(process.argv);
|
||||
|
||||
console.log('you ordered a pizza with:');
|
||||
if (program.peppers) console.log(' - peppers');
|
||||
if (program.pineapple) console.log(' - pineapple');
|
||||
if (program.bbqSauce) console.log(' - bbq');
|
||||
console.log(' - %s cheese', program.cheese);
|
||||
```
|
||||
|
||||
Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc.
|
||||
|
||||
Note that multi-word options starting with `--no` prefix negate the boolean value of the following word. For example, `--no-sauce` sets the value of `program.sauce` to false.
|
||||
|
||||
```js
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var program = require('commander');
|
||||
|
||||
program
|
||||
.option('--no-sauce', 'Remove sauce')
|
||||
.parse(process.argv);
|
||||
|
||||
console.log('you ordered a pizza');
|
||||
if (program.sauce) console.log(' with sauce');
|
||||
else console.log(' without sauce');
|
||||
```
|
||||
|
||||
To get string arguments from options you will need to use angle brackets <> for required inputs or square brackets [] for optional inputs.
|
||||
|
||||
e.g. ```.option('-m --myarg [myVar]', 'my super cool description')```
|
||||
|
||||
Then to access the input if it was passed in.
|
||||
|
||||
e.g. ```var myInput = program.myarg```
|
||||
|
||||
**NOTE**: If you pass a argument without using brackets the example above will return true and not the value passed in.
|
||||
|
||||
|
||||
## Version option
|
||||
|
||||
Calling the `version` implicitly adds the `-V` and `--version` options to the command.
|
||||
When either of these options is present, the command prints the version number and exits.
|
||||
|
||||
$ ./examples/pizza -V
|
||||
0.0.1
|
||||
|
||||
If you want your program to respond to the `-v` option instead of the `-V` option, simply pass custom flags to the `version` method using the same syntax as the `option` method.
|
||||
|
||||
```js
|
||||
program
|
||||
.version('0.0.1', '-v, --version')
|
||||
```
|
||||
|
||||
The version flags can be named anything, but the long option is required.
|
||||
|
||||
## Command-specific options
|
||||
|
||||
You can attach options to a command.
|
||||
|
||||
```js
|
||||
#!/usr/bin/env node
|
||||
|
||||
var program = require('commander');
|
||||
|
||||
program
|
||||
.command('rm <dir>')
|
||||
.option('-r, --recursive', 'Remove recursively')
|
||||
.action(function (dir, cmd) {
|
||||
console.log('remove ' + dir + (cmd.recursive ? ' recursively' : ''))
|
||||
})
|
||||
|
||||
program.parse(process.argv)
|
||||
```
|
||||
|
||||
A command's options are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated.
|
||||
|
||||
## Coercion
|
||||
|
||||
```js
|
||||
function range(val) {
|
||||
return val.split('..').map(Number);
|
||||
}
|
||||
|
||||
function list(val) {
|
||||
return val.split(',');
|
||||
}
|
||||
|
||||
function collect(val, memo) {
|
||||
memo.push(val);
|
||||
return memo;
|
||||
}
|
||||
|
||||
function increaseVerbosity(v, total) {
|
||||
return total + 1;
|
||||
}
|
||||
|
||||
program
|
||||
.version('0.1.0')
|
||||
.usage('[options] <file ...>')
|
||||
.option('-i, --integer <n>', 'An integer argument', parseInt)
|
||||
.option('-f, --float <n>', 'A float argument', parseFloat)
|
||||
.option('-r, --range <a>..<b>', 'A range', range)
|
||||
.option('-l, --list <items>', 'A list', list)
|
||||
.option('-o, --optional [value]', 'An optional value')
|
||||
.option('-c, --collect [value]', 'A repeatable value', collect, [])
|
||||
.option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)
|
||||
.parse(process.argv);
|
||||
|
||||
console.log(' int: %j', program.integer);
|
||||
console.log(' float: %j', program.float);
|
||||
console.log(' optional: %j', program.optional);
|
||||
program.range = program.range || [];
|
||||
console.log(' range: %j..%j', program.range[0], program.range[1]);
|
||||
console.log(' list: %j', program.list);
|
||||
console.log(' collect: %j', program.collect);
|
||||
console.log(' verbosity: %j', program.verbose);
|
||||
console.log(' args: %j', program.args);
|
||||
```
|
||||
|
||||
## Regular Expression
|
||||
```js
|
||||
program
|
||||
.version('0.1.0')
|
||||
.option('-s --size <size>', 'Pizza size', /^(large|medium|small)$/i, 'medium')
|
||||
.option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i)
|
||||
.parse(process.argv);
|
||||
|
||||
console.log(' size: %j', program.size);
|
||||
console.log(' drink: %j', program.drink);
|
||||
```
|
||||
|
||||
## Variadic arguments
|
||||
|
||||
The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to
|
||||
append `...` to the argument name. Here is an example:
|
||||
|
||||
```js
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var program = require('commander');
|
||||
|
||||
program
|
||||
.version('0.1.0')
|
||||
.command('rmdir <dir> [otherDirs...]')
|
||||
.action(function (dir, otherDirs) {
|
||||
console.log('rmdir %s', dir);
|
||||
if (otherDirs) {
|
||||
otherDirs.forEach(function (oDir) {
|
||||
console.log('rmdir %s', oDir);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
program.parse(process.argv);
|
||||
```
|
||||
|
||||
An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed
|
||||
to your action as demonstrated above.
|
||||
|
||||
## Specify the argument syntax
|
||||
|
||||
```js
|
||||
#!/usr/bin/env node
|
||||
|
||||
var program = require('commander');
|
||||
|
||||
program
|
||||
.version('0.1.0')
|
||||
.arguments('<cmd> [env]')
|
||||
.action(function (cmd, env) {
|
||||
cmdValue = cmd;
|
||||
envValue = env;
|
||||
});
|
||||
|
||||
program.parse(process.argv);
|
||||
|
||||
if (typeof cmdValue === 'undefined') {
|
||||
console.error('no command given!');
|
||||
process.exit(1);
|
||||
}
|
||||
console.log('command:', cmdValue);
|
||||
console.log('environment:', envValue || "no environment given");
|
||||
```
|
||||
Angled brackets (e.g. `<cmd>`) indicate required input. Square brackets (e.g. `[env]`) indicate optional input.
|
||||
|
||||
## Git-style sub-commands
|
||||
|
||||
```js
|
||||
// file: ./examples/pm
|
||||
var program = require('commander');
|
||||
|
||||
program
|
||||
.version('0.1.0')
|
||||
.command('install [name]', 'install one or more packages')
|
||||
.command('search [query]', 'search with optional query')
|
||||
.command('list', 'list packages installed', {isDefault: true})
|
||||
.parse(process.argv);
|
||||
```
|
||||
|
||||
When `.command()` is invoked with a description argument, no `.action(callback)` should be called to handle sub-commands, otherwise there will be an error. This tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools.
|
||||
The commander will try to search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-command`, like `pm-install`, `pm-search`.
|
||||
|
||||
Options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the subcommand from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified.
|
||||
|
||||
If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
|
||||
|
||||
### `--harmony`
|
||||
|
||||
You can enable `--harmony` option in two ways:
|
||||
* Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. Note some os version don’t support this pattern.
|
||||
* Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process.
|
||||
|
||||
## Automated --help
|
||||
|
||||
The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:
|
||||
|
||||
```
|
||||
$ ./examples/pizza --help
|
||||
Usage: pizza [options]
|
||||
|
||||
An application for pizzas ordering
|
||||
|
||||
Options:
|
||||
-h, --help output usage information
|
||||
-V, --version output the version number
|
||||
-p, --peppers Add peppers
|
||||
-P, --pineapple Add pineapple
|
||||
-b, --bbq Add bbq sauce
|
||||
-c, --cheese <type> Add the specified type of cheese [marble]
|
||||
-C, --no-cheese You do not want any cheese
|
||||
```
|
||||
|
||||
## Custom help
|
||||
|
||||
You can display arbitrary `-h, --help` information
|
||||
by listening for "--help". Commander will automatically
|
||||
exit once you are done so that the remainder of your program
|
||||
does not execute causing undesired behaviors, for example
|
||||
in the following executable "stuff" will not output when
|
||||
`--help` is used.
|
||||
|
||||
```js
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
var program = require('commander');
|
||||
|
||||
program
|
||||
.version('0.1.0')
|
||||
.option('-f, --foo', 'enable some foo')
|
||||
.option('-b, --bar', 'enable some bar')
|
||||
.option('-B, --baz', 'enable some baz');
|
||||
|
||||
// must be before .parse() since
|
||||
// node's emit() is immediate
|
||||
|
||||
program.on('--help', function(){
|
||||
console.log('')
|
||||
console.log('Examples:');
|
||||
console.log(' $ custom-help --help');
|
||||
console.log(' $ custom-help -h');
|
||||
});
|
||||
|
||||
program.parse(process.argv);
|
||||
|
||||
console.log('stuff');
|
||||
```
|
||||
|
||||
Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run:
|
||||
|
||||
```
|
||||
Usage: custom-help [options]
|
||||
|
||||
Options:
|
||||
-h, --help output usage information
|
||||
-V, --version output the version number
|
||||
-f, --foo enable some foo
|
||||
-b, --bar enable some bar
|
||||
-B, --baz enable some baz
|
||||
|
||||
Examples:
|
||||
$ custom-help --help
|
||||
$ custom-help -h
|
||||
```
|
||||
|
||||
## .outputHelp(cb)
|
||||
|
||||
Output help information without exiting.
|
||||
Optional callback cb allows post-processing of help text before it is displayed.
|
||||
|
||||
If you want to display help by default (e.g. if no command was provided), you can use something like:
|
||||
|
||||
```js
|
||||
var program = require('commander');
|
||||
var colors = require('colors');
|
||||
|
||||
program
|
||||
.version('0.1.0')
|
||||
.command('getstream [url]', 'get stream URL')
|
||||
.parse(process.argv);
|
||||
|
||||
if (!process.argv.slice(2).length) {
|
||||
program.outputHelp(make_red);
|
||||
}
|
||||
|
||||
function make_red(txt) {
|
||||
return colors.red(txt); //display the help text in red on the console
|
||||
}
|
||||
```
|
||||
|
||||
## .help(cb)
|
||||
|
||||
Output help information and exit immediately.
|
||||
Optional callback cb allows post-processing of help text before it is displayed.
|
||||
|
||||
|
||||
## Custom event listeners
|
||||
You can execute custom actions by listening to command and option events.
|
||||
|
||||
```js
|
||||
program.on('option:verbose', function () {
|
||||
process.env.VERBOSE = this.verbose;
|
||||
});
|
||||
|
||||
// error on unknown commands
|
||||
program.on('command:*', function () {
|
||||
console.error('Invalid command: %s\nSee --help for a list of available commands.', program.args.join(' '));
|
||||
process.exit(1);
|
||||
});
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
```js
|
||||
var program = require('commander');
|
||||
|
||||
program
|
||||
.version('0.1.0')
|
||||
.option('-C, --chdir <path>', 'change the working directory')
|
||||
.option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
|
||||
.option('-T, --no-tests', 'ignore test hook');
|
||||
|
||||
program
|
||||
.command('setup [env]')
|
||||
.description('run setup commands for all envs')
|
||||
.option("-s, --setup_mode [mode]", "Which setup mode to use")
|
||||
.action(function(env, options){
|
||||
var mode = options.setup_mode || "normal";
|
||||
env = env || 'all';
|
||||
console.log('setup for %s env(s) with %s mode', env, mode);
|
||||
});
|
||||
|
||||
program
|
||||
.command('exec <cmd>')
|
||||
.alias('ex')
|
||||
.description('execute the given remote cmd')
|
||||
.option("-e, --exec_mode <mode>", "Which exec mode to use")
|
||||
.action(function(cmd, options){
|
||||
console.log('exec "%s" using %s mode', cmd, options.exec_mode);
|
||||
}).on('--help', function() {
|
||||
console.log('');
|
||||
console.log('Examples:');
|
||||
console.log('');
|
||||
console.log(' $ deploy exec sequential');
|
||||
console.log(' $ deploy exec async');
|
||||
});
|
||||
|
||||
program
|
||||
.command('*')
|
||||
.action(function(env){
|
||||
console.log('deploying "%s"', env);
|
||||
});
|
||||
|
||||
program.parse(process.argv);
|
||||
```
|
||||
|
||||
More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
|
||||
|
||||
## License
|
||||
|
||||
[MIT](https://github.com/tj/commander.js/blob/master/LICENSE)
|
||||
@@ -0,0 +1,33 @@
|
||||
// Returns a wrapper function that returns a wrapped callback
|
||||
// The wrapper function should do some stuff, and return a
|
||||
// presumably different callback function.
|
||||
// This makes sure that own properties are retained, so that
|
||||
// decorations and such are not lost along the way.
|
||||
module.exports = wrappy
|
||||
function wrappy (fn, cb) {
|
||||
if (fn && cb) return wrappy(fn)(cb)
|
||||
|
||||
if (typeof fn !== 'function')
|
||||
throw new TypeError('need wrapper function')
|
||||
|
||||
Object.keys(fn).forEach(function (k) {
|
||||
wrapper[k] = fn[k]
|
||||
})
|
||||
|
||||
return wrapper
|
||||
|
||||
function wrapper() {
|
||||
var args = new Array(arguments.length)
|
||||
for (var i = 0; i < args.length; i++) {
|
||||
args[i] = arguments[i]
|
||||
}
|
||||
var ret = fn.apply(this, args)
|
||||
var cb = args[args.length-1]
|
||||
if (typeof ret === 'function' && ret !== cb) {
|
||||
Object.keys(cb).forEach(function (k) {
|
||||
ret[k] = cb[k]
|
||||
})
|
||||
}
|
||||
return ret
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
"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.es2020_string = void 0;
|
||||
const base_config_1 = require("./base-config");
|
||||
const es2015_iterable_1 = require("./es2015.iterable");
|
||||
const es2020_intl_1 = require("./es2020.intl");
|
||||
const es2020_symbol_wellknown_1 = require("./es2020.symbol.wellknown");
|
||||
exports.es2020_string = {
|
||||
libs: [es2015_iterable_1.es2015_iterable, es2020_intl_1.es2020_intl, es2020_symbol_wellknown_1.es2020_symbol_wellknown],
|
||||
variables: [['String', base_config_1.TYPE]],
|
||||
};
|
||||
@@ -0,0 +1,270 @@
|
||||
/**
|
||||
* @fileoverview Rule to replace assignment expressions with operator assignment
|
||||
* @author Brandon Mills
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Checks whether an operator is commutative and has an operator assignment
|
||||
* shorthand form.
|
||||
* @param {string} operator Operator to check.
|
||||
* @returns {boolean} True if the operator is commutative and has a
|
||||
* shorthand form.
|
||||
*/
|
||||
function isCommutativeOperatorWithShorthand(operator) {
|
||||
return ["*", "&", "^", "|"].includes(operator);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether an operator is not commutative and has an operator assignment
|
||||
* shorthand form.
|
||||
* @param {string} operator Operator to check.
|
||||
* @returns {boolean} True if the operator is not commutative and has
|
||||
* a shorthand form.
|
||||
*/
|
||||
function isNonCommutativeOperatorWithShorthand(operator) {
|
||||
return ["+", "-", "/", "%", "<<", ">>", ">>>", "**"].includes(operator);
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Determines if the left side of a node can be safely fixed (i.e. if it activates the same getters/setters and)
|
||||
* toString calls regardless of whether assignment shorthand is used)
|
||||
* @param {ASTNode} node The node on the left side of the expression
|
||||
* @returns {boolean} `true` if the node can be fixed
|
||||
*/
|
||||
function canBeFixed(node) {
|
||||
return (
|
||||
node.type === "Identifier" ||
|
||||
(node.type === "MemberExpression" &&
|
||||
(node.object.type === "Identifier" ||
|
||||
node.object.type === "ThisExpression") &&
|
||||
(!node.computed || node.property.type === "Literal"))
|
||||
);
|
||||
}
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "suggestion",
|
||||
|
||||
defaultOptions: ["always"],
|
||||
|
||||
docs: {
|
||||
description:
|
||||
"Require or disallow assignment operator shorthand where possible",
|
||||
recommended: false,
|
||||
frozen: true,
|
||||
url: "https://eslint.org/docs/latest/rules/operator-assignment",
|
||||
},
|
||||
|
||||
schema: [
|
||||
{
|
||||
enum: ["always", "never"],
|
||||
},
|
||||
],
|
||||
|
||||
fixable: "code",
|
||||
messages: {
|
||||
replaced:
|
||||
"Assignment (=) can be replaced with operator assignment ({{operator}}).",
|
||||
unexpected:
|
||||
"Unexpected operator assignment ({{operator}}) shorthand.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const never = context.options[0] === "never";
|
||||
const sourceCode = context.sourceCode;
|
||||
|
||||
/**
|
||||
* Returns the operator token of an AssignmentExpression or BinaryExpression
|
||||
* @param {ASTNode} node An AssignmentExpression or BinaryExpression node
|
||||
* @returns {Token} The operator token in the node
|
||||
*/
|
||||
function getOperatorToken(node) {
|
||||
return sourceCode.getFirstTokenBetween(
|
||||
node.left,
|
||||
node.right,
|
||||
token => token.value === node.operator,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that an assignment uses the shorthand form where possible.
|
||||
* @param {ASTNode} node An AssignmentExpression node.
|
||||
* @returns {void}
|
||||
*/
|
||||
function verify(node) {
|
||||
if (
|
||||
node.operator !== "=" ||
|
||||
node.right.type !== "BinaryExpression"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const left = node.left;
|
||||
const expr = node.right;
|
||||
const operator = expr.operator;
|
||||
|
||||
if (
|
||||
isCommutativeOperatorWithShorthand(operator) ||
|
||||
isNonCommutativeOperatorWithShorthand(operator)
|
||||
) {
|
||||
const replacementOperator = `${operator}=`;
|
||||
|
||||
if (astUtils.isSameReference(left, expr.left, true)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "replaced",
|
||||
data: { operator: replacementOperator },
|
||||
fix(fixer) {
|
||||
if (canBeFixed(left) && canBeFixed(expr.left)) {
|
||||
const equalsToken = getOperatorToken(node);
|
||||
const operatorToken = getOperatorToken(expr);
|
||||
const leftText = sourceCode
|
||||
.getText()
|
||||
.slice(node.range[0], equalsToken.range[0]);
|
||||
const rightText = sourceCode
|
||||
.getText()
|
||||
.slice(
|
||||
operatorToken.range[1],
|
||||
node.right.range[1],
|
||||
);
|
||||
|
||||
// Check for comments that would be removed.
|
||||
if (
|
||||
sourceCode.commentsExistBetween(
|
||||
equalsToken,
|
||||
operatorToken,
|
||||
)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return fixer.replaceText(
|
||||
node,
|
||||
`${leftText}${replacementOperator}${rightText}`,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
},
|
||||
});
|
||||
} else if (
|
||||
astUtils.isSameReference(left, expr.right, true) &&
|
||||
isCommutativeOperatorWithShorthand(operator)
|
||||
) {
|
||||
/*
|
||||
* This case can't be fixed safely.
|
||||
* If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would
|
||||
* change the execution order of the valueOf() functions.
|
||||
*/
|
||||
context.report({
|
||||
node,
|
||||
messageId: "replaced",
|
||||
data: { operator: replacementOperator },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Warns if an assignment expression uses operator assignment shorthand.
|
||||
* @param {ASTNode} node An AssignmentExpression node.
|
||||
* @returns {void}
|
||||
*/
|
||||
function prohibit(node) {
|
||||
if (
|
||||
node.operator !== "=" &&
|
||||
!astUtils.isLogicalAssignmentOperator(node.operator)
|
||||
) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "unexpected",
|
||||
data: { operator: node.operator },
|
||||
fix(fixer) {
|
||||
if (canBeFixed(node.left)) {
|
||||
const firstToken = sourceCode.getFirstToken(node);
|
||||
const operatorToken = getOperatorToken(node);
|
||||
const leftText = sourceCode
|
||||
.getText()
|
||||
.slice(node.range[0], operatorToken.range[0]);
|
||||
const newOperator = node.operator.slice(0, -1);
|
||||
let rightText;
|
||||
|
||||
// Check for comments that would be duplicated.
|
||||
if (
|
||||
sourceCode.commentsExistBetween(
|
||||
firstToken,
|
||||
operatorToken,
|
||||
)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side.
|
||||
if (
|
||||
astUtils.getPrecedence(node.right) <=
|
||||
astUtils.getPrecedence({
|
||||
type: "BinaryExpression",
|
||||
operator: newOperator,
|
||||
}) &&
|
||||
!astUtils.isParenthesised(
|
||||
sourceCode,
|
||||
node.right,
|
||||
)
|
||||
) {
|
||||
rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`;
|
||||
} else {
|
||||
const tokenAfterOperator =
|
||||
sourceCode.getTokenAfter(operatorToken, {
|
||||
includeComments: true,
|
||||
});
|
||||
let rightTextPrefix = "";
|
||||
|
||||
if (
|
||||
operatorToken.range[1] ===
|
||||
tokenAfterOperator.range[0] &&
|
||||
!astUtils.canTokensBeAdjacent(
|
||||
{
|
||||
type: "Punctuator",
|
||||
value: newOperator,
|
||||
},
|
||||
tokenAfterOperator,
|
||||
)
|
||||
) {
|
||||
rightTextPrefix = " "; // foo+=+bar -> foo= foo+ +bar
|
||||
}
|
||||
|
||||
rightText = `${rightTextPrefix}${sourceCode.text.slice(operatorToken.range[1], node.range[1])}`;
|
||||
}
|
||||
|
||||
return fixer.replaceText(
|
||||
node,
|
||||
`${leftText}= ${leftText}${newOperator}${rightText}`,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
AssignmentExpression: !never ? verify : prohibit,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,476 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.wNAF = void 0;
|
||||
exports.negateCt = negateCt;
|
||||
exports.normalizeZ = normalizeZ;
|
||||
exports.mulEndoUnsafe = mulEndoUnsafe;
|
||||
exports.pippenger = pippenger;
|
||||
exports.precomputeMSMUnsafe = precomputeMSMUnsafe;
|
||||
exports.validateBasic = validateBasic;
|
||||
exports._createCurveFields = _createCurveFields;
|
||||
/**
|
||||
* Methods for elliptic curve multiplication by scalars.
|
||||
* Contains wNAF, pippenger.
|
||||
* @module
|
||||
*/
|
||||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||||
const utils_ts_1 = require("../utils.js");
|
||||
const modular_ts_1 = require("./modular.js");
|
||||
const _0n = BigInt(0);
|
||||
const _1n = BigInt(1);
|
||||
function negateCt(condition, item) {
|
||||
const neg = item.negate();
|
||||
return condition ? neg : item;
|
||||
}
|
||||
/**
|
||||
* Takes a bunch of Projective Points but executes only one
|
||||
* inversion on all of them. Inversion is very slow operation,
|
||||
* so this improves performance massively.
|
||||
* Optimization: converts a list of projective points to a list of identical points with Z=1.
|
||||
*/
|
||||
function normalizeZ(c, points) {
|
||||
const invertedZs = (0, modular_ts_1.FpInvertBatch)(c.Fp, points.map((p) => p.Z));
|
||||
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
|
||||
}
|
||||
function validateW(W, bits) {
|
||||
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
|
||||
throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
|
||||
}
|
||||
function calcWOpts(W, scalarBits) {
|
||||
validateW(W, scalarBits);
|
||||
const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
|
||||
const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
|
||||
const maxNumber = 2 ** W; // W=8 256
|
||||
const mask = (0, utils_ts_1.bitMask)(W); // W=8 255 == mask 0b11111111
|
||||
const shiftBy = BigInt(W); // W=8 8
|
||||
return { windows, windowSize, mask, maxNumber, shiftBy };
|
||||
}
|
||||
function calcOffsets(n, window, wOpts) {
|
||||
const { windowSize, mask, maxNumber, shiftBy } = wOpts;
|
||||
let wbits = Number(n & mask); // extract W bits.
|
||||
let nextN = n >> shiftBy; // shift number by W bits.
|
||||
// What actually happens here:
|
||||
// const highestBit = Number(mask ^ (mask >> 1n));
|
||||
// let wbits2 = wbits - 1; // skip zero
|
||||
// if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
|
||||
// split if bits > max: +224 => 256-32
|
||||
if (wbits > windowSize) {
|
||||
// we skip zero, which means instead of `>= size-1`, we do `> size`
|
||||
wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
|
||||
nextN += _1n; // +256 (carry)
|
||||
}
|
||||
const offsetStart = window * windowSize;
|
||||
const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
|
||||
const isZero = wbits === 0; // is current window slice a 0?
|
||||
const isNeg = wbits < 0; // is current window slice negative?
|
||||
const isNegF = window % 2 !== 0; // fake random statement for noise
|
||||
const offsetF = offsetStart; // fake offset for noise
|
||||
return { nextN, offset, isZero, isNeg, isNegF, offsetF };
|
||||
}
|
||||
function validateMSMPoints(points, c) {
|
||||
if (!Array.isArray(points))
|
||||
throw new Error('array expected');
|
||||
points.forEach((p, i) => {
|
||||
if (!(p instanceof c))
|
||||
throw new Error('invalid point at index ' + i);
|
||||
});
|
||||
}
|
||||
function validateMSMScalars(scalars, field) {
|
||||
if (!Array.isArray(scalars))
|
||||
throw new Error('array of scalars expected');
|
||||
scalars.forEach((s, i) => {
|
||||
if (!field.isValid(s))
|
||||
throw new Error('invalid scalar at index ' + i);
|
||||
});
|
||||
}
|
||||
// Since points in different groups cannot be equal (different object constructor),
|
||||
// we can have single place to store precomputes.
|
||||
// Allows to make points frozen / immutable.
|
||||
const pointPrecomputes = new WeakMap();
|
||||
const pointWindowSizes = new WeakMap();
|
||||
function getW(P) {
|
||||
// To disable precomputes:
|
||||
// return 1;
|
||||
return pointWindowSizes.get(P) || 1;
|
||||
}
|
||||
function assert0(n) {
|
||||
if (n !== _0n)
|
||||
throw new Error('invalid wNAF');
|
||||
}
|
||||
/**
|
||||
* Elliptic curve multiplication of Point by scalar. Fragile.
|
||||
* Table generation takes **30MB of ram and 10ms on high-end CPU**,
|
||||
* but may take much longer on slow devices. Actual generation will happen on
|
||||
* first call of `multiply()`. By default, `BASE` point is precomputed.
|
||||
*
|
||||
* Scalars should always be less than curve order: this should be checked inside of a curve itself.
|
||||
* Creates precomputation tables for fast multiplication:
|
||||
* - private scalar is split by fixed size windows of W bits
|
||||
* - every window point is collected from window's table & added to accumulator
|
||||
* - since windows are different, same point inside tables won't be accessed more than once per calc
|
||||
* - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
|
||||
* - +1 window is neccessary for wNAF
|
||||
* - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
|
||||
*
|
||||
* @todo Research returning 2d JS array of windows, instead of a single window.
|
||||
* This would allow windows to be in different memory locations
|
||||
*/
|
||||
class wNAF {
|
||||
// Parametrized with a given Point class (not individual point)
|
||||
constructor(Point, bits) {
|
||||
this.BASE = Point.BASE;
|
||||
this.ZERO = Point.ZERO;
|
||||
this.Fn = Point.Fn;
|
||||
this.bits = bits;
|
||||
}
|
||||
// non-const time multiplication ladder
|
||||
_unsafeLadder(elm, n, p = this.ZERO) {
|
||||
let d = elm;
|
||||
while (n > _0n) {
|
||||
if (n & _1n)
|
||||
p = p.add(d);
|
||||
d = d.double();
|
||||
n >>= _1n;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
/**
|
||||
* Creates a wNAF precomputation window. Used for caching.
|
||||
* Default window size is set by `utils.precompute()` and is equal to 8.
|
||||
* Number of precomputed points depends on the curve size:
|
||||
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
|
||||
* - 𝑊 is the window size
|
||||
* - 𝑛 is the bitlength of the curve order.
|
||||
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
|
||||
* @param point Point instance
|
||||
* @param W window size
|
||||
* @returns precomputed point tables flattened to a single array
|
||||
*/
|
||||
precomputeWindow(point, W) {
|
||||
const { windows, windowSize } = calcWOpts(W, this.bits);
|
||||
const points = [];
|
||||
let p = point;
|
||||
let base = p;
|
||||
for (let window = 0; window < windows; window++) {
|
||||
base = p;
|
||||
points.push(base);
|
||||
// i=1, bc we skip 0
|
||||
for (let i = 1; i < windowSize; i++) {
|
||||
base = base.add(p);
|
||||
points.push(base);
|
||||
}
|
||||
p = base.double();
|
||||
}
|
||||
return points;
|
||||
}
|
||||
/**
|
||||
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
|
||||
* More compact implementation:
|
||||
* https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
|
||||
* @returns real and fake (for const-time) points
|
||||
*/
|
||||
wNAF(W, precomputes, n) {
|
||||
// Scalar should be smaller than field order
|
||||
if (!this.Fn.isValid(n))
|
||||
throw new Error('invalid scalar');
|
||||
// Accumulators
|
||||
let p = this.ZERO;
|
||||
let f = this.BASE;
|
||||
// This code was first written with assumption that 'f' and 'p' will never be infinity point:
|
||||
// since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
|
||||
// there is negate now: it is possible that negated element from low value
|
||||
// would be the same as high element, which will create carry into next window.
|
||||
// It's not obvious how this can fail, but still worth investigating later.
|
||||
const wo = calcWOpts(W, this.bits);
|
||||
for (let window = 0; window < wo.windows; window++) {
|
||||
// (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
|
||||
const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
|
||||
n = nextN;
|
||||
if (isZero) {
|
||||
// bits are 0: add garbage to fake point
|
||||
// Important part for const-time getPublicKey: add random "noise" point to f.
|
||||
f = f.add(negateCt(isNegF, precomputes[offsetF]));
|
||||
}
|
||||
else {
|
||||
// bits are 1: add to result point
|
||||
p = p.add(negateCt(isNeg, precomputes[offset]));
|
||||
}
|
||||
}
|
||||
assert0(n);
|
||||
// Return both real and fake points: JIT won't eliminate f.
|
||||
// At this point there is a way to F be infinity-point even if p is not,
|
||||
// which makes it less const-time: around 1 bigint multiply.
|
||||
return { p, f };
|
||||
}
|
||||
/**
|
||||
* Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
|
||||
* @param acc accumulator point to add result of multiplication
|
||||
* @returns point
|
||||
*/
|
||||
wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
|
||||
const wo = calcWOpts(W, this.bits);
|
||||
for (let window = 0; window < wo.windows; window++) {
|
||||
if (n === _0n)
|
||||
break; // Early-exit, skip 0 value
|
||||
const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
|
||||
n = nextN;
|
||||
if (isZero) {
|
||||
// Window bits are 0: skip processing.
|
||||
// Move to next window.
|
||||
continue;
|
||||
}
|
||||
else {
|
||||
const item = precomputes[offset];
|
||||
acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
|
||||
}
|
||||
}
|
||||
assert0(n);
|
||||
return acc;
|
||||
}
|
||||
getPrecomputes(W, point, transform) {
|
||||
// Calculate precomputes on a first run, reuse them after
|
||||
let comp = pointPrecomputes.get(point);
|
||||
if (!comp) {
|
||||
comp = this.precomputeWindow(point, W);
|
||||
if (W !== 1) {
|
||||
// Doing transform outside of if brings 15% perf hit
|
||||
if (typeof transform === 'function')
|
||||
comp = transform(comp);
|
||||
pointPrecomputes.set(point, comp);
|
||||
}
|
||||
}
|
||||
return comp;
|
||||
}
|
||||
cached(point, scalar, transform) {
|
||||
const W = getW(point);
|
||||
return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
|
||||
}
|
||||
unsafe(point, scalar, transform, prev) {
|
||||
const W = getW(point);
|
||||
if (W === 1)
|
||||
return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster
|
||||
return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
|
||||
}
|
||||
// We calculate precomputes for elliptic curve point multiplication
|
||||
// using windowed method. This specifies window size and
|
||||
// stores precomputed values. Usually only base point would be precomputed.
|
||||
createCache(P, W) {
|
||||
validateW(W, this.bits);
|
||||
pointWindowSizes.set(P, W);
|
||||
pointPrecomputes.delete(P);
|
||||
}
|
||||
hasCache(elm) {
|
||||
return getW(elm) !== 1;
|
||||
}
|
||||
}
|
||||
exports.wNAF = wNAF;
|
||||
/**
|
||||
* Endomorphism-specific multiplication for Koblitz curves.
|
||||
* Cost: 128 dbl, 0-256 adds.
|
||||
*/
|
||||
function mulEndoUnsafe(Point, point, k1, k2) {
|
||||
let acc = point;
|
||||
let p1 = Point.ZERO;
|
||||
let p2 = Point.ZERO;
|
||||
while (k1 > _0n || k2 > _0n) {
|
||||
if (k1 & _1n)
|
||||
p1 = p1.add(acc);
|
||||
if (k2 & _1n)
|
||||
p2 = p2.add(acc);
|
||||
acc = acc.double();
|
||||
k1 >>= _1n;
|
||||
k2 >>= _1n;
|
||||
}
|
||||
return { p1, p2 };
|
||||
}
|
||||
/**
|
||||
* Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
|
||||
* 30x faster vs naive addition on L=4096, 10x faster than precomputes.
|
||||
* For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
|
||||
* Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
|
||||
* @param c Curve Point constructor
|
||||
* @param fieldN field over CURVE.N - important that it's not over CURVE.P
|
||||
* @param points array of L curve points
|
||||
* @param scalars array of L scalars (aka secret keys / bigints)
|
||||
*/
|
||||
function pippenger(c, fieldN, points, scalars) {
|
||||
// If we split scalars by some window (let's say 8 bits), every chunk will only
|
||||
// take 256 buckets even if there are 4096 scalars, also re-uses double.
|
||||
// TODO:
|
||||
// - https://eprint.iacr.org/2024/750.pdf
|
||||
// - https://tches.iacr.org/index.php/TCHES/article/view/10287
|
||||
// 0 is accepted in scalars
|
||||
validateMSMPoints(points, c);
|
||||
validateMSMScalars(scalars, fieldN);
|
||||
const plength = points.length;
|
||||
const slength = scalars.length;
|
||||
if (plength !== slength)
|
||||
throw new Error('arrays of points and scalars must have equal length');
|
||||
// if (plength === 0) throw new Error('array must be of length >= 2');
|
||||
const zero = c.ZERO;
|
||||
const wbits = (0, utils_ts_1.bitLen)(BigInt(plength));
|
||||
let windowSize = 1; // bits
|
||||
if (wbits > 12)
|
||||
windowSize = wbits - 3;
|
||||
else if (wbits > 4)
|
||||
windowSize = wbits - 2;
|
||||
else if (wbits > 0)
|
||||
windowSize = 2;
|
||||
const MASK = (0, utils_ts_1.bitMask)(windowSize);
|
||||
const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
|
||||
const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
|
||||
let sum = zero;
|
||||
for (let i = lastBits; i >= 0; i -= windowSize) {
|
||||
buckets.fill(zero);
|
||||
for (let j = 0; j < slength; j++) {
|
||||
const scalar = scalars[j];
|
||||
const wbits = Number((scalar >> BigInt(i)) & MASK);
|
||||
buckets[wbits] = buckets[wbits].add(points[j]);
|
||||
}
|
||||
let resI = zero; // not using this will do small speed-up, but will lose ct
|
||||
// Skip first bucket, because it is zero
|
||||
for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
|
||||
sumI = sumI.add(buckets[j]);
|
||||
resI = resI.add(sumI);
|
||||
}
|
||||
sum = sum.add(resI);
|
||||
if (i !== 0)
|
||||
for (let j = 0; j < windowSize; j++)
|
||||
sum = sum.double();
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
/**
|
||||
* Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
|
||||
* @param c Curve Point constructor
|
||||
* @param fieldN field over CURVE.N - important that it's not over CURVE.P
|
||||
* @param points array of L curve points
|
||||
* @returns function which multiplies points with scaars
|
||||
*/
|
||||
function precomputeMSMUnsafe(c, fieldN, points, windowSize) {
|
||||
/**
|
||||
* Performance Analysis of Window-based Precomputation
|
||||
*
|
||||
* Base Case (256-bit scalar, 8-bit window):
|
||||
* - Standard precomputation requires:
|
||||
* - 31 additions per scalar × 256 scalars = 7,936 ops
|
||||
* - Plus 255 summary additions = 8,191 total ops
|
||||
* Note: Summary additions can be optimized via accumulator
|
||||
*
|
||||
* Chunked Precomputation Analysis:
|
||||
* - Using 32 chunks requires:
|
||||
* - 255 additions per chunk
|
||||
* - 256 doublings
|
||||
* - Total: (255 × 32) + 256 = 8,416 ops
|
||||
*
|
||||
* Memory Usage Comparison:
|
||||
* Window Size | Standard Points | Chunked Points
|
||||
* ------------|-----------------|---------------
|
||||
* 4-bit | 520 | 15
|
||||
* 8-bit | 4,224 | 255
|
||||
* 10-bit | 13,824 | 1,023
|
||||
* 16-bit | 557,056 | 65,535
|
||||
*
|
||||
* Key Advantages:
|
||||
* 1. Enables larger window sizes due to reduced memory overhead
|
||||
* 2. More efficient for smaller scalar counts:
|
||||
* - 16 chunks: (16 × 255) + 256 = 4,336 ops
|
||||
* - ~2x faster than standard 8,191 ops
|
||||
*
|
||||
* Limitations:
|
||||
* - Not suitable for plain precomputes (requires 256 constant doublings)
|
||||
* - Performance degrades with larger scalar counts:
|
||||
* - Optimal for ~256 scalars
|
||||
* - Less efficient for 4096+ scalars (Pippenger preferred)
|
||||
*/
|
||||
validateW(windowSize, fieldN.BITS);
|
||||
validateMSMPoints(points, c);
|
||||
const zero = c.ZERO;
|
||||
const tableSize = 2 ** windowSize - 1; // table size (without zero)
|
||||
const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item
|
||||
const MASK = (0, utils_ts_1.bitMask)(windowSize);
|
||||
const tables = points.map((p) => {
|
||||
const res = [];
|
||||
for (let i = 0, acc = p; i < tableSize; i++) {
|
||||
res.push(acc);
|
||||
acc = acc.add(p);
|
||||
}
|
||||
return res;
|
||||
});
|
||||
return (scalars) => {
|
||||
validateMSMScalars(scalars, fieldN);
|
||||
if (scalars.length > points.length)
|
||||
throw new Error('array of scalars must be smaller than array of points');
|
||||
let res = zero;
|
||||
for (let i = 0; i < chunks; i++) {
|
||||
// No need to double if accumulator is still zero.
|
||||
if (res !== zero)
|
||||
for (let j = 0; j < windowSize; j++)
|
||||
res = res.double();
|
||||
const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);
|
||||
for (let j = 0; j < scalars.length; j++) {
|
||||
const n = scalars[j];
|
||||
const curr = Number((n >> shiftBy) & MASK);
|
||||
if (!curr)
|
||||
continue; // skip zero scalars chunks
|
||||
res = res.add(tables[j][curr - 1]);
|
||||
}
|
||||
}
|
||||
return res;
|
||||
};
|
||||
}
|
||||
// TODO: remove
|
||||
/** @deprecated */
|
||||
function validateBasic(curve) {
|
||||
(0, modular_ts_1.validateField)(curve.Fp);
|
||||
(0, utils_ts_1.validateObject)(curve, {
|
||||
n: 'bigint',
|
||||
h: 'bigint',
|
||||
Gx: 'field',
|
||||
Gy: 'field',
|
||||
}, {
|
||||
nBitLength: 'isSafeInteger',
|
||||
nByteLength: 'isSafeInteger',
|
||||
});
|
||||
// Set defaults
|
||||
return Object.freeze({
|
||||
...(0, modular_ts_1.nLength)(curve.n, curve.nBitLength),
|
||||
...curve,
|
||||
...{ p: curve.Fp.ORDER },
|
||||
});
|
||||
}
|
||||
function createField(order, field, isLE) {
|
||||
if (field) {
|
||||
if (field.ORDER !== order)
|
||||
throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
|
||||
(0, modular_ts_1.validateField)(field);
|
||||
return field;
|
||||
}
|
||||
else {
|
||||
return (0, modular_ts_1.Field)(order, { isLE });
|
||||
}
|
||||
}
|
||||
/** Validates CURVE opts and creates fields */
|
||||
function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
|
||||
if (FpFnLE === undefined)
|
||||
FpFnLE = type === 'edwards';
|
||||
if (!CURVE || typeof CURVE !== 'object')
|
||||
throw new Error(`expected valid ${type} CURVE object`);
|
||||
for (const p of ['p', 'n', 'h']) {
|
||||
const val = CURVE[p];
|
||||
if (!(typeof val === 'bigint' && val > _0n))
|
||||
throw new Error(`CURVE.${p} must be positive bigint`);
|
||||
}
|
||||
const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
|
||||
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
|
||||
const _b = type === 'weierstrass' ? 'b' : 'd';
|
||||
const params = ['Gx', 'Gy', 'a', _b];
|
||||
for (const p of params) {
|
||||
// @ts-ignore
|
||||
if (!Fp.isValid(CURVE[p]))
|
||||
throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
|
||||
}
|
||||
CURVE = Object.freeze(Object.assign({}, CURVE));
|
||||
return { CURVE, Fp, Fn };
|
||||
}
|
||||
//# sourceMappingURL=curve.js.map
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,137 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = default_1;
|
||||
const util = __importStar(require("../core/util.cjs"));
|
||||
const error = () => {
|
||||
const Sizable = {
|
||||
string: { unit: "எழுத்துக்கள்", verb: "கொண்டிருக்க வேண்டும்" },
|
||||
file: { unit: "பைட்டுகள்", verb: "கொண்டிருக்க வேண்டும்" },
|
||||
array: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" },
|
||||
set: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" },
|
||||
};
|
||||
function getSizing(origin) {
|
||||
return Sizable[origin] ?? null;
|
||||
}
|
||||
const FormatDictionary = {
|
||||
regex: "உள்ளீடு",
|
||||
email: "மின்னஞ்சல் முகவரி",
|
||||
url: "URL",
|
||||
emoji: "emoji",
|
||||
uuid: "UUID",
|
||||
uuidv4: "UUIDv4",
|
||||
uuidv6: "UUIDv6",
|
||||
nanoid: "nanoid",
|
||||
guid: "GUID",
|
||||
cuid: "cuid",
|
||||
cuid2: "cuid2",
|
||||
ulid: "ULID",
|
||||
xid: "XID",
|
||||
ksuid: "KSUID",
|
||||
datetime: "ISO தேதி நேரம்",
|
||||
date: "ISO தேதி",
|
||||
time: "ISO நேரம்",
|
||||
duration: "ISO கால அளவு",
|
||||
ipv4: "IPv4 முகவரி",
|
||||
ipv6: "IPv6 முகவரி",
|
||||
cidrv4: "IPv4 வரம்பு",
|
||||
cidrv6: "IPv6 வரம்பு",
|
||||
base64: "base64-encoded சரம்",
|
||||
base64url: "base64url-encoded சரம்",
|
||||
json_string: "JSON சரம்",
|
||||
e164: "E.164 எண்",
|
||||
jwt: "JWT",
|
||||
template_literal: "input",
|
||||
};
|
||||
const TypeDictionary = {
|
||||
nan: "NaN",
|
||||
number: "எண்",
|
||||
array: "அணி",
|
||||
null: "வெறுமை",
|
||||
};
|
||||
return (issue) => {
|
||||
switch (issue.code) {
|
||||
case "invalid_type": {
|
||||
const expected = TypeDictionary[issue.expected] ?? issue.expected;
|
||||
const receivedType = util.parsedType(issue.input);
|
||||
const received = TypeDictionary[receivedType] ?? receivedType;
|
||||
if (/^[A-Z]/.test(issue.expected)) {
|
||||
return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${issue.expected}, பெறப்பட்டது ${received}`;
|
||||
}
|
||||
return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${expected}, பெறப்பட்டது ${received}`;
|
||||
}
|
||||
case "invalid_value":
|
||||
if (issue.values.length === 1)
|
||||
return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${util.stringifyPrimitive(issue.values[0])}`;
|
||||
return `தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${util.joinValues(issue.values, "|")} இல் ஒன்று`;
|
||||
case "too_big": {
|
||||
const adj = issue.inclusive ? "<=" : "<";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing) {
|
||||
return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue.origin ?? "மதிப்பு"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "உறுப்புகள்"} ஆக இருக்க வேண்டும்`;
|
||||
}
|
||||
return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue.origin ?? "மதிப்பு"} ${adj}${issue.maximum.toString()} ஆக இருக்க வேண்டும்`;
|
||||
}
|
||||
case "too_small": {
|
||||
const adj = issue.inclusive ? ">=" : ">";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing) {
|
||||
return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} ஆக இருக்க வேண்டும்`; //
|
||||
}
|
||||
return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue.origin} ${adj}${issue.minimum.toString()} ஆக இருக்க வேண்டும்`;
|
||||
}
|
||||
case "invalid_format": {
|
||||
const _issue = issue;
|
||||
if (_issue.format === "starts_with")
|
||||
return `தவறான சரம்: "${_issue.prefix}" இல் தொடங்க வேண்டும்`;
|
||||
if (_issue.format === "ends_with")
|
||||
return `தவறான சரம்: "${_issue.suffix}" இல் முடிவடைய வேண்டும்`;
|
||||
if (_issue.format === "includes")
|
||||
return `தவறான சரம்: "${_issue.includes}" ஐ உள்ளடக்க வேண்டும்`;
|
||||
if (_issue.format === "regex")
|
||||
return `தவறான சரம்: ${_issue.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;
|
||||
return `தவறான ${FormatDictionary[_issue.format] ?? issue.format}`;
|
||||
}
|
||||
case "not_multiple_of":
|
||||
return `தவறான எண்: ${issue.divisor} இன் பலமாக இருக்க வேண்டும்`;
|
||||
case "unrecognized_keys":
|
||||
return `அடையாளம் தெரியாத விசை${issue.keys.length > 1 ? "கள்" : ""}: ${util.joinValues(issue.keys, ", ")}`;
|
||||
case "invalid_key":
|
||||
return `${issue.origin} இல் தவறான விசை`;
|
||||
case "invalid_union":
|
||||
return "தவறான உள்ளீடு";
|
||||
case "invalid_element":
|
||||
return `${issue.origin} இல் தவறான மதிப்பு`;
|
||||
default:
|
||||
return `தவறான உள்ளீடு`;
|
||||
}
|
||||
};
|
||||
};
|
||||
function default_1() {
|
||||
return {
|
||||
localeError: error(),
|
||||
};
|
||||
}
|
||||
module.exports = exports.default;
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"diagnosticCategory.enum.js","sourceRoot":"","sources":["../../src/enums/diagnosticCategory.enum.ts"],"names":[],"mappings":"AAAA,yGAAyG;AAEzG,MAAM,CAAN,IAAY,kBAKX;AALD,WAAY,kBAAkB;IAC1B,iEAAW,CAAA;IACX,6DAAS,CAAA;IACT,uEAAc,CAAA;IACd,iEAAW,CAAA;AACf,CAAC,EALW,kBAAkB,KAAlB,kBAAkB,QAK7B"}
|
||||
@@ -0,0 +1 @@
|
||||
export { _ as default } from "../esm/_iterable_to_array_limit.js";
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Compiler options required to avoid critical functionality issues
|
||||
*/
|
||||
export declare const CORE_COMPILER_OPTIONS: {
|
||||
noEmit: true;
|
||||
noUnusedLocals: true;
|
||||
noUnusedParameters: true;
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { TSESTree } from '@typescript-eslint/utils';
|
||||
export type ClassNode = TSESTree.ClassDeclaration | TSESTree.ClassExpression;
|
||||
export type MemberNode = TSESTree.AccessorProperty | TSESTree.MethodDefinition | TSESTree.PropertyDefinition | TSESTree.TSAbstractAccessorProperty | TSESTree.TSAbstractMethodDefinition | TSESTree.TSAbstractPropertyDefinition | TSESTree.TSParameterProperty;
|
||||
export type PrivateKey = string & {
|
||||
__brand: 'private-key';
|
||||
};
|
||||
export type PublicKey = string & {
|
||||
__brand: 'public-key';
|
||||
};
|
||||
export type Key = PrivateKey | PublicKey;
|
||||
export declare function publicKey(name: string): PublicKey;
|
||||
export declare function privateKey(node: TSESTree.PrivateIdentifier): PrivateKey;
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,11 @@
|
||||
"use strict";
|
||||
|
||||
var _assert_this_initialized = require("./_assert_this_initialized.cjs");
|
||||
var _type_of = require("./_type_of.cjs");
|
||||
|
||||
function _possible_constructor_return(self, call) {
|
||||
if (call && (_type_of._(call) === "object" || typeof call === "function")) return call;
|
||||
|
||||
return _assert_this_initialized._(self);
|
||||
}
|
||||
exports._ = _possible_constructor_return;
|
||||
@@ -0,0 +1,104 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.default = void 0;
|
||||
|
||||
// Adapted from Chris Veness' SHA1 code at
|
||||
// http://www.movable-type.co.uk/scripts/sha1.html
|
||||
function f(s, x, y, z) {
|
||||
switch (s) {
|
||||
case 0:
|
||||
return x & y ^ ~x & z;
|
||||
|
||||
case 1:
|
||||
return x ^ y ^ z;
|
||||
|
||||
case 2:
|
||||
return x & y ^ x & z ^ y & z;
|
||||
|
||||
case 3:
|
||||
return x ^ y ^ z;
|
||||
}
|
||||
}
|
||||
|
||||
function ROTL(x, n) {
|
||||
return x << n | x >>> 32 - n;
|
||||
}
|
||||
|
||||
function sha1(bytes) {
|
||||
const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
|
||||
const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
|
||||
|
||||
if (typeof bytes === 'string') {
|
||||
const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
|
||||
|
||||
bytes = [];
|
||||
|
||||
for (let i = 0; i < msg.length; ++i) {
|
||||
bytes.push(msg.charCodeAt(i));
|
||||
}
|
||||
} else if (!Array.isArray(bytes)) {
|
||||
// Convert Array-like to Array
|
||||
bytes = Array.prototype.slice.call(bytes);
|
||||
}
|
||||
|
||||
bytes.push(0x80);
|
||||
const l = bytes.length / 4 + 2;
|
||||
const N = Math.ceil(l / 16);
|
||||
const M = new Array(N);
|
||||
|
||||
for (let i = 0; i < N; ++i) {
|
||||
const arr = new Uint32Array(16);
|
||||
|
||||
for (let j = 0; j < 16; ++j) {
|
||||
arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3];
|
||||
}
|
||||
|
||||
M[i] = arr;
|
||||
}
|
||||
|
||||
M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
|
||||
M[N - 1][14] = Math.floor(M[N - 1][14]);
|
||||
M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
|
||||
|
||||
for (let i = 0; i < N; ++i) {
|
||||
const W = new Uint32Array(80);
|
||||
|
||||
for (let t = 0; t < 16; ++t) {
|
||||
W[t] = M[i][t];
|
||||
}
|
||||
|
||||
for (let t = 16; t < 80; ++t) {
|
||||
W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
|
||||
}
|
||||
|
||||
let a = H[0];
|
||||
let b = H[1];
|
||||
let c = H[2];
|
||||
let d = H[3];
|
||||
let e = H[4];
|
||||
|
||||
for (let t = 0; t < 80; ++t) {
|
||||
const s = Math.floor(t / 20);
|
||||
const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0;
|
||||
e = d;
|
||||
d = c;
|
||||
c = ROTL(b, 30) >>> 0;
|
||||
b = a;
|
||||
a = T;
|
||||
}
|
||||
|
||||
H[0] = H[0] + a >>> 0;
|
||||
H[1] = H[1] + b >>> 0;
|
||||
H[2] = H[2] + c >>> 0;
|
||||
H[3] = H[3] + d >>> 0;
|
||||
H[4] = H[4] + e >>> 0;
|
||||
}
|
||||
|
||||
return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
|
||||
}
|
||||
|
||||
var _default = sha1;
|
||||
exports.default = _default;
|
||||
@@ -0,0 +1,59 @@
|
||||
import { expect, expectTypeOf, test } from "vitest";
|
||||
|
||||
import * as z from "zod/v4";
|
||||
|
||||
test("basic apply (object)", () => {
|
||||
const schema = z
|
||||
.object({
|
||||
a: z.number(),
|
||||
b: z.string(),
|
||||
})
|
||||
.apply((s) => s.omit({ b: true }))
|
||||
.apply((s) => s.extend({ c: z.boolean() }));
|
||||
|
||||
expect(z.toJSONSchema(schema)).toMatchInlineSnapshot(`
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"a": {
|
||||
"type": "number",
|
||||
},
|
||||
"c": {
|
||||
"type": "boolean",
|
||||
},
|
||||
},
|
||||
"required": [
|
||||
"a",
|
||||
"c",
|
||||
],
|
||||
"type": "object",
|
||||
}
|
||||
`);
|
||||
expectTypeOf<z.infer<typeof schema>>().toEqualTypeOf<{
|
||||
a: number;
|
||||
c: boolean;
|
||||
}>();
|
||||
});
|
||||
|
||||
test("basic apply (number)", () => {
|
||||
const setCommonNumberChecks = <T extends z.ZodNumber>(schema: T) => {
|
||||
return schema.min(0).max(100);
|
||||
};
|
||||
|
||||
const schema = z.number().apply(setCommonNumberChecks).nullable();
|
||||
|
||||
expect(() => schema.parse(-1)).toThrowError();
|
||||
expect(() => schema.parse(101)).toThrowError();
|
||||
expect(schema.parse(0)).toBe(0);
|
||||
expect(schema.parse(null)).toBe(null);
|
||||
expectTypeOf<z.infer<typeof schema>>().toEqualTypeOf<number | null>();
|
||||
});
|
||||
|
||||
test("The callback's return value becomes the apply's return value.", () => {
|
||||
const symbol = Symbol();
|
||||
const result = z.number().apply(() => symbol);
|
||||
|
||||
expect(result).toBe(symbol);
|
||||
expectTypeOf<typeof result>().toEqualTypeOf<symbol>();
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,4 @@
|
||||
import { stringify } from '../index.js'
|
||||
|
||||
export * from '../index.js'
|
||||
export default stringify
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { Lib, SourceType, TSESTree } from '@typescript-eslint/types';
|
||||
import type { ReferencerOptions } from './referencer';
|
||||
import { ScopeManager } from './ScopeManager';
|
||||
export interface AnalyzeOptions {
|
||||
/**
|
||||
* Known visitor keys.
|
||||
*/
|
||||
childVisitorKeys?: ReferencerOptions['childVisitorKeys'];
|
||||
/**
|
||||
* Whether the whole script is executed under node.js environment.
|
||||
* When enabled, the scope manager adds a function scope immediately following the global scope.
|
||||
* Defaults to `false`.
|
||||
*/
|
||||
globalReturn?: boolean;
|
||||
/**
|
||||
* Implied strict mode.
|
||||
* Defaults to `false`.
|
||||
*/
|
||||
impliedStrict?: boolean;
|
||||
/**
|
||||
* The identifier that's used for JSX Element creation (after transpilation).
|
||||
* This should not be a member expression - just the root identifier (i.e. use "React" instead of "React.createElement").
|
||||
* Defaults to `"React"`.
|
||||
*/
|
||||
jsxPragma?: string | null;
|
||||
/**
|
||||
* The identifier that's used for JSX fragment elements (after transpilation).
|
||||
* If `null`, assumes transpilation will always use a member on `jsxFactory` (i.e. React.Fragment).
|
||||
* This should not be a member expression - just the root identifier (i.e. use "h" instead of "h.Fragment").
|
||||
* Defaults to `null`.
|
||||
*/
|
||||
jsxFragmentName?: string | null;
|
||||
/**
|
||||
* The lib used by the project.
|
||||
* This automatically defines a type variable for any types provided by the configured TS libs.
|
||||
* Defaults to ['esnext'].
|
||||
*
|
||||
* https://www.typescriptlang.org/tsconfig#lib
|
||||
*/
|
||||
lib?: Lib[];
|
||||
/**
|
||||
* The source type of the script.
|
||||
*/
|
||||
sourceType?: SourceType;
|
||||
/**
|
||||
* @deprecated This option never did what it was intended for and will be removed in a future major release.
|
||||
*/
|
||||
emitDecoratorMetadata?: boolean;
|
||||
}
|
||||
/**
|
||||
* Takes an AST and returns the analyzed scopes.
|
||||
*/
|
||||
export declare function analyze(tree: TSESTree.Program, providedOptions?: AnalyzeOptions): ScopeManager;
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2022 Paul Miller (https://paulmillr.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the “Software”), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
@@ -0,0 +1,9 @@
|
||||
'use strict'
|
||||
|
||||
global.process = { __proto__: process, pid: 123456 }
|
||||
Date.now = function () { return 1459875739796 }
|
||||
require('node:os').hostname = function () { return 'abcdefghijklmnopqr' }
|
||||
|
||||
const pino = require('../../..')()
|
||||
|
||||
pino.info('hello world')
|
||||
@@ -0,0 +1,22 @@
|
||||
import { RAL, Disposable } from '../common/api';
|
||||
interface RIL extends RAL {
|
||||
readonly stream: {
|
||||
readonly asReadableStream: (stream: WebSocket) => RAL.ReadableStream;
|
||||
readonly asWritableStream: (stream: WebSocket) => RAL.WritableStream;
|
||||
};
|
||||
}
|
||||
export declare class QueueMicrotaskImpl implements Disposable {
|
||||
private isDisposed;
|
||||
constructor(callback: (...args: any[]) => void, ...args: any[]);
|
||||
dispose(): void;
|
||||
}
|
||||
export declare class PromiseImpl implements Disposable {
|
||||
private isDisposed;
|
||||
constructor(callback: (...args: any[]) => void, ...args: any[]);
|
||||
dispose(): void;
|
||||
}
|
||||
declare function RIL(): RIL;
|
||||
declare namespace RIL {
|
||||
function install(): void;
|
||||
}
|
||||
export default RIL;
|
||||
@@ -0,0 +1,17 @@
|
||||
"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.es2018_asyncgenerator = void 0;
|
||||
const base_config_1 = require("./base-config");
|
||||
const es2018_asynciterable_1 = require("./es2018.asynciterable");
|
||||
exports.es2018_asyncgenerator = {
|
||||
libs: [es2018_asynciterable_1.es2018_asynciterable],
|
||||
variables: [
|
||||
['AsyncGenerator', base_config_1.TYPE],
|
||||
['AsyncGeneratorFunction', base_config_1.TYPE],
|
||||
['AsyncGeneratorFunctionConstructor', base_config_1.TYPE],
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
var assert = require('assert');
|
||||
var stackback = require('./');
|
||||
|
||||
test('capture', function() {
|
||||
var err = new Error();
|
||||
var stack = stackback(err);
|
||||
assert.equal(stack[0].getFileName(), __filename);
|
||||
});
|
||||
|
||||
// calling stackback on the same error twice should work
|
||||
test('multiple calls', function() {
|
||||
var err = new Error();
|
||||
var stack1 = stackback(err);
|
||||
var stack2 = stackback(err);
|
||||
assert.equal(stack1[0].getFileName(), __filename);
|
||||
assert.deepEqual(stack1, stack2);
|
||||
});
|
||||
|
||||
test('string', function() {
|
||||
var err = new Error();
|
||||
stackback(err);
|
||||
assert.equal(typeof err.stack, 'string');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
import type { TSESTree } from '@typescript-eslint/utils';
|
||||
export declare function getParentFunctionNode(node: TSESTree.Node): TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclaration | TSESTree.FunctionExpression | null;
|
||||
@@ -0,0 +1,2 @@
|
||||
import type { TSESTree } from '@typescript-eslint/utils';
|
||||
export declare function getThisExpression(node: TSESTree.Node): TSESTree.ThisExpression | undefined;
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"name": "real-require",
|
||||
"version": "0.2.0",
|
||||
"description": "Keep require and import consistent after bundling or transpiling",
|
||||
"author": "Paolo Insogna <shogun@cowtech.it>",
|
||||
"homepage": "https://github.com/pinojs/real-require",
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Paolo Insogna",
|
||||
"url": "https://github.com/ShogunPanda"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/pinojs/real-require.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/pinojs/real-require/issues"
|
||||
},
|
||||
"main": "src/index.js",
|
||||
"files": [
|
||||
"src"
|
||||
],
|
||||
"scripts": {
|
||||
"format": "prettier -w src test",
|
||||
"lint": "eslint src test",
|
||||
"test": "c8 --reporter=text --reporter=html tap --reporter=spec --no-coverage test/*.test.js",
|
||||
"test:watch": "tap --watch --reporter=spec --no-browser --coverage-report=text --coverage-report=html test/*.test.js",
|
||||
"test:ci": "c8 --reporter=text --reporter=json --check-coverage --branches 90 --functions 90 --lines 90 --statements 90 tap --no-color --no-coverage test/*.test.js",
|
||||
"ci": "npm run lint && npm run test:ci",
|
||||
"prepublishOnly": "npm run ci",
|
||||
"postpublish": "git push origin && git push origin -f --tags"
|
||||
},
|
||||
"devDependencies": {
|
||||
"eslint": "^7.12.0",
|
||||
"eslint-config-standard": "^16.0.3",
|
||||
"eslint-plugin-import": "^2.25.2",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-plugin-promise": "^5.1.1",
|
||||
"eslint-plugin-standard": "^5.0.0",
|
||||
"c8": "^7.10.0",
|
||||
"prettier": "^2.4.1",
|
||||
"tap": "^16.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 12.13.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import * as core from "./core.js";
|
||||
import * as errors from "./errors.js";
|
||||
import type * as schemas from "./schemas.js";
|
||||
import * as util from "./util.js";
|
||||
export type $ZodErrorClass = {
|
||||
new (issues: errors.$ZodIssue[]): errors.$ZodError;
|
||||
};
|
||||
export type $Parse = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>, _params?: {
|
||||
callee?: util.AnyFunc;
|
||||
Err?: $ZodErrorClass;
|
||||
}) => core.output<T>;
|
||||
export declare const _parse: (_Err: $ZodErrorClass) => $Parse;
|
||||
export declare const parse: $Parse;
|
||||
export type $ParseAsync = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>, _params?: {
|
||||
callee?: util.AnyFunc;
|
||||
Err?: $ZodErrorClass;
|
||||
}) => Promise<core.output<T>>;
|
||||
export declare const _parseAsync: (_Err: $ZodErrorClass) => $ParseAsync;
|
||||
export declare const parseAsync: $ParseAsync;
|
||||
export type $SafeParse = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => util.SafeParseResult<core.output<T>>;
|
||||
export declare const _safeParse: (_Err: $ZodErrorClass) => $SafeParse;
|
||||
export declare const safeParse: $SafeParse;
|
||||
export type $SafeParseAsync = <T extends schemas.$ZodType>(schema: T, value: unknown, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => Promise<util.SafeParseResult<core.output<T>>>;
|
||||
export declare const _safeParseAsync: (_Err: $ZodErrorClass) => $SafeParseAsync;
|
||||
export declare const safeParseAsync: $SafeParseAsync;
|
||||
export type $Encode = <T extends schemas.$ZodType>(schema: T, value: core.output<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => core.input<T>;
|
||||
export declare const _encode: (_Err: $ZodErrorClass) => $Encode;
|
||||
export declare const encode: $Encode;
|
||||
export type $Decode = <T extends schemas.$ZodType>(schema: T, value: core.input<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => core.output<T>;
|
||||
export declare const _decode: (_Err: $ZodErrorClass) => $Decode;
|
||||
export declare const decode: $Decode;
|
||||
export type $EncodeAsync = <T extends schemas.$ZodType>(schema: T, value: core.output<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => Promise<core.input<T>>;
|
||||
export declare const _encodeAsync: (_Err: $ZodErrorClass) => $EncodeAsync;
|
||||
export declare const encodeAsync: $EncodeAsync;
|
||||
export type $DecodeAsync = <T extends schemas.$ZodType>(schema: T, value: core.input<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => Promise<core.output<T>>;
|
||||
export declare const _decodeAsync: (_Err: $ZodErrorClass) => $DecodeAsync;
|
||||
export declare const decodeAsync: $DecodeAsync;
|
||||
export type $SafeEncode = <T extends schemas.$ZodType>(schema: T, value: core.output<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => util.SafeParseResult<core.input<T>>;
|
||||
export declare const _safeEncode: (_Err: $ZodErrorClass) => $SafeEncode;
|
||||
export declare const safeEncode: $SafeEncode;
|
||||
export type $SafeDecode = <T extends schemas.$ZodType>(schema: T, value: core.input<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => util.SafeParseResult<core.output<T>>;
|
||||
export declare const _safeDecode: (_Err: $ZodErrorClass) => $SafeDecode;
|
||||
export declare const safeDecode: $SafeDecode;
|
||||
export type $SafeEncodeAsync = <T extends schemas.$ZodType>(schema: T, value: core.output<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => Promise<util.SafeParseResult<core.input<T>>>;
|
||||
export declare const _safeEncodeAsync: (_Err: $ZodErrorClass) => $SafeEncodeAsync;
|
||||
export declare const safeEncodeAsync: $SafeEncodeAsync;
|
||||
export type $SafeDecodeAsync = <T extends schemas.$ZodType>(schema: T, value: core.input<T>, _ctx?: schemas.ParseContext<errors.$ZodIssue>) => Promise<util.SafeParseResult<core.output<T>>>;
|
||||
export declare const _safeDecodeAsync: (_Err: $ZodErrorClass) => $SafeDecodeAsync;
|
||||
export declare const safeDecodeAsync: $SafeDecodeAsync;
|
||||
Reference in New Issue
Block a user