WIP: bootstrap and partial real Solana watcher implementation
This commit is contained in:
39
.env.example
Normal file
39
.env.example
Normal file
@@ -0,0 +1,39 @@
|
||||
# System Environment
|
||||
NODE_ENV=development
|
||||
APP_VERSION=1.0.0
|
||||
GIT_COMMIT=local-dev
|
||||
|
||||
# Logging Configuration (pino)
|
||||
# Levels: fatal, error, warn, info, debug, trace, silent
|
||||
LOG_LEVEL=info
|
||||
|
||||
# Solana Connection Endpoints (for future integration)
|
||||
SOLANA_RPC_ENDPOINT=https://api.mainnet-beta.solana.com
|
||||
SOLANA_WSS_ENDPOINT=wss://api.mainnet-beta.solana.com
|
||||
|
||||
# PostgreSQL Database Connection
|
||||
# Format: postgres://username:password@host:port/database_name
|
||||
DATABASE_URL=postgres://postgres:postgres@localhost:5432/memecoin_bot
|
||||
|
||||
# InfluxDB Configuration
|
||||
INFLUXDB_URL=http://localhost:8086
|
||||
INFLUXDB_TOKEN=my-super-secret-auth-token
|
||||
INFLUXDB_ORG=my-org
|
||||
INFLUXDB_BUCKET=memecoin-bot-metrics
|
||||
|
||||
# Watcher Configuration
|
||||
# Comma-separated list of public keys to watch
|
||||
WATCHED_WALLETS=3yF9asA9B7G3Y1G7as78gHJKa7A,4yF9asA9B7G3Y1G7as78gHJKa7B
|
||||
|
||||
# Watcher Mode: real or mock
|
||||
WALLET_WATCHER_MODE=real
|
||||
|
||||
# Latency Simulation Configuration
|
||||
# Comma-separated list of latency values in milliseconds to simulate simultaneously
|
||||
# Supported values: 0, 1000, 3000, 5000, 10000
|
||||
LATENCY_SCENARIOS=0,1000,3000,5000,10000
|
||||
|
||||
# Simulation Accounting
|
||||
# Use SOL as the primary simulation accounting unit
|
||||
SIMULATION_STARTING_BALANCE_SOL=1.0
|
||||
SIMULATED_POSITION_SIZE_SOL=0.05
|
||||
6
.gitignore
vendored
Normal file
6
.gitignore
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.env
|
||||
*.log
|
||||
coverage/
|
||||
.DS_Store
|
||||
@@ -0,0 +1,183 @@
|
||||
import type { AST_NODE_TYPES, AST_TOKEN_TYPES } from '../ts-estree';
|
||||
import type { ClassicConfig } from './Config';
|
||||
import type { Linter } from './Linter';
|
||||
import type { ParserOptions } from './ParserOptions';
|
||||
import type { ReportDescriptorMessageData, RuleCreateFunction, RuleModule, SharedConfigurationSettings } from './Rule';
|
||||
/**
|
||||
* @deprecated Use `@typescript-eslint/rule-tester` instead.
|
||||
*/
|
||||
export interface ValidTestCase<Options extends readonly unknown[]> {
|
||||
/**
|
||||
* Code for the test case.
|
||||
*/
|
||||
readonly code: string;
|
||||
/**
|
||||
* Environments for the test case.
|
||||
*/
|
||||
readonly env?: Readonly<Linter.EnvironmentConfig>;
|
||||
/**
|
||||
* The fake filename for the test case. Useful for rules that make assertion about filenames.
|
||||
*/
|
||||
readonly filename?: string;
|
||||
/**
|
||||
* The additional global variables.
|
||||
*/
|
||||
readonly globals?: Readonly<Linter.GlobalsConfig>;
|
||||
/**
|
||||
* Name for the test case.
|
||||
*/
|
||||
readonly name?: string;
|
||||
/**
|
||||
* Run this case exclusively for debugging in supported test frameworks.
|
||||
*/
|
||||
readonly only?: boolean;
|
||||
/**
|
||||
* Options for the test case.
|
||||
*/
|
||||
readonly options?: Readonly<Options>;
|
||||
/**
|
||||
* The absolute path for the parser.
|
||||
*/
|
||||
readonly parser?: string;
|
||||
/**
|
||||
* Options for the parser.
|
||||
*/
|
||||
readonly parserOptions?: Readonly<ParserOptions>;
|
||||
/**
|
||||
* Settings for the test case.
|
||||
*/
|
||||
readonly settings?: Readonly<SharedConfigurationSettings>;
|
||||
}
|
||||
/**
|
||||
* @deprecated Use `@typescript-eslint/rule-tester` instead.
|
||||
*/
|
||||
export interface SuggestionOutput<MessageIds extends string> {
|
||||
/**
|
||||
* The data used to fill the message template.
|
||||
*/
|
||||
readonly data?: ReportDescriptorMessageData;
|
||||
/**
|
||||
* Reported message ID.
|
||||
*/
|
||||
readonly messageId: MessageIds;
|
||||
/**
|
||||
* NOTE: Suggestions will be applied as a stand-alone change, without triggering multi-pass fixes.
|
||||
* Each individual error has its own suggestion, so you have to show the correct, _isolated_ output for each suggestion.
|
||||
*/
|
||||
readonly output: string;
|
||||
}
|
||||
/**
|
||||
* @deprecated Use `@typescript-eslint/rule-tester` instead.
|
||||
*/
|
||||
export interface InvalidTestCase<MessageIds extends string, Options extends readonly unknown[]> extends ValidTestCase<Options> {
|
||||
/**
|
||||
* Expected errors.
|
||||
*/
|
||||
readonly errors: readonly TestCaseError<MessageIds>[];
|
||||
/**
|
||||
* The expected code after autofixes are applied. If set to `null`, the test runner will assert that no autofix is suggested.
|
||||
*/
|
||||
readonly output?: string | string[] | null;
|
||||
}
|
||||
/**
|
||||
* @deprecated Use `@typescript-eslint/rule-tester` instead.
|
||||
*/
|
||||
export interface TestCaseError<MessageIds extends string> {
|
||||
/**
|
||||
* The 1-based column number of the reported start location.
|
||||
*/
|
||||
readonly column?: number;
|
||||
/**
|
||||
* The data used to fill the message template.
|
||||
*/
|
||||
readonly data?: ReportDescriptorMessageData;
|
||||
/**
|
||||
* The 1-based column number of the reported end location.
|
||||
*/
|
||||
readonly endColumn?: number;
|
||||
/**
|
||||
* The 1-based line number of the reported end location.
|
||||
*/
|
||||
readonly endLine?: number;
|
||||
/**
|
||||
* The 1-based line number of the reported start location.
|
||||
*/
|
||||
readonly line?: number;
|
||||
/**
|
||||
* Reported message ID.
|
||||
*/
|
||||
readonly messageId: MessageIds;
|
||||
/**
|
||||
* Reported suggestions.
|
||||
*/
|
||||
readonly suggestions?: readonly SuggestionOutput<MessageIds>[] | null;
|
||||
/**
|
||||
* The type of the reported AST node.
|
||||
*/
|
||||
readonly type?: AST_NODE_TYPES | AST_TOKEN_TYPES;
|
||||
}
|
||||
/**
|
||||
* @param text a string describing the rule
|
||||
* @deprecated Use `@typescript-eslint/rule-tester` instead.
|
||||
*/
|
||||
export type RuleTesterTestFrameworkFunction = (text: string, callback: () => void) => void;
|
||||
/**
|
||||
* @deprecated Use `@typescript-eslint/rule-tester` instead.
|
||||
*/
|
||||
export interface RunTests<MessageIds extends string, Options extends readonly unknown[]> {
|
||||
readonly invalid: readonly InvalidTestCase<MessageIds, Options>[];
|
||||
readonly valid: readonly (string | ValidTestCase<Options>)[];
|
||||
}
|
||||
/**
|
||||
* @deprecated Use `@typescript-eslint/rule-tester` instead.
|
||||
*/
|
||||
export interface RuleTesterConfig extends ClassicConfig.Config {
|
||||
readonly parser: string;
|
||||
readonly parserOptions?: Readonly<ParserOptions>;
|
||||
}
|
||||
/**
|
||||
* @deprecated Use `@typescript-eslint/rule-tester` instead.
|
||||
*/
|
||||
declare class RuleTesterBase {
|
||||
/**
|
||||
* Creates a new instance of RuleTester.
|
||||
* @param testerConfig extra configuration for the tester
|
||||
*/
|
||||
constructor(testerConfig?: RuleTesterConfig);
|
||||
/**
|
||||
* Adds a new rule test to execute.
|
||||
* @param ruleName The name of the rule to run.
|
||||
* @param rule The rule to test.
|
||||
* @param tests The collection of tests to run.
|
||||
*/
|
||||
run<MessageIds extends string, Options extends readonly unknown[]>(ruleName: string, rule: RuleModule<MessageIds, Options>, tests: RunTests<MessageIds, Options>): void;
|
||||
/**
|
||||
* If you supply a value to this property, the rule tester will call this instead of using the version defined on
|
||||
* the global namespace.
|
||||
*/
|
||||
static get describe(): RuleTesterTestFrameworkFunction;
|
||||
static set describe(value: RuleTesterTestFrameworkFunction | undefined);
|
||||
/**
|
||||
* If you supply a value to this property, the rule tester will call this instead of using the version defined on
|
||||
* the global namespace.
|
||||
*/
|
||||
static get it(): RuleTesterTestFrameworkFunction;
|
||||
static set it(value: RuleTesterTestFrameworkFunction | undefined);
|
||||
/**
|
||||
* If you supply a value to this property, the rule tester will call this instead of using the version defined on
|
||||
* the global namespace.
|
||||
*/
|
||||
static get itOnly(): RuleTesterTestFrameworkFunction;
|
||||
static set itOnly(value: RuleTesterTestFrameworkFunction | undefined);
|
||||
/**
|
||||
* Define a rule for one particular run of tests.
|
||||
*/
|
||||
defineRule<MessageIds extends string, Options extends readonly unknown[]>(name: string, rule: RuleCreateFunction<MessageIds, Options> | RuleModule<MessageIds, Options>): void;
|
||||
}
|
||||
declare const RuleTester_base: typeof RuleTesterBase;
|
||||
/**
|
||||
* @deprecated Use `@typescript-eslint/rule-tester` instead.
|
||||
*/
|
||||
export declare class RuleTester extends RuleTester_base {
|
||||
}
|
||||
export {};
|
||||
@@ -0,0 +1,97 @@
|
||||
import { CommentDirectiveType } from "#enums/commentDirectiveType";
|
||||
import { LanguageVariant } from "#enums/languageVariant";
|
||||
import { RegularExpressionFlags } from "#enums/regularExpressionFlags";
|
||||
import { ScriptTarget } from "#enums/scriptTarget";
|
||||
import { SyntaxKind } from "#enums/syntaxKind";
|
||||
import { TokenFlags } from "#enums/tokenFlags";
|
||||
import type { JsxTokenSyntaxKind, KeywordSyntaxKind } from "./ast.ts";
|
||||
export type JSDocTokenKind = SyntaxKind.EndOfFile | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.GreaterThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.OpenParenToken | SyntaxKind.CloseParenToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.BacktickToken | SyntaxKind.HashToken | SyntaxKind.Unknown | KeywordSyntaxKind;
|
||||
export interface CommentDirective {
|
||||
range: {
|
||||
pos: number;
|
||||
end: number;
|
||||
};
|
||||
type: CommentDirectiveType;
|
||||
}
|
||||
export declare function tokenIsIdentifierOrKeyword(token: SyntaxKind): boolean;
|
||||
export declare function tokenIsIdentifierOrKeywordOrGreaterThan(token: SyntaxKind): boolean;
|
||||
export interface Scanner {
|
||||
getTokenFullStart(): number;
|
||||
getToken(): SyntaxKind;
|
||||
getTokenStart(): number;
|
||||
getTokenEnd(): number;
|
||||
getTokenText(): string;
|
||||
getTokenValue(): string;
|
||||
hasUnicodeEscape(): boolean;
|
||||
hasExtendedUnicodeEscape(): boolean;
|
||||
hasPrecedingLineBreak(): boolean;
|
||||
hasPrecedingJSDocComment(): boolean;
|
||||
hasPrecedingJSDocLeadingAsterisks(): boolean;
|
||||
hasPrecedingJSDocWithDeprecatedTag(): boolean;
|
||||
hasPrecedingJSDocWithSeeOrLink(): boolean;
|
||||
isIdentifier(): boolean;
|
||||
isReservedWord(): boolean;
|
||||
isUnterminated(): boolean;
|
||||
getNumericLiteralFlags(): TokenFlags;
|
||||
getCommentDirectives(): CommentDirective[] | undefined;
|
||||
getTokenFlags(): TokenFlags;
|
||||
reScanGreaterToken(): SyntaxKind;
|
||||
reScanSlashToken(): SyntaxKind;
|
||||
reScanAsteriskEqualsToken(): SyntaxKind;
|
||||
reScanTemplateToken(isTaggedTemplate: boolean): SyntaxKind;
|
||||
reScanTemplateHeadOrNoSubstitutionTemplate(): SyntaxKind;
|
||||
scanJsxIdentifier(): SyntaxKind;
|
||||
scanJsxAttributeValue(): SyntaxKind;
|
||||
reScanJsxAttributeValue(): SyntaxKind;
|
||||
reScanJsxToken(allowMultilineJsxText?: boolean): JsxTokenSyntaxKind;
|
||||
reScanLessThanToken(): SyntaxKind;
|
||||
reScanHashToken(): SyntaxKind;
|
||||
reScanQuestionToken(): SyntaxKind;
|
||||
reScanInvalidIdentifier(): SyntaxKind;
|
||||
scanJsxToken(): JsxTokenSyntaxKind;
|
||||
scanJsDocToken(): JSDocTokenKind;
|
||||
scanJSDocCommentTextToken(inBackticks: boolean): JSDocTokenKind | SyntaxKind.JSDocCommentTextToken;
|
||||
scan(): SyntaxKind;
|
||||
getText(): string;
|
||||
clearCommentDirectives(): void;
|
||||
setText(text: string | undefined, start?: number, length?: number): void;
|
||||
setLanguageVariant(variant: LanguageVariant): void;
|
||||
resetTokenState(pos: number): void;
|
||||
setSkipJsDocLeadingAsterisks(skip: boolean): void;
|
||||
lookAhead<T>(callback: () => T): T;
|
||||
scanRange<T>(start: number, length: number, callback: () => T): T;
|
||||
tryScan<T>(callback: () => T): T;
|
||||
}
|
||||
export declare const textToKeywordObj: Record<string, KeywordSyntaxKind>;
|
||||
export declare function isUnicodeIdentifierStart(code: number): boolean;
|
||||
export declare function tokenToString(t: SyntaxKind): string | undefined;
|
||||
export declare function stringToToken(s: string): SyntaxKind | undefined;
|
||||
export declare function characterCodeToRegularExpressionFlag(ch: number): RegularExpressionFlags | undefined;
|
||||
export declare function computeLineStarts(text: string): number[];
|
||||
export declare function isWhiteSpaceLike(ch: number): boolean;
|
||||
export declare function isWhiteSpaceSingleLine(ch: number): boolean;
|
||||
export declare function isLineBreak(ch: number): boolean;
|
||||
export declare function couldStartTrivia(text: string, pos: number): boolean;
|
||||
export declare function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean, stopAtComments?: boolean, inJSDoc?: boolean): number;
|
||||
export type CommentKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia;
|
||||
export interface CommentRange {
|
||||
pos: number;
|
||||
end: number;
|
||||
hasTrailingNewLine?: boolean;
|
||||
kind: CommentKind;
|
||||
}
|
||||
export declare function forEachLeadingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined;
|
||||
export declare function forEachLeadingCommentRange<U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined;
|
||||
export declare function forEachTrailingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined;
|
||||
export declare function forEachTrailingCommentRange<U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined;
|
||||
export declare function reduceEachLeadingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T, initial: U): U | undefined;
|
||||
export declare function reduceEachTrailingCommentRange<T, U>(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T, initial: U): U | undefined;
|
||||
export declare function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined;
|
||||
export declare function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined;
|
||||
export declare function getShebang(text: string): string | undefined;
|
||||
export declare function isIdentifierStart(ch: number, _languageVersion?: ScriptTarget): boolean;
|
||||
export declare function isIdentifierPart(ch: number, _languageVersion?: ScriptTarget, identifierVariant?: LanguageVariant): boolean;
|
||||
export declare function isIdentifierText(name: string, _languageVersion?: ScriptTarget, identifierVariant?: LanguageVariant): boolean;
|
||||
export declare function utf16EncodeAsString(codePoint: number): string;
|
||||
export declare function createScanner(skipTrivia: boolean, languageVariant?: LanguageVariant, textInitial?: string, start?: number, length?: number): Scanner;
|
||||
//# sourceMappingURL=scanner.d.ts.map
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
var proc = require('child_process')
|
||||
var os = require('os')
|
||||
var path = require('path')
|
||||
|
||||
if (!buildFromSource()) {
|
||||
proc.exec('node-gyp-build-test', function (err, stdout, stderr) {
|
||||
if (err) {
|
||||
if (verbose()) console.error(stderr)
|
||||
preinstall()
|
||||
}
|
||||
})
|
||||
} else {
|
||||
preinstall()
|
||||
}
|
||||
|
||||
function build () {
|
||||
var win32 = os.platform() === 'win32'
|
||||
var shell = win32
|
||||
var args = [win32 ? 'node-gyp.cmd' : 'node-gyp', 'rebuild']
|
||||
|
||||
try {
|
||||
var pkg = require('node-gyp/package.json')
|
||||
args = [
|
||||
process.execPath,
|
||||
path.join(require.resolve('node-gyp/package.json'), '..', typeof pkg.bin === 'string' ? pkg.bin : pkg.bin['node-gyp']),
|
||||
'rebuild'
|
||||
]
|
||||
shell = false
|
||||
} catch (_) {}
|
||||
|
||||
proc.spawn(args[0], args.slice(1), { stdio: 'inherit', shell, windowsHide: true }).on('exit', function (code) {
|
||||
if (code || !process.argv[3]) process.exit(code)
|
||||
exec(process.argv[3]).on('exit', function (code) {
|
||||
process.exit(code)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function preinstall () {
|
||||
if (!process.argv[2]) return build()
|
||||
exec(process.argv[2]).on('exit', function (code) {
|
||||
if (code) process.exit(code)
|
||||
build()
|
||||
})
|
||||
}
|
||||
|
||||
function exec (cmd) {
|
||||
if (process.platform !== 'win32') {
|
||||
var shell = os.platform() === 'android' ? 'sh' : true
|
||||
return proc.spawn(cmd, [], {
|
||||
shell,
|
||||
stdio: 'inherit'
|
||||
})
|
||||
}
|
||||
|
||||
return proc.spawn(cmd, [], {
|
||||
windowsVerbatimArguments: true,
|
||||
stdio: 'inherit',
|
||||
shell: true,
|
||||
windowsHide: true
|
||||
})
|
||||
}
|
||||
|
||||
function buildFromSource () {
|
||||
return hasFlag('--build-from-source') || process.env.npm_config_build_from_source === 'true'
|
||||
}
|
||||
|
||||
function verbose () {
|
||||
return hasFlag('--verbose') || process.env.npm_config_loglevel === 'verbose'
|
||||
}
|
||||
|
||||
// TODO (next major): remove in favor of env.npm_config_* which works since npm
|
||||
// 0.1.8 while npm_config_argv will stop working in npm 7. See npm/rfcs#90
|
||||
function hasFlag (flag) {
|
||||
if (!process.env.npm_config_argv) return false
|
||||
|
||||
try {
|
||||
return JSON.parse(process.env.npm_config_argv).original.indexOf(flag) !== -1
|
||||
} catch (_) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2018 base-x contributors
|
||||
Copyright (c) 2014-2018 The Bitcoin Core developers
|
||||
|
||||
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,182 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
const util_1 = require("../util");
|
||||
exports.default = (0, util_1.createRule)({
|
||||
name: 'no-inferrable-types',
|
||||
meta: {
|
||||
type: 'suggestion',
|
||||
docs: {
|
||||
description: 'Disallow explicit type declarations for variables or parameters initialized to a number, string, or boolean',
|
||||
recommended: 'stylistic',
|
||||
},
|
||||
fixable: 'code',
|
||||
messages: {
|
||||
noInferrableType: 'Type {{type}} trivially inferred from a {{type}} literal, remove type annotation.',
|
||||
},
|
||||
schema: [
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
ignoreParameters: {
|
||||
type: 'boolean',
|
||||
description: 'Whether to ignore function parameters.',
|
||||
},
|
||||
ignoreProperties: {
|
||||
type: 'boolean',
|
||||
description: 'Whether to ignore class properties.',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
defaultOptions: [
|
||||
{
|
||||
ignoreParameters: false,
|
||||
ignoreProperties: false,
|
||||
},
|
||||
],
|
||||
create(context, [{ ignoreParameters, ignoreProperties }]) {
|
||||
function isFunctionCall(init, callName) {
|
||||
const node = (0, util_1.skipChainExpression)(init);
|
||||
return (node.type === utils_1.AST_NODE_TYPES.CallExpression &&
|
||||
node.callee.type === utils_1.AST_NODE_TYPES.Identifier &&
|
||||
node.callee.name === callName);
|
||||
}
|
||||
function isLiteral(init, typeName) {
|
||||
return (init.type === utils_1.AST_NODE_TYPES.Literal && typeof init.value === typeName);
|
||||
}
|
||||
function isIdentifier(init, ...names) {
|
||||
return (init.type === utils_1.AST_NODE_TYPES.Identifier && names.includes(init.name));
|
||||
}
|
||||
function hasUnaryPrefix(init, ...operators) {
|
||||
return (init.type === utils_1.AST_NODE_TYPES.UnaryExpression &&
|
||||
operators.includes(init.operator));
|
||||
}
|
||||
const keywordMap = {
|
||||
[utils_1.AST_NODE_TYPES.TSBigIntKeyword]: 'bigint',
|
||||
[utils_1.AST_NODE_TYPES.TSBooleanKeyword]: 'boolean',
|
||||
[utils_1.AST_NODE_TYPES.TSNullKeyword]: 'null',
|
||||
[utils_1.AST_NODE_TYPES.TSNumberKeyword]: 'number',
|
||||
[utils_1.AST_NODE_TYPES.TSStringKeyword]: 'string',
|
||||
[utils_1.AST_NODE_TYPES.TSSymbolKeyword]: 'symbol',
|
||||
[utils_1.AST_NODE_TYPES.TSUndefinedKeyword]: 'undefined',
|
||||
};
|
||||
/**
|
||||
* Returns whether a node has an inferrable value or not
|
||||
*/
|
||||
function isInferrable(annotation, init) {
|
||||
switch (annotation.type) {
|
||||
case utils_1.AST_NODE_TYPES.TSBigIntKeyword: {
|
||||
// note that bigint cannot have + prefixed to it
|
||||
const unwrappedInit = hasUnaryPrefix(init, '-')
|
||||
? init.argument
|
||||
: init;
|
||||
return (isFunctionCall(unwrappedInit, 'BigInt') ||
|
||||
unwrappedInit.type === utils_1.AST_NODE_TYPES.Literal);
|
||||
}
|
||||
case utils_1.AST_NODE_TYPES.TSBooleanKeyword:
|
||||
return (hasUnaryPrefix(init, '!') ||
|
||||
isFunctionCall(init, 'Boolean') ||
|
||||
isLiteral(init, 'boolean'));
|
||||
case utils_1.AST_NODE_TYPES.TSNumberKeyword: {
|
||||
const unwrappedInit = hasUnaryPrefix(init, '+', '-')
|
||||
? init.argument
|
||||
: init;
|
||||
return (isIdentifier(unwrappedInit, 'Infinity', 'NaN') ||
|
||||
isFunctionCall(unwrappedInit, 'Number') ||
|
||||
isLiteral(unwrappedInit, 'number'));
|
||||
}
|
||||
case utils_1.AST_NODE_TYPES.TSNullKeyword:
|
||||
return init.type === utils_1.AST_NODE_TYPES.Literal && init.value == null;
|
||||
case utils_1.AST_NODE_TYPES.TSStringKeyword:
|
||||
return (isFunctionCall(init, 'String') ||
|
||||
isLiteral(init, 'string') ||
|
||||
init.type === utils_1.AST_NODE_TYPES.TemplateLiteral);
|
||||
case utils_1.AST_NODE_TYPES.TSSymbolKeyword:
|
||||
return isFunctionCall(init, 'Symbol');
|
||||
case utils_1.AST_NODE_TYPES.TSTypeReference: {
|
||||
if (annotation.typeName.type === utils_1.AST_NODE_TYPES.Identifier &&
|
||||
annotation.typeName.name === 'RegExp') {
|
||||
const isRegExpLiteral = init.type === utils_1.AST_NODE_TYPES.Literal &&
|
||||
init.value instanceof RegExp;
|
||||
const isRegExpNewCall = init.type === utils_1.AST_NODE_TYPES.NewExpression &&
|
||||
init.callee.type === utils_1.AST_NODE_TYPES.Identifier &&
|
||||
init.callee.name === 'RegExp';
|
||||
const isRegExpCall = isFunctionCall(init, 'RegExp');
|
||||
return isRegExpLiteral || isRegExpCall || isRegExpNewCall;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
case utils_1.AST_NODE_TYPES.TSUndefinedKeyword:
|
||||
return (hasUnaryPrefix(init, 'void') || isIdentifier(init, 'undefined'));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Reports an inferrable type declaration, if any
|
||||
*/
|
||||
function reportInferrableType(node, typeNode, initNode) {
|
||||
if (!typeNode || !initNode) {
|
||||
return;
|
||||
}
|
||||
if (!isInferrable(typeNode.typeAnnotation, initNode)) {
|
||||
return;
|
||||
}
|
||||
const type = typeNode.typeAnnotation.type === utils_1.AST_NODE_TYPES.TSTypeReference
|
||||
? // TODO - if we add more references
|
||||
'RegExp'
|
||||
: keywordMap[typeNode.typeAnnotation.type];
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'noInferrableType',
|
||||
data: {
|
||||
type,
|
||||
},
|
||||
*fix(fixer) {
|
||||
if ((node.type === utils_1.AST_NODE_TYPES.AssignmentPattern &&
|
||||
node.left.optional) ||
|
||||
(node.type === utils_1.AST_NODE_TYPES.PropertyDefinition && node.definite)) {
|
||||
yield fixer.remove((0, util_1.nullThrows)(context.sourceCode.getTokenBefore(typeNode), util_1.NullThrowsReasons.MissingToken('token before', 'type node')));
|
||||
}
|
||||
yield fixer.remove(typeNode);
|
||||
},
|
||||
});
|
||||
}
|
||||
function inferrableVariableVisitor(node) {
|
||||
reportInferrableType(node, node.id.typeAnnotation, node.init);
|
||||
}
|
||||
function inferrableParameterVisitor(node) {
|
||||
if (ignoreParameters) {
|
||||
return;
|
||||
}
|
||||
node.params.forEach(param => {
|
||||
if (param.type === utils_1.AST_NODE_TYPES.TSParameterProperty) {
|
||||
param = param.parameter;
|
||||
}
|
||||
if (param.type === utils_1.AST_NODE_TYPES.AssignmentPattern) {
|
||||
reportInferrableType(param, param.left.typeAnnotation, param.right);
|
||||
}
|
||||
});
|
||||
}
|
||||
function inferrablePropertyVisitor(node) {
|
||||
// We ignore `readonly` because of Microsoft/TypeScript#14416
|
||||
// Essentially a readonly property without a type
|
||||
// will result in its value being the type, leading to
|
||||
// compile errors if the type is stripped.
|
||||
if (ignoreProperties || node.readonly || node.optional) {
|
||||
return;
|
||||
}
|
||||
reportInferrableType(node, node.typeAnnotation, node.value);
|
||||
}
|
||||
return {
|
||||
AccessorProperty: inferrablePropertyVisitor,
|
||||
ArrowFunctionExpression: inferrableParameterVisitor,
|
||||
FunctionDeclaration: inferrableParameterVisitor,
|
||||
FunctionExpression: inferrableParameterVisitor,
|
||||
PropertyDefinition: inferrablePropertyVisitor,
|
||||
VariableDeclarator: inferrableVariableVisitor,
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,614 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.analyzeChain = analyzeChain;
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
const ts_api_utils_1 = require("ts-api-utils");
|
||||
const ts = __importStar(require("typescript"));
|
||||
const util_1 = require("../../util");
|
||||
const checkNullishAndReport_1 = require("./checkNullishAndReport");
|
||||
const compareNodes_1 = require("./compareNodes");
|
||||
const gatherLogicalOperands_1 = require("./gatherLogicalOperands");
|
||||
function includesType(parserServices, node, typeFlagIn) {
|
||||
const typeFlag = typeFlagIn | ts.TypeFlags.Any | ts.TypeFlags.Unknown;
|
||||
const types = (0, ts_api_utils_1.unionConstituents)(parserServices.getTypeAtLocation(node));
|
||||
for (const type of types) {
|
||||
if ((0, util_1.isTypeFlagSet)(type, typeFlag)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function isValidAndLastChainOperand(ComparisonValueType, comparisonType, parserServices) {
|
||||
const type = parserServices.getTypeAtLocation(ComparisonValueType);
|
||||
const ANY_UNKNOWN_FLAGS = ts.TypeFlags.Any | ts.TypeFlags.Unknown;
|
||||
const types = (0, ts_api_utils_1.unionConstituents)(type);
|
||||
switch (comparisonType) {
|
||||
case gatherLogicalOperands_1.ComparisonType.Equal: {
|
||||
const isNullish = types.some(t => (0, util_1.isTypeFlagSet)(t, ANY_UNKNOWN_FLAGS | ts.TypeFlags.Null | ts.TypeFlags.Undefined));
|
||||
return !isNullish;
|
||||
}
|
||||
case gatherLogicalOperands_1.ComparisonType.StrictEqual: {
|
||||
const isUndefined = types.some(t => (0, util_1.isTypeFlagSet)(t, ANY_UNKNOWN_FLAGS | ts.TypeFlags.Undefined));
|
||||
return !isUndefined;
|
||||
}
|
||||
case gatherLogicalOperands_1.ComparisonType.NotStrictEqual: {
|
||||
return types.every(t => (0, util_1.isTypeFlagSet)(t, ts.TypeFlags.Undefined));
|
||||
}
|
||||
case gatherLogicalOperands_1.ComparisonType.NotEqual: {
|
||||
return types.every(t => (0, util_1.isTypeFlagSet)(t, ts.TypeFlags.Undefined | ts.TypeFlags.Null));
|
||||
}
|
||||
}
|
||||
}
|
||||
function isValidOrLastChainOperand(ComparisonValueType, comparisonType, parserServices) {
|
||||
const type = parserServices.getTypeAtLocation(ComparisonValueType);
|
||||
const ANY_UNKNOWN_FLAGS = ts.TypeFlags.Any | ts.TypeFlags.Unknown;
|
||||
const types = (0, ts_api_utils_1.unionConstituents)(type);
|
||||
switch (comparisonType) {
|
||||
case gatherLogicalOperands_1.ComparisonType.NotEqual: {
|
||||
const isNullish = types.some(t => (0, util_1.isTypeFlagSet)(t, ANY_UNKNOWN_FLAGS | ts.TypeFlags.Null | ts.TypeFlags.Undefined));
|
||||
return !isNullish;
|
||||
}
|
||||
case gatherLogicalOperands_1.ComparisonType.NotStrictEqual: {
|
||||
const isUndefined = types.some(t => (0, util_1.isTypeFlagSet)(t, ANY_UNKNOWN_FLAGS | ts.TypeFlags.Undefined));
|
||||
return !isUndefined;
|
||||
}
|
||||
case gatherLogicalOperands_1.ComparisonType.Equal:
|
||||
return types.every(t => (0, util_1.isTypeFlagSet)(t, ts.TypeFlags.Undefined | ts.TypeFlags.Null));
|
||||
case gatherLogicalOperands_1.ComparisonType.StrictEqual:
|
||||
return types.every(t => (0, util_1.isTypeFlagSet)(t, ts.TypeFlags.Undefined));
|
||||
}
|
||||
}
|
||||
const analyzeAndChainOperand = (parserServices, operand, index, chain) => {
|
||||
switch (operand.comparisonType) {
|
||||
case gatherLogicalOperands_1.NullishComparisonType.Boolean:
|
||||
case gatherLogicalOperands_1.NullishComparisonType.NotEqualNullOrUndefined:
|
||||
return [operand];
|
||||
case gatherLogicalOperands_1.NullishComparisonType.NotStrictEqualNull: {
|
||||
// handle `x !== null && x !== undefined`
|
||||
const nextOperand = chain.at(index + 1);
|
||||
if (nextOperand?.comparisonType ===
|
||||
gatherLogicalOperands_1.NullishComparisonType.NotStrictEqualUndefined &&
|
||||
(0, compareNodes_1.compareNodes)(operand.comparedName, nextOperand.comparedName) ===
|
||||
compareNodes_1.NodeComparisonResult.Equal) {
|
||||
return [operand, nextOperand];
|
||||
}
|
||||
if (nextOperand &&
|
||||
!includesType(parserServices, operand.comparedName, ts.TypeFlags.Undefined)) {
|
||||
// we know the next operand is not an `undefined` check and that this
|
||||
// operand includes `undefined` - which means that making this an
|
||||
// optional chain would change the runtime behavior of the expression
|
||||
return [operand];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
case gatherLogicalOperands_1.NullishComparisonType.NotStrictEqualUndefined: {
|
||||
// handle `x !== undefined && x !== null`
|
||||
const nextOperand = chain.at(index + 1);
|
||||
if (nextOperand?.comparisonType ===
|
||||
gatherLogicalOperands_1.NullishComparisonType.NotStrictEqualNull &&
|
||||
(0, compareNodes_1.compareNodes)(operand.comparedName, nextOperand.comparedName) ===
|
||||
compareNodes_1.NodeComparisonResult.Equal) {
|
||||
return [operand, nextOperand];
|
||||
}
|
||||
if (includesType(parserServices, operand.comparedName, ts.TypeFlags.Null)) {
|
||||
// we know the next operand is not a `null` check and that this
|
||||
// operand includes `null` - which means that making this an
|
||||
// optional chain would change the runtime behavior of the expression
|
||||
return null;
|
||||
}
|
||||
return [operand];
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const analyzeOrChainOperand = (parserServices, operand, index, chain) => {
|
||||
switch (operand.comparisonType) {
|
||||
case gatherLogicalOperands_1.NullishComparisonType.NotBoolean:
|
||||
case gatherLogicalOperands_1.NullishComparisonType.EqualNullOrUndefined:
|
||||
return [operand];
|
||||
case gatherLogicalOperands_1.NullishComparisonType.StrictEqualNull: {
|
||||
// handle `x === null || x === undefined`
|
||||
const nextOperand = chain.at(index + 1);
|
||||
if (nextOperand?.comparisonType ===
|
||||
gatherLogicalOperands_1.NullishComparisonType.StrictEqualUndefined &&
|
||||
(0, compareNodes_1.compareNodes)(operand.comparedName, nextOperand.comparedName) ===
|
||||
compareNodes_1.NodeComparisonResult.Equal) {
|
||||
return [operand, nextOperand];
|
||||
}
|
||||
if (includesType(parserServices, operand.comparedName, ts.TypeFlags.Undefined)) {
|
||||
// we know the next operand is not an `undefined` check and that this
|
||||
// operand includes `undefined` - which means that making this an
|
||||
// optional chain would change the runtime behavior of the expression
|
||||
return null;
|
||||
}
|
||||
return [operand];
|
||||
}
|
||||
case gatherLogicalOperands_1.NullishComparisonType.StrictEqualUndefined: {
|
||||
// handle `x === undefined || x === null`
|
||||
const nextOperand = chain.at(index + 1);
|
||||
if (nextOperand?.comparisonType === gatherLogicalOperands_1.NullishComparisonType.StrictEqualNull &&
|
||||
(0, compareNodes_1.compareNodes)(operand.comparedName, nextOperand.comparedName) ===
|
||||
compareNodes_1.NodeComparisonResult.Equal) {
|
||||
return [operand, nextOperand];
|
||||
}
|
||||
if (includesType(parserServices, operand.comparedName, ts.TypeFlags.Null)) {
|
||||
// we know the next operand is not a `null` check and that this
|
||||
// operand includes `null` - which means that making this an
|
||||
// optional chain would change the runtime behavior of the expression
|
||||
return null;
|
||||
}
|
||||
return [operand];
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const resolveOperandSubset = (previousOperand, lastChainOperand) => {
|
||||
const isNameSubset = (0, compareNodes_1.compareNodes)(previousOperand.comparedName, lastChainOperand.comparedName) === compareNodes_1.NodeComparisonResult.Subset;
|
||||
if (lastChainOperand.yoda !== gatherLogicalOperands_1.Yoda.Unknown) {
|
||||
return {
|
||||
comparedName: lastChainOperand.comparedName,
|
||||
comparisonValue: lastChainOperand.comparisonValue,
|
||||
isSubset: isNameSubset,
|
||||
isYoda: lastChainOperand.yoda === gatherLogicalOperands_1.Yoda.Yes,
|
||||
};
|
||||
}
|
||||
const isValueSubset = (0, compareNodes_1.compareNodes)(previousOperand.comparedName, lastChainOperand.comparisonValue) === compareNodes_1.NodeComparisonResult.Subset;
|
||||
if (isNameSubset && !isValueSubset) {
|
||||
return {
|
||||
comparedName: lastChainOperand.comparedName,
|
||||
comparisonValue: lastChainOperand.comparisonValue,
|
||||
isSubset: true,
|
||||
isYoda: false,
|
||||
};
|
||||
}
|
||||
if (!isNameSubset && isValueSubset) {
|
||||
return {
|
||||
comparedName: lastChainOperand.comparisonValue,
|
||||
comparisonValue: lastChainOperand.comparedName,
|
||||
isSubset: true,
|
||||
isYoda: true,
|
||||
};
|
||||
}
|
||||
return {
|
||||
comparedName: lastChainOperand.comparisonValue,
|
||||
comparisonValue: lastChainOperand.comparisonValue,
|
||||
isSubset: false,
|
||||
isYoda: true,
|
||||
};
|
||||
};
|
||||
/**
|
||||
* Returns the range that needs to be reported from the chain.
|
||||
* @param chain The chain of logical expressions.
|
||||
* @param boundary The boundary range that the range to report cannot fall outside.
|
||||
* @param sourceCode The source code to get tokens.
|
||||
* @returns The range to report.
|
||||
*/
|
||||
function getReportRange(chain, boundary, sourceCode) {
|
||||
const leftNode = chain[0].node;
|
||||
const rightNode = chain[chain.length - 1].node;
|
||||
let leftMost = (0, util_1.nullThrows)(sourceCode.getFirstToken(leftNode), util_1.NullThrowsReasons.MissingToken('any token', leftNode.type));
|
||||
let rightMost = (0, util_1.nullThrows)(sourceCode.getLastToken(rightNode), util_1.NullThrowsReasons.MissingToken('any token', rightNode.type));
|
||||
while (leftMost.range[0] > boundary[0]) {
|
||||
const token = sourceCode.getTokenBefore(leftMost);
|
||||
if (!token || !(0, util_1.isOpeningParenToken)(token) || token.range[0] < boundary[0]) {
|
||||
break;
|
||||
}
|
||||
leftMost = token;
|
||||
}
|
||||
while (rightMost.range[1] < boundary[1]) {
|
||||
const token = sourceCode.getTokenAfter(rightMost);
|
||||
if (!token || !(0, util_1.isClosingParenToken)(token) || token.range[1] > boundary[1]) {
|
||||
break;
|
||||
}
|
||||
rightMost = token;
|
||||
}
|
||||
return [leftMost.range[0], rightMost.range[1]];
|
||||
}
|
||||
function getReportDescriptor(sourceCode, parserServices, node, operator, options, subChain, lastChain) {
|
||||
const chain = lastChain ? [...subChain, lastChain] : subChain;
|
||||
const lastOperand = chain[chain.length - 1];
|
||||
let useSuggestionFixer;
|
||||
if (options.allowPotentiallyUnsafeFixesThatModifyTheReturnTypeIKnowWhatImDoing ===
|
||||
true) {
|
||||
// user has opted-in to the unsafe behavior
|
||||
useSuggestionFixer = false;
|
||||
}
|
||||
// optional chain specifically will union `undefined` into the final type
|
||||
// so we need to make sure that there is at least one operand that includes
|
||||
// `undefined`, or else we're going to change the final type - which is
|
||||
// unsafe and might cause downstream type errors.
|
||||
else if (lastChain) {
|
||||
useSuggestionFixer = true;
|
||||
}
|
||||
else if (lastOperand.comparisonType === gatherLogicalOperands_1.NullishComparisonType.EqualNullOrUndefined ||
|
||||
lastOperand.comparisonType ===
|
||||
gatherLogicalOperands_1.NullishComparisonType.NotEqualNullOrUndefined ||
|
||||
lastOperand.comparisonType === gatherLogicalOperands_1.NullishComparisonType.StrictEqualUndefined ||
|
||||
lastOperand.comparisonType ===
|
||||
gatherLogicalOperands_1.NullishComparisonType.NotStrictEqualUndefined ||
|
||||
(operator === '||' &&
|
||||
lastOperand.comparisonType === gatherLogicalOperands_1.NullishComparisonType.NotBoolean)) {
|
||||
// we know the last operand is an equality check - so the change in types
|
||||
// DOES NOT matter and will not change the runtime result or cause a type
|
||||
// check error
|
||||
useSuggestionFixer = false;
|
||||
}
|
||||
else {
|
||||
useSuggestionFixer = true;
|
||||
for (const operand of chain) {
|
||||
if (includesType(parserServices, operand.node, ts.TypeFlags.Undefined)) {
|
||||
useSuggestionFixer = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// TODO - we could further reduce the false-positive rate of this check by
|
||||
// checking for cases where the change in types don't matter like
|
||||
// the test location of an if/while/etc statement.
|
||||
// but it's quite complex to do this without false-negatives, so
|
||||
// for now we'll just be over-eager with our matching.
|
||||
//
|
||||
// it's MUCH better to false-positive here and only provide a
|
||||
// suggestion fixer, rather than false-negative and autofix to
|
||||
// broken code.
|
||||
}
|
||||
// In its most naive form we could just slap `?.` for every single part of the
|
||||
// chain. However this would be undesirable because it'd create unnecessary
|
||||
// conditions in the user's code where there were none before - and it would
|
||||
// cause errors with rules like our `no-unnecessary-condition`.
|
||||
//
|
||||
// Instead we want to include the minimum number of `?.` required to correctly
|
||||
// unify the code into a single chain. Naively you might think that we can
|
||||
// just take the final operand add `?.` after the locations from the previous
|
||||
// operands - however this won't be correct either because earlier operands
|
||||
// can include a necessary `?.` that's not needed or included in a later
|
||||
// operand.
|
||||
//
|
||||
// So instead what we need to do is to start at the first operand and
|
||||
// iteratively diff it against the next operand, and add the difference to the
|
||||
// first operand.
|
||||
//
|
||||
// eg
|
||||
// `foo && foo.bar && foo.bar.baz?.bam && foo.bar.baz.bam()`
|
||||
// 1) `foo`
|
||||
// 2) diff(`foo`, `foo.bar`) = `.bar`
|
||||
// 3) result = `foo?.bar`
|
||||
// 4) diff(`foo.bar`, `foo.bar.baz?.bam`) = `.baz?.bam`
|
||||
// 5) result = `foo?.bar?.baz?.bam`
|
||||
// 6) diff(`foo.bar.baz?.bam`, `foo.bar.baz.bam()`) = `()`
|
||||
// 7) result = `foo?.bar?.baz?.bam?.()`
|
||||
const parts = [];
|
||||
for (const current of chain) {
|
||||
const nextOperand = flattenChainExpression(sourceCode, current.comparedName);
|
||||
const diff = nextOperand.slice(parts.length);
|
||||
if (diff.length > 0) {
|
||||
if (parts.length > 0) {
|
||||
// we need to make the first operand of the diff optional so it matches the
|
||||
// logic before merging
|
||||
// foo.bar && foo.bar.baz
|
||||
// diff = .baz
|
||||
// result = foo.bar?.baz
|
||||
diff[0].optional = true;
|
||||
}
|
||||
parts.push(...diff);
|
||||
}
|
||||
}
|
||||
let newCode = parts
|
||||
.map(part => {
|
||||
let str = '';
|
||||
if (part.optional) {
|
||||
str += '?.';
|
||||
}
|
||||
else {
|
||||
if (part.nonNull) {
|
||||
str += '!';
|
||||
}
|
||||
if (part.requiresDot) {
|
||||
str += '.';
|
||||
}
|
||||
}
|
||||
if (part.precedence !== util_1.OperatorPrecedence.Invalid &&
|
||||
part.precedence < util_1.OperatorPrecedence.Member) {
|
||||
str += `(${part.text})`;
|
||||
}
|
||||
else {
|
||||
str += part.text;
|
||||
}
|
||||
return str;
|
||||
})
|
||||
.join('');
|
||||
if (lastOperand.node.type === utils_1.AST_NODE_TYPES.BinaryExpression) {
|
||||
// retain the ending comparison for cases like
|
||||
// x && x.a != null
|
||||
// x && typeof x.a !== 'undefined'
|
||||
const operator = lastOperand.node.operator;
|
||||
const { left, right } = (() => {
|
||||
if (lastOperand.isYoda) {
|
||||
const unaryOperator = lastOperand.node.right.type === utils_1.AST_NODE_TYPES.UnaryExpression
|
||||
? `${lastOperand.node.right.operator} `
|
||||
: '';
|
||||
return {
|
||||
left: sourceCode.getText(lastOperand.node.left),
|
||||
right: unaryOperator + newCode,
|
||||
};
|
||||
}
|
||||
const unaryOperator = lastOperand.node.left.type === utils_1.AST_NODE_TYPES.UnaryExpression
|
||||
? `${lastOperand.node.left.operator} `
|
||||
: '';
|
||||
return {
|
||||
left: unaryOperator + newCode,
|
||||
right: sourceCode.getText(lastOperand.node.right),
|
||||
};
|
||||
})();
|
||||
newCode = `${left} ${operator} ${right}`;
|
||||
}
|
||||
else if (lastOperand.comparisonType === gatherLogicalOperands_1.NullishComparisonType.NotBoolean) {
|
||||
newCode = `!${newCode}`;
|
||||
}
|
||||
const reportRange = getReportRange(chain, node.range, sourceCode);
|
||||
const fix = fixer => {
|
||||
let unclosedParens = 0;
|
||||
const tokensInRange = sourceCode.getTokens(node, {
|
||||
filter: token => token.range[0] >= reportRange[0] && token.range[1] <= reportRange[1],
|
||||
});
|
||||
for (const token of tokensInRange) {
|
||||
if ((0, util_1.isOpeningParenToken)(token)) {
|
||||
unclosedParens++;
|
||||
}
|
||||
else if ((0, util_1.isClosingParenToken)(token)) {
|
||||
unclosedParens--;
|
||||
}
|
||||
}
|
||||
if (unclosedParens > 0 && reportRange[1] < node.range[1]) {
|
||||
const openParensOutsideRange = [];
|
||||
const unmatchedCloseParens = [];
|
||||
const tokensOutRange = sourceCode.getTokens(node, {
|
||||
filter: token => token.range[1] > reportRange[1],
|
||||
});
|
||||
for (const token of tokensOutRange) {
|
||||
if ((0, util_1.isOpeningParenToken)(token)) {
|
||||
openParensOutsideRange.push(token.range[0]);
|
||||
}
|
||||
if ((0, util_1.isClosingParenToken)(token)) {
|
||||
if (openParensOutsideRange.length > 0) {
|
||||
openParensOutsideRange.pop();
|
||||
}
|
||||
else {
|
||||
unmatchedCloseParens.push(token.range[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let leftCode = sourceCode.getText(node);
|
||||
unmatchedCloseParens.reverse();
|
||||
for (const unmatchedParenIndex of unmatchedCloseParens) {
|
||||
leftCode =
|
||||
leftCode.slice(0, unmatchedParenIndex) +
|
||||
leftCode.slice(unmatchedParenIndex + 1);
|
||||
}
|
||||
leftCode = leftCode.slice(reportRange[1]);
|
||||
return fixer.replaceTextRange(node.range, newCode + leftCode);
|
||||
}
|
||||
return fixer.replaceTextRange(reportRange, newCode);
|
||||
};
|
||||
return {
|
||||
loc: {
|
||||
end: sourceCode.getLocFromIndex(reportRange[1]),
|
||||
start: sourceCode.getLocFromIndex(reportRange[0]),
|
||||
},
|
||||
messageId: 'preferOptionalChain',
|
||||
...(0, util_1.getFixOrSuggest)({
|
||||
fixOrSuggest: useSuggestionFixer ? 'suggest' : 'fix',
|
||||
suggestion: {
|
||||
fix,
|
||||
messageId: 'optionalChainSuggest',
|
||||
},
|
||||
}),
|
||||
};
|
||||
function flattenChainExpression(sourceCode, node) {
|
||||
switch (node.type) {
|
||||
case utils_1.AST_NODE_TYPES.ChainExpression:
|
||||
return flattenChainExpression(sourceCode, node.expression);
|
||||
case utils_1.AST_NODE_TYPES.CallExpression: {
|
||||
const argumentsText = (() => {
|
||||
const closingParenToken = (0, util_1.nullThrows)(sourceCode.getLastToken(node), util_1.NullThrowsReasons.MissingToken('closing parenthesis', node.type));
|
||||
const openingParenToken = (0, util_1.nullThrows)(sourceCode.getFirstTokenBetween(node.typeArguments ?? node.callee, closingParenToken, util_1.isOpeningParenToken), util_1.NullThrowsReasons.MissingToken('opening parenthesis', node.type));
|
||||
return sourceCode.text.substring(openingParenToken.range[0], closingParenToken.range[1]);
|
||||
})();
|
||||
const typeArgumentsText = (() => {
|
||||
if (node.typeArguments == null) {
|
||||
return '';
|
||||
}
|
||||
return sourceCode.getText(node.typeArguments);
|
||||
})();
|
||||
return [
|
||||
...flattenChainExpression(sourceCode, node.callee),
|
||||
{
|
||||
nonNull: false,
|
||||
optional: node.optional,
|
||||
// no precedence for this
|
||||
precedence: util_1.OperatorPrecedence.Invalid,
|
||||
requiresDot: false,
|
||||
text: typeArgumentsText + argumentsText,
|
||||
},
|
||||
];
|
||||
}
|
||||
case utils_1.AST_NODE_TYPES.MemberExpression: {
|
||||
const propertyText = sourceCode.getText(node.property);
|
||||
return [
|
||||
...flattenChainExpression(sourceCode, node.object),
|
||||
{
|
||||
nonNull: node.object.type === utils_1.AST_NODE_TYPES.TSNonNullExpression,
|
||||
optional: node.optional,
|
||||
precedence: node.computed
|
||||
? // computed is already wrapped in [] so no need to wrap in () as well
|
||||
util_1.OperatorPrecedence.Invalid
|
||||
: (0, util_1.getOperatorPrecedenceForNode)(node.property),
|
||||
requiresDot: !node.computed,
|
||||
text: node.computed ? `[${propertyText}]` : propertyText,
|
||||
},
|
||||
];
|
||||
}
|
||||
case utils_1.AST_NODE_TYPES.TSNonNullExpression:
|
||||
return flattenChainExpression(sourceCode, node.expression);
|
||||
default:
|
||||
return [
|
||||
{
|
||||
nonNull: false,
|
||||
optional: false,
|
||||
precedence: (0, util_1.getOperatorPrecedenceForNode)(node),
|
||||
requiresDot: false,
|
||||
text: sourceCode.getText(node),
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
function analyzeChain(context, parserServices, options, node, operator, chain, lastChainOperand) {
|
||||
// need at least 2 operands in a chain for it to be a chain
|
||||
if (chain.length + (lastChainOperand ? 1 : 0) <= 1 ||
|
||||
/* istanbul ignore next -- previous checks make this unreachable, but keep it for exhaustiveness check */
|
||||
operator === '??') {
|
||||
return;
|
||||
}
|
||||
const analyzeOperand = (() => {
|
||||
switch (operator) {
|
||||
case '&&':
|
||||
return analyzeAndChainOperand;
|
||||
case '||':
|
||||
return analyzeOrChainOperand;
|
||||
}
|
||||
})();
|
||||
// Things like x !== null && x !== undefined have two nodes, but they are
|
||||
// one logical unit here, so we'll allow them to be grouped.
|
||||
let subChain = [];
|
||||
let lastChain = undefined;
|
||||
const maybeReportThenReset = (newChainSeed) => {
|
||||
if (subChain.length + (lastChain ? 1 : 0) > 1) {
|
||||
const subChainFlat = subChain.flat();
|
||||
const maybeNullishNodes = lastChain
|
||||
? subChainFlat.map(({ node }) => node)
|
||||
: subChainFlat.slice(0, -1).map(({ node }) => node);
|
||||
(0, checkNullishAndReport_1.checkNullishAndReport)(context, parserServices, options, maybeNullishNodes, getReportDescriptor(context.sourceCode, parserServices, node, operator, options, subChainFlat, lastChain));
|
||||
}
|
||||
// we've reached the end of a chain of logical expressions
|
||||
// i.e. the current operand doesn't belong to the previous chain.
|
||||
//
|
||||
// we don't want to throw away the current operand otherwise we will skip it
|
||||
// and that can cause us to miss chains. So instead we seed the new chain
|
||||
// with the current operand
|
||||
//
|
||||
// eg this means we can catch cases like:
|
||||
// unrelated != null && foo != null && foo.bar != null;
|
||||
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ first "chain"
|
||||
// ^^^^^^^^^^^ newChainSeed
|
||||
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ second chain
|
||||
subChain = newChainSeed ? [newChainSeed] : [];
|
||||
lastChain = undefined;
|
||||
};
|
||||
for (let i = 0; i < chain.length; i += 1) {
|
||||
const lastOperand = subChain.flat().at(-1);
|
||||
const operand = chain[i];
|
||||
const validatedOperands = analyzeOperand(parserServices, operand, i, chain);
|
||||
if (!validatedOperands) {
|
||||
// TODO - #7170
|
||||
// check if the name is a superset/equal - if it is, then it likely
|
||||
// intended to be part of the chain and something we should include in the
|
||||
// report, eg
|
||||
// foo == null || foo.bar;
|
||||
// ^^^^^^^^^^^ valid OR chain
|
||||
// ^^^^^^^ invalid OR chain logical, but still part of
|
||||
// the chain for combination purposes
|
||||
if (lastOperand) {
|
||||
const comparisonResult = (0, compareNodes_1.compareNodes)(lastOperand.comparedName, operand.comparedName);
|
||||
switch (operand.comparisonType) {
|
||||
case gatherLogicalOperands_1.NullishComparisonType.StrictEqualUndefined:
|
||||
case gatherLogicalOperands_1.NullishComparisonType.NotStrictEqualUndefined: {
|
||||
if (comparisonResult === compareNodes_1.NodeComparisonResult.Subset) {
|
||||
lastChain = operand;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
maybeReportThenReset();
|
||||
continue;
|
||||
}
|
||||
// in case multiple operands were consumed - make sure to correctly increment the index
|
||||
i += validatedOperands.length - 1;
|
||||
const currentOperand = validatedOperands[0];
|
||||
if (lastOperand) {
|
||||
const comparisonResult = (0, compareNodes_1.compareNodes)(lastOperand.comparedName,
|
||||
// purposely inspect and push the last operand because the prior operands don't matter
|
||||
// this also means we won't false-positive in cases like
|
||||
// foo !== null && foo !== undefined
|
||||
validatedOperands[validatedOperands.length - 1].comparedName);
|
||||
if (comparisonResult === compareNodes_1.NodeComparisonResult.Subset) {
|
||||
// the operands are comparable, so we can continue searching
|
||||
subChain.push(currentOperand);
|
||||
}
|
||||
else if (comparisonResult === compareNodes_1.NodeComparisonResult.Invalid) {
|
||||
maybeReportThenReset(validatedOperands);
|
||||
}
|
||||
else {
|
||||
// purposely don't push this case because the node is a no-op and if
|
||||
// we consider it then we might report on things like
|
||||
// foo && foo
|
||||
}
|
||||
}
|
||||
else {
|
||||
subChain.push(currentOperand);
|
||||
}
|
||||
}
|
||||
const lastOperand = subChain.flat().at(-1);
|
||||
if (lastOperand && lastChainOperand) {
|
||||
const isValidLastChainOperand = operator === '&&'
|
||||
? isValidAndLastChainOperand
|
||||
: isValidOrLastChainOperand;
|
||||
const { comparedName, comparisonValue, isSubset, isYoda } = resolveOperandSubset(lastOperand, lastChainOperand);
|
||||
if (isSubset &&
|
||||
isValidLastChainOperand(comparisonValue, lastChainOperand.comparisonType, parserServices)) {
|
||||
lastChain = {
|
||||
...lastChainOperand,
|
||||
comparedName,
|
||||
comparisonValue,
|
||||
isYoda,
|
||||
};
|
||||
}
|
||||
}
|
||||
// check the leftovers
|
||||
maybeReportThenReset();
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint';
|
||||
export default _default;
|
||||
/**
|
||||
* Contains all of `stylistic`, along with additional stylistic rules that require type information.
|
||||
* @see {@link https://typescript-eslint.io/users/configs#stylistic-type-checked}
|
||||
*/
|
||||
declare function _default(plugin: FlatConfig.Plugin, parser: FlatConfig.Parser): FlatConfig.ConfigArray;
|
||||
@@ -0,0 +1,270 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isStaticMemberAccessOfValue = exports.MemberNameType = void 0;
|
||||
exports.isDefinitionFile = isDefinitionFile;
|
||||
exports.upperCaseFirst = upperCaseFirst;
|
||||
exports.arrayGroupByToMap = arrayGroupByToMap;
|
||||
exports.arraysAreEqual = arraysAreEqual;
|
||||
exports.findFirstResult = findFirstResult;
|
||||
exports.getNameFromIndexSignature = getNameFromIndexSignature;
|
||||
exports.getNameFromMember = getNameFromMember;
|
||||
exports.getEnumNames = getEnumNames;
|
||||
exports.formatWordList = formatWordList;
|
||||
exports.findLastIndex = findLastIndex;
|
||||
exports.typeNodeRequiresParentheses = typeNodeRequiresParentheses;
|
||||
exports.isRestParameterDeclaration = isRestParameterDeclaration;
|
||||
exports.isParenlessArrowFunction = isParenlessArrowFunction;
|
||||
exports.getStaticMemberAccessValue = getStaticMemberAccessValue;
|
||||
const type_utils_1 = require("@typescript-eslint/type-utils");
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
const ts = __importStar(require("typescript"));
|
||||
const astUtils_1 = require("./astUtils");
|
||||
const DEFINITION_EXTENSIONS = [
|
||||
ts.Extension.Dts,
|
||||
ts.Extension.Dcts,
|
||||
ts.Extension.Dmts,
|
||||
];
|
||||
/**
|
||||
* Check if the context file name is *.d.ts or *.d.tsx
|
||||
*/
|
||||
function isDefinitionFile(fileName) {
|
||||
const lowerFileName = fileName.toLowerCase();
|
||||
for (const definitionExt of DEFINITION_EXTENSIONS) {
|
||||
if (lowerFileName.endsWith(definitionExt)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return /\.d\.(ts|cts|mts|.*\.ts)$/.test(lowerFileName);
|
||||
}
|
||||
/**
|
||||
* Upper cases the first character or the string
|
||||
*/
|
||||
function upperCaseFirst(str) {
|
||||
return str[0].toUpperCase() + str.slice(1);
|
||||
}
|
||||
function arrayGroupByToMap(array, getKey) {
|
||||
const groups = new Map();
|
||||
for (const item of array) {
|
||||
const key = getKey(item);
|
||||
const existing = groups.get(key);
|
||||
if (existing) {
|
||||
existing.push(item);
|
||||
}
|
||||
else {
|
||||
groups.set(key, [item]);
|
||||
}
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
function arraysAreEqual(a, b, eq) {
|
||||
return (a === b ||
|
||||
(a != null && a.length === b?.length && a.every((x, idx) => eq(x, b[idx]))));
|
||||
}
|
||||
/** Returns the first non-`undefined` result. */
|
||||
function findFirstResult(inputs, getResult) {
|
||||
for (const element of inputs) {
|
||||
const result = getResult(element);
|
||||
// eslint-disable-next-line @typescript-eslint/internal/eqeq-nullish
|
||||
if (result !== undefined) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
/**
|
||||
* Gets a string representation of the name of the index signature.
|
||||
*/
|
||||
function getNameFromIndexSignature(node) {
|
||||
const propName = node.parameters.find((parameter) => parameter.type === utils_1.AST_NODE_TYPES.Identifier);
|
||||
return propName ? propName.name : '(index signature)';
|
||||
}
|
||||
var MemberNameType;
|
||||
(function (MemberNameType) {
|
||||
MemberNameType[MemberNameType["Private"] = 1] = "Private";
|
||||
MemberNameType[MemberNameType["Quoted"] = 2] = "Quoted";
|
||||
MemberNameType[MemberNameType["Normal"] = 3] = "Normal";
|
||||
MemberNameType[MemberNameType["Expression"] = 4] = "Expression";
|
||||
})(MemberNameType || (exports.MemberNameType = MemberNameType = {}));
|
||||
/**
|
||||
* Gets a string name representation of the name of the given MethodDefinition
|
||||
* or PropertyDefinition node, with handling for computed property names.
|
||||
*/
|
||||
function getNameFromMember(member, sourceCode) {
|
||||
if (member.key.type === utils_1.AST_NODE_TYPES.Identifier) {
|
||||
return {
|
||||
name: member.key.name,
|
||||
type: MemberNameType.Normal,
|
||||
};
|
||||
}
|
||||
if (member.key.type === utils_1.AST_NODE_TYPES.PrivateIdentifier) {
|
||||
return {
|
||||
name: `#${member.key.name}`,
|
||||
type: MemberNameType.Private,
|
||||
};
|
||||
}
|
||||
if (member.key.type === utils_1.AST_NODE_TYPES.Literal) {
|
||||
const name = `${member.key.value}`;
|
||||
if ((0, type_utils_1.requiresQuoting)(name)) {
|
||||
return {
|
||||
name: `"${name}"`,
|
||||
type: MemberNameType.Quoted,
|
||||
};
|
||||
}
|
||||
return {
|
||||
name,
|
||||
type: MemberNameType.Normal,
|
||||
};
|
||||
}
|
||||
return {
|
||||
name: sourceCode.text.slice(...member.key.range),
|
||||
type: MemberNameType.Expression,
|
||||
};
|
||||
}
|
||||
function getEnumNames(myEnum) {
|
||||
return Object.keys(myEnum).filter(x => isNaN(Number(x)));
|
||||
}
|
||||
/**
|
||||
* Given an array of words, returns an English-friendly concatenation, separated with commas, with
|
||||
* the `and` clause inserted before the last item.
|
||||
*
|
||||
* Example: ['foo', 'bar', 'baz' ] returns the string "foo, bar, and baz".
|
||||
*/
|
||||
function formatWordList(words) {
|
||||
if (!words.length) {
|
||||
return '';
|
||||
}
|
||||
if (words.length === 1) {
|
||||
return words[0];
|
||||
}
|
||||
return [words.slice(0, -1).join(', '), words.slice(-1)[0]].join(' and ');
|
||||
}
|
||||
/**
|
||||
* Iterates the array in reverse and returns the index of the first element it
|
||||
* finds which passes the predicate function.
|
||||
*
|
||||
* @returns Returns the index of the element if it finds it or -1 otherwise.
|
||||
*/
|
||||
function findLastIndex(members, predicate) {
|
||||
let idx = members.length - 1;
|
||||
while (idx >= 0) {
|
||||
const valid = predicate(members[idx]);
|
||||
if (valid) {
|
||||
return idx;
|
||||
}
|
||||
idx--;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
function typeNodeRequiresParentheses(node, text) {
|
||||
return (node.type === utils_1.AST_NODE_TYPES.TSFunctionType ||
|
||||
node.type === utils_1.AST_NODE_TYPES.TSConstructorType ||
|
||||
node.type === utils_1.AST_NODE_TYPES.TSConditionalType ||
|
||||
(node.type === utils_1.AST_NODE_TYPES.TSUnionType && text.startsWith('|')) ||
|
||||
(node.type === utils_1.AST_NODE_TYPES.TSIntersectionType && text.startsWith('&')));
|
||||
}
|
||||
function isRestParameterDeclaration(decl) {
|
||||
return ts.isParameter(decl) && decl.dotDotDotToken != null;
|
||||
}
|
||||
function isParenlessArrowFunction(node, sourceCode) {
|
||||
return (node.params.length === 1 && !(0, astUtils_1.isParenthesized)(node.params[0], sourceCode));
|
||||
}
|
||||
/**
|
||||
* Gets a member being accessed or declared if its value can be determined statically, and
|
||||
* resolves it to the string or symbol value that will be used as the actual member
|
||||
* access key at runtime. Otherwise, returns `undefined`.
|
||||
*
|
||||
* ```ts
|
||||
* x.member // returns 'member'
|
||||
* ^^^^^^^^
|
||||
*
|
||||
* x?.member // returns 'member' (optional chaining is treated the same)
|
||||
* ^^^^^^^^^
|
||||
*
|
||||
* x['value'] // returns 'value'
|
||||
* ^^^^^^^^^^
|
||||
*
|
||||
* x[Math.random()] // returns undefined (not a static value)
|
||||
* ^^^^^^^^^^^^^^^^
|
||||
*
|
||||
* arr[0] // returns '0' (NOT 0)
|
||||
* ^^^^^^
|
||||
*
|
||||
* arr[0n] // returns '0' (NOT 0n)
|
||||
* ^^^^^^^
|
||||
*
|
||||
* const s = Symbol.for('symbolName')
|
||||
* x[s] // returns `Symbol.for('symbolName')` (since it's a static/global symbol)
|
||||
* ^^^^
|
||||
*
|
||||
* const us = Symbol('symbolName')
|
||||
* x[us] // returns undefined (since it's a unique symbol, so not statically analyzable)
|
||||
* ^^^^^
|
||||
*
|
||||
* var object = {
|
||||
* 1234: '4567', // returns '1234' (NOT 1234)
|
||||
* ^^^^^^^^^^^^
|
||||
* method() { } // returns 'method'
|
||||
* ^^^^^^^^^^^^
|
||||
* }
|
||||
*
|
||||
* class WithMembers {
|
||||
* foo: string // returns 'foo'
|
||||
* ^^^^^^^^^^^
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
function getStaticMemberAccessValue(node, { sourceCode }) {
|
||||
const key = node.type === utils_1.AST_NODE_TYPES.MemberExpression ? node.property : node.key;
|
||||
const { type } = key;
|
||||
if (!node.computed &&
|
||||
(type === utils_1.AST_NODE_TYPES.Identifier ||
|
||||
type === utils_1.AST_NODE_TYPES.PrivateIdentifier)) {
|
||||
return key.name;
|
||||
}
|
||||
const result = (0, astUtils_1.getStaticValue)(key, sourceCode.getScope(node));
|
||||
if (!result) {
|
||||
return undefined;
|
||||
}
|
||||
const { value } = result;
|
||||
return typeof value === 'symbol' ? value : String(value);
|
||||
}
|
||||
/**
|
||||
* Answers whether the member expression looks like
|
||||
* `x.value`, `x['value']`,
|
||||
* or even `const v = 'value'; x[v]` (or optional variants thereof).
|
||||
*/
|
||||
const isStaticMemberAccessOfValue = (memberExpression, context, ...values) => values.includes(getStaticMemberAccessValue(memberExpression, context));
|
||||
exports.isStaticMemberAccessOfValue = isStaticMemberAccessOfValue;
|
||||
@@ -0,0 +1,38 @@
|
||||
'use strict'
|
||||
|
||||
const { test } = require('node:test')
|
||||
const { join } = require('path')
|
||||
const ThreadStream = require('..')
|
||||
const { file } = require('./helper')
|
||||
|
||||
const MAX = 1000
|
||||
|
||||
let str = ''
|
||||
|
||||
for (let i = 0; i < 10; i++) {
|
||||
str += 'hello'
|
||||
}
|
||||
|
||||
test('base', function (t, done) {
|
||||
const dest = file()
|
||||
const stream = new ThreadStream({
|
||||
filename: join(__dirname, 'to-file.js'),
|
||||
workerData: { dest }
|
||||
})
|
||||
let runs = 0
|
||||
function benchThreadStream () {
|
||||
if (++runs === 1000) {
|
||||
stream.end()
|
||||
return
|
||||
}
|
||||
|
||||
for (let i = 0; i < MAX; i++) {
|
||||
stream.write(str)
|
||||
}
|
||||
setImmediate(benchThreadStream)
|
||||
}
|
||||
benchThreadStream()
|
||||
stream.on('finish', function () {
|
||||
done()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { Linter } from './Linter';
|
||||
export declare namespace Processor {
|
||||
interface ProcessorMeta {
|
||||
/**
|
||||
* The unique name of the processor.
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* The a string identifying the version of the processor.
|
||||
*/
|
||||
version?: string;
|
||||
}
|
||||
type PreProcess = (text: string, filename: string) => (string | {
|
||||
filename: string;
|
||||
text: string;
|
||||
})[];
|
||||
type PostProcess = (messagesList: Linter.LintMessage[][], filename: string) => Linter.LintMessage[];
|
||||
interface ProcessorModule {
|
||||
/**
|
||||
* Information about the processor to uniquely identify it when serializing.
|
||||
*/
|
||||
meta?: ProcessorMeta;
|
||||
/**
|
||||
* The function to merge messages.
|
||||
*/
|
||||
postprocess?: PostProcess;
|
||||
/**
|
||||
* The function to extract code blocks.
|
||||
*/
|
||||
preprocess?: PreProcess;
|
||||
/**
|
||||
* If `true` then it means the processor supports autofix.
|
||||
*/
|
||||
supportsAutofix?: boolean;
|
||||
}
|
||||
/**
|
||||
* A loose definition of the ParserModule type for use with configs
|
||||
* This type intended to relax validation of configs so that parsers that have
|
||||
* different AST types or scope managers can still be passed to configs
|
||||
*
|
||||
* @see {@link LooseRuleDefinition}, {@link LooseParserModule}
|
||||
*/
|
||||
interface LooseProcessorModule {
|
||||
/**
|
||||
* Information about the processor to uniquely identify it when serializing.
|
||||
*/
|
||||
meta?: {
|
||||
[K in keyof ProcessorMeta]?: ProcessorMeta[K] | undefined;
|
||||
};
|
||||
/**
|
||||
* The function to merge messages.
|
||||
*/
|
||||
postprocess?: (messagesList: any, filename: string) => any;
|
||||
/**
|
||||
* The function to extract code blocks.
|
||||
*/
|
||||
preprocess?: (text: string, filename: string) => any;
|
||||
/**
|
||||
* If `true` then it means the processor supports autofix.
|
||||
*/
|
||||
supportsAutofix?: boolean | undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { _ as default } from "../esm/_ts_param.js";
|
||||
@@ -0,0 +1,61 @@
|
||||
type Pathname = string
|
||||
|
||||
interface TestResult {
|
||||
ignored: boolean
|
||||
unignored: boolean
|
||||
}
|
||||
|
||||
export interface Ignore {
|
||||
/**
|
||||
* Adds one or several rules to the current manager.
|
||||
* @param {string[]} patterns
|
||||
* @returns IgnoreBase
|
||||
*/
|
||||
add(patterns: string | Ignore | readonly (string | Ignore)[]): this
|
||||
|
||||
/**
|
||||
* Filters the given array of pathnames, and returns the filtered array.
|
||||
* NOTICE that each path here should be a relative path to the root of your repository.
|
||||
* @param paths the array of paths to be filtered.
|
||||
* @returns The filtered array of paths
|
||||
*/
|
||||
filter(pathnames: readonly Pathname[]): Pathname[]
|
||||
|
||||
/**
|
||||
* Creates a filter function which could filter
|
||||
* an array of paths with Array.prototype.filter.
|
||||
*/
|
||||
createFilter(): (pathname: Pathname) => boolean
|
||||
|
||||
/**
|
||||
* Returns Boolean whether pathname should be ignored.
|
||||
* @param {string} pathname a path to check
|
||||
* @returns boolean
|
||||
*/
|
||||
ignores(pathname: Pathname): boolean
|
||||
|
||||
/**
|
||||
* Returns whether pathname should be ignored or unignored
|
||||
* @param {string} pathname a path to check
|
||||
* @returns TestResult
|
||||
*/
|
||||
test(pathname: Pathname): TestResult
|
||||
}
|
||||
|
||||
export interface Options {
|
||||
ignorecase?: boolean
|
||||
// For compatibility
|
||||
ignoreCase?: boolean
|
||||
allowRelativePaths?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates new ignore manager.
|
||||
*/
|
||||
declare function ignore(options?: Options): Ignore
|
||||
|
||||
declare namespace ignore {
|
||||
export function isPathValid (pathname: string): boolean
|
||||
}
|
||||
|
||||
export default ignore
|
||||
@@ -0,0 +1,377 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
const tsutils = __importStar(require("ts-api-utils"));
|
||||
const util_1 = require("../util");
|
||||
const promiseUtils_1 = require("../util/promiseUtils");
|
||||
const messageBase = 'Promises must be awaited, end with a call to .catch, or end with a call to .then with a rejection handler.';
|
||||
const messageBaseVoid = 'Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler' +
|
||||
' or be explicitly marked as ignored with the `void` operator.';
|
||||
const messageRejectionHandler = 'A rejection handler that is not a function will be ignored.';
|
||||
const messagePromiseArray = "An array of Promises may be unintentional. Consider handling the promises' fulfillment or rejection with Promise.all or similar.";
|
||||
const messagePromiseArrayVoid = "An array of Promises may be unintentional. Consider handling the promises' fulfillment or rejection with Promise.all or similar," +
|
||||
' or explicitly marking the expression as ignored with the `void` operator.';
|
||||
exports.default = (0, util_1.createRule)({
|
||||
name: 'no-floating-promises',
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Require Promise-like statements to be handled appropriately',
|
||||
recommended: 'recommended',
|
||||
requiresTypeChecking: true,
|
||||
},
|
||||
hasSuggestions: true,
|
||||
messages: {
|
||||
floating: messageBase,
|
||||
floatingFixAwait: 'Add await operator.',
|
||||
floatingFixVoid: 'Add void operator to ignore.',
|
||||
floatingPromiseArray: messagePromiseArray,
|
||||
floatingPromiseArrayVoid: messagePromiseArrayVoid,
|
||||
floatingUselessRejectionHandler: `${messageBase} ${messageRejectionHandler}`,
|
||||
floatingUselessRejectionHandlerVoid: `${messageBaseVoid} ${messageRejectionHandler}`,
|
||||
floatingVoid: messageBaseVoid,
|
||||
},
|
||||
schema: [
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
allowForKnownSafeCalls: {
|
||||
...util_1.readonlynessOptionsSchema.properties.allow,
|
||||
description: 'Type specifiers of functions whose calls are safe to float.',
|
||||
},
|
||||
allowForKnownSafePromises: {
|
||||
...util_1.readonlynessOptionsSchema.properties.allow,
|
||||
description: 'Type specifiers that are known to be safe to float.',
|
||||
},
|
||||
checkThenables: {
|
||||
type: 'boolean',
|
||||
description: 'Whether to check all "Thenable"s, not just the built-in Promise type.',
|
||||
},
|
||||
ignoreIIFE: {
|
||||
type: 'boolean',
|
||||
description: 'Whether to ignore async IIFEs (Immediately Invoked Function Expressions).',
|
||||
},
|
||||
ignoreVoid: {
|
||||
type: 'boolean',
|
||||
description: 'Whether to ignore `void` expressions.',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
defaultOptions: [
|
||||
{
|
||||
allowForKnownSafeCalls: util_1.readonlynessOptionsDefaults.allow,
|
||||
allowForKnownSafePromises: util_1.readonlynessOptionsDefaults.allow,
|
||||
checkThenables: false,
|
||||
ignoreIIFE: false,
|
||||
ignoreVoid: true,
|
||||
},
|
||||
],
|
||||
create(context, [options]) {
|
||||
const services = (0, util_1.getParserServices)(context);
|
||||
const checker = services.program.getTypeChecker();
|
||||
const { checkThenables } = options;
|
||||
// TODO: #5439
|
||||
/* eslint-disable @typescript-eslint/no-non-null-assertion */
|
||||
const allowForKnownSafePromises = options.allowForKnownSafePromises;
|
||||
const allowForKnownSafeCalls = options.allowForKnownSafeCalls;
|
||||
/* eslint-enable @typescript-eslint/no-non-null-assertion */
|
||||
return {
|
||||
ExpressionStatement(node) {
|
||||
if (options.ignoreIIFE && isAsyncIife(node)) {
|
||||
return;
|
||||
}
|
||||
const expression = (0, util_1.skipChainExpression)(node.expression);
|
||||
if (isKnownSafePromiseCall(expression)) {
|
||||
return;
|
||||
}
|
||||
const { isUnhandled, nonFunctionHandler, promiseArray } = isUnhandledPromise(checker, expression);
|
||||
if (isUnhandled) {
|
||||
if (promiseArray) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: options.ignoreVoid
|
||||
? 'floatingPromiseArrayVoid'
|
||||
: 'floatingPromiseArray',
|
||||
});
|
||||
}
|
||||
else if (options.ignoreVoid) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: nonFunctionHandler
|
||||
? 'floatingUselessRejectionHandlerVoid'
|
||||
: 'floatingVoid',
|
||||
suggest: [
|
||||
{
|
||||
messageId: 'floatingFixVoid',
|
||||
fix(fixer) {
|
||||
if ((0, util_1.isParenthesized)(expression, context.sourceCode) ||
|
||||
(0, util_1.getOperatorPrecedenceForNode)(expression) >
|
||||
util_1.OperatorPrecedence.Unary) {
|
||||
return fixer.insertTextBefore(node, 'void ');
|
||||
}
|
||||
return [
|
||||
fixer.insertTextBefore(node, 'void ('),
|
||||
fixer.insertTextAfterRange([expression.range[1], expression.range[1]], ')'),
|
||||
];
|
||||
},
|
||||
},
|
||||
{
|
||||
messageId: 'floatingFixAwait',
|
||||
fix: (fixer) => addAwait(fixer, expression, node),
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
else {
|
||||
context.report({
|
||||
node,
|
||||
messageId: nonFunctionHandler
|
||||
? 'floatingUselessRejectionHandler'
|
||||
: 'floating',
|
||||
suggest: [
|
||||
{
|
||||
messageId: 'floatingFixAwait',
|
||||
fix: (fixer) => addAwait(fixer, expression, node),
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
function addAwait(fixer, expression, node) {
|
||||
if (expression.type === utils_1.AST_NODE_TYPES.UnaryExpression &&
|
||||
expression.operator === 'void') {
|
||||
return fixer.replaceTextRange([expression.range[0], expression.range[0] + 4], 'await');
|
||||
}
|
||||
if ((0, util_1.isParenthesized)(expression, context.sourceCode) ||
|
||||
(0, util_1.getOperatorPrecedenceForNode)(expression) > util_1.OperatorPrecedence.Unary) {
|
||||
return fixer.insertTextBefore(node, 'await ');
|
||||
}
|
||||
return [
|
||||
fixer.insertTextBefore(node, 'await ('),
|
||||
fixer.insertTextAfterRange([expression.range[1], expression.range[1]], ')'),
|
||||
];
|
||||
}
|
||||
function isKnownSafePromiseCall(node) {
|
||||
if (node.type !== utils_1.AST_NODE_TYPES.CallExpression) {
|
||||
return false;
|
||||
}
|
||||
const type = services.getTypeAtLocation(node.callee);
|
||||
if ((0, util_1.valueMatchesSomeSpecifier)(node.callee, allowForKnownSafeCalls, services.program, type)) {
|
||||
return true;
|
||||
}
|
||||
return (0, util_1.typeMatchesSomeSpecifier)(type, allowForKnownSafeCalls, services.program);
|
||||
}
|
||||
function isAsyncIife(node) {
|
||||
if (node.expression.type !== utils_1.AST_NODE_TYPES.CallExpression) {
|
||||
return false;
|
||||
}
|
||||
return (node.expression.callee.type ===
|
||||
utils_1.AST_NODE_TYPES.ArrowFunctionExpression ||
|
||||
node.expression.callee.type === utils_1.AST_NODE_TYPES.FunctionExpression);
|
||||
}
|
||||
function isValidRejectionHandler(rejectionHandler) {
|
||||
return (services.program
|
||||
.getTypeChecker()
|
||||
.getTypeAtLocation(services.esTreeNodeToTSNodeMap.get(rejectionHandler))
|
||||
.getCallSignatures().length > 0);
|
||||
}
|
||||
function isUnhandledPromise(checker, node) {
|
||||
if (node.type === utils_1.AST_NODE_TYPES.AssignmentExpression) {
|
||||
return { isUnhandled: false };
|
||||
}
|
||||
// First, check expressions whose resulting types may not be promise-like
|
||||
if (node.type === utils_1.AST_NODE_TYPES.SequenceExpression) {
|
||||
// Any child in a comma expression could return a potentially unhandled
|
||||
// promise, so we check them all regardless of whether the final returned
|
||||
// value is promise-like.
|
||||
return (node.expressions
|
||||
.map(item => isUnhandledPromise(checker, item))
|
||||
.find(result => result.isUnhandled) ?? { isUnhandled: false });
|
||||
}
|
||||
if (!options.ignoreVoid &&
|
||||
node.type === utils_1.AST_NODE_TYPES.UnaryExpression &&
|
||||
node.operator === 'void') {
|
||||
// Similarly, a `void` expression always returns undefined, so we need to
|
||||
// see what's inside it without checking the type of the overall expression.
|
||||
return isUnhandledPromise(checker, node.argument);
|
||||
}
|
||||
const tsNode = services.esTreeNodeToTSNodeMap.get(node);
|
||||
// Check the type. At this point it can't be unhandled if it isn't a promise
|
||||
// or array thereof.
|
||||
if (isPromiseArray(tsNode)) {
|
||||
return { isUnhandled: true, promiseArray: true };
|
||||
}
|
||||
// await expression addresses promises, but not promise arrays.
|
||||
if (node.type === utils_1.AST_NODE_TYPES.AwaitExpression) {
|
||||
// you would think this wouldn't be strictly necessary, since we're
|
||||
// anyway checking the type of the expression, but, unfortunately TS
|
||||
// reports the result of `await (promise as Promise<number> & number)`
|
||||
// as `Promise<number> & number` instead of `number`.
|
||||
return { isUnhandled: false };
|
||||
}
|
||||
if (!isPromiseLike(tsNode)) {
|
||||
return { isUnhandled: false };
|
||||
}
|
||||
if (node.type === utils_1.AST_NODE_TYPES.CallExpression) {
|
||||
// If the outer expression is a call, a `.catch()` or `.then()` with
|
||||
// rejection handler handles the promise.
|
||||
const promiseHandlingMethodCall = (0, promiseUtils_1.parseCatchCall)(node, context) ?? (0, promiseUtils_1.parseThenCall)(node, context);
|
||||
if (promiseHandlingMethodCall != null) {
|
||||
const onRejected = promiseHandlingMethodCall.onRejected;
|
||||
if (onRejected != null) {
|
||||
if (isValidRejectionHandler(onRejected)) {
|
||||
return { isUnhandled: false };
|
||||
}
|
||||
return { isUnhandled: true, nonFunctionHandler: true };
|
||||
}
|
||||
return { isUnhandled: true };
|
||||
}
|
||||
const promiseFinallyCall = (0, promiseUtils_1.parseFinallyCall)(node, context);
|
||||
if (promiseFinallyCall != null) {
|
||||
return isUnhandledPromise(checker, promiseFinallyCall.object);
|
||||
}
|
||||
// All other cases are unhandled.
|
||||
return { isUnhandled: true };
|
||||
}
|
||||
if (node.type === utils_1.AST_NODE_TYPES.ConditionalExpression) {
|
||||
// We must be getting the promise-like value from one of the branches of the
|
||||
// ternary. Check them directly.
|
||||
const alternateResult = isUnhandledPromise(checker, node.alternate);
|
||||
if (alternateResult.isUnhandled) {
|
||||
return alternateResult;
|
||||
}
|
||||
return isUnhandledPromise(checker, node.consequent);
|
||||
}
|
||||
if (node.type === utils_1.AST_NODE_TYPES.LogicalExpression) {
|
||||
const leftResult = isUnhandledPromise(checker, node.left);
|
||||
if (leftResult.isUnhandled) {
|
||||
return leftResult;
|
||||
}
|
||||
return isUnhandledPromise(checker, node.right);
|
||||
}
|
||||
// Anything else is unhandled.
|
||||
return { isUnhandled: true };
|
||||
}
|
||||
function isPromiseArray(node) {
|
||||
const type = getTypeAtLocation(checker, node);
|
||||
if (type == null) {
|
||||
return false;
|
||||
}
|
||||
for (const ty of tsutils
|
||||
.unionConstituents(type)
|
||||
.map(t => checker.getApparentType(t))) {
|
||||
if (checker.isArrayType(ty)) {
|
||||
const arrayType = checker.getTypeArguments(ty)[0];
|
||||
if (isPromiseLike(node, arrayType)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (checker.isTupleType(ty)) {
|
||||
for (const tupleElementType of checker.getTypeArguments(ty)) {
|
||||
if (isPromiseLike(node, tupleElementType)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function isPromiseLike(node, type) {
|
||||
type ??= checker.getTypeAtLocation(node);
|
||||
// The highest priority is to allow anything allowlisted
|
||||
if ((0, util_1.typeMatchesSomeSpecifier)(type, allowForKnownSafePromises, services.program)) {
|
||||
return false;
|
||||
}
|
||||
// Otherwise, we always consider the built-in Promise to be Promise-like...
|
||||
const typeParts = tsutils.unionConstituents(checker.getApparentType(type));
|
||||
if (typeParts.some(typePart => (0, util_1.isBuiltinSymbolLike)(services.program, typePart, 'Promise'))) {
|
||||
return true;
|
||||
}
|
||||
// ...and only check all Thenables if explicitly told to
|
||||
if (!checkThenables) {
|
||||
return false;
|
||||
}
|
||||
// Modified from tsutils.isThenable() to only consider thenables which can be
|
||||
// rejected/caught via a second parameter. Original source (MIT licensed):
|
||||
//
|
||||
// https://github.com/ajafff/tsutils/blob/49d0d31050b44b81e918eae4fbaf1dfe7b7286af/util/type.ts#L95-L125
|
||||
for (const ty of typeParts) {
|
||||
const then = ty.getProperty('then');
|
||||
if (then == null) {
|
||||
continue;
|
||||
}
|
||||
const thenType = checker.getTypeOfSymbolAtLocation(then, node);
|
||||
if (hasMatchingSignature(thenType, signature => signature.parameters.length >= 2 &&
|
||||
isFunctionParam(checker, signature.parameters[0], node) &&
|
||||
isFunctionParam(checker, signature.parameters[1], node))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
},
|
||||
});
|
||||
function hasMatchingSignature(type, matcher) {
|
||||
for (const t of tsutils.unionConstituents(type)) {
|
||||
if (t.getCallSignatures().some(matcher)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function isFunctionParam(checker, param, node) {
|
||||
const type = checker.getApparentType(checker.getTypeOfSymbolAtLocation(param, node));
|
||||
for (const t of tsutils.unionConstituents(type)) {
|
||||
if (t.getCallSignatures().length !== 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function getTypeAtLocation(checker, node) {
|
||||
try {
|
||||
return checker.getTypeAtLocation(node);
|
||||
}
|
||||
catch {
|
||||
// Workaround for https://github.com/typescript-eslint/typescript-eslint/issues/11947
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"name": "esrecurse",
|
||||
"description": "ECMAScript AST recursive visitor",
|
||||
"homepage": "https://github.com/estools/esrecurse",
|
||||
"main": "esrecurse.js",
|
||||
"version": "4.3.0",
|
||||
"engines": {
|
||||
"node": ">=4.0"
|
||||
},
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "Yusuke Suzuki",
|
||||
"email": "utatane.tea@gmail.com",
|
||||
"web": "https://github.com/Constellation"
|
||||
}
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/estools/esrecurse.git"
|
||||
},
|
||||
"dependencies": {
|
||||
"estraverse": "^5.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"babel-cli": "^6.24.1",
|
||||
"babel-eslint": "^7.2.3",
|
||||
"babel-preset-es2015": "^6.24.1",
|
||||
"babel-register": "^6.24.1",
|
||||
"chai": "^4.0.2",
|
||||
"esprima": "^4.0.0",
|
||||
"gulp": "^3.9.0",
|
||||
"gulp-bump": "^2.7.0",
|
||||
"gulp-eslint": "^4.0.0",
|
||||
"gulp-filter": "^5.0.0",
|
||||
"gulp-git": "^2.4.1",
|
||||
"gulp-mocha": "^4.3.1",
|
||||
"gulp-tag-version": "^1.2.1",
|
||||
"jsdoc": "^3.3.0-alpha10",
|
||||
"minimist": "^1.1.0"
|
||||
},
|
||||
"license": "BSD-2-Clause",
|
||||
"scripts": {
|
||||
"test": "gulp travis",
|
||||
"unit-test": "gulp test",
|
||||
"lint": "gulp lint"
|
||||
},
|
||||
"babel": {
|
||||
"presets": [
|
||||
"es2015"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import type { $ZodStringFormats } from "../core/checks.js";
|
||||
import type * as errors from "../core/errors.js";
|
||||
import * as util from "../core/util.js";
|
||||
|
||||
const error: () => errors.$ZodErrorMap = () => {
|
||||
const Sizable: Record<string, { unit: string; verb: string }> = {
|
||||
string: { unit: "caracteres", verb: "tener" },
|
||||
file: { unit: "bytes", verb: "tener" },
|
||||
array: { unit: "elementos", verb: "tener" },
|
||||
set: { unit: "elementos", verb: "tener" },
|
||||
};
|
||||
|
||||
function getSizing(origin: string): { unit: string; verb: string } | null {
|
||||
return Sizable[origin] ?? null;
|
||||
}
|
||||
|
||||
const FormatDictionary: {
|
||||
[k in $ZodStringFormats | (string & {})]?: string;
|
||||
} = {
|
||||
regex: "entrada",
|
||||
email: "dirección de correo electrónico",
|
||||
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: "fecha y hora ISO",
|
||||
date: "fecha ISO",
|
||||
time: "hora ISO",
|
||||
duration: "duración ISO",
|
||||
ipv4: "dirección IPv4",
|
||||
ipv6: "dirección IPv6",
|
||||
cidrv4: "rango IPv4",
|
||||
cidrv6: "rango IPv6",
|
||||
base64: "cadena codificada en base64",
|
||||
base64url: "URL codificada en base64",
|
||||
json_string: "cadena JSON",
|
||||
e164: "número E.164",
|
||||
jwt: "JWT",
|
||||
template_literal: "entrada",
|
||||
};
|
||||
|
||||
const TypeDictionary: {
|
||||
[k in errors.$ZodInvalidTypeExpected | (string & {})]?: string;
|
||||
} = {
|
||||
nan: "NaN",
|
||||
string: "texto",
|
||||
number: "número",
|
||||
boolean: "booleano",
|
||||
array: "arreglo",
|
||||
object: "objeto",
|
||||
set: "conjunto",
|
||||
file: "archivo",
|
||||
date: "fecha",
|
||||
bigint: "número grande",
|
||||
symbol: "símbolo",
|
||||
undefined: "indefinido",
|
||||
null: "nulo",
|
||||
function: "función",
|
||||
map: "mapa",
|
||||
record: "registro",
|
||||
tuple: "tupla",
|
||||
enum: "enumeración",
|
||||
union: "unión",
|
||||
literal: "literal",
|
||||
promise: "promesa",
|
||||
void: "vacío",
|
||||
never: "nunca",
|
||||
unknown: "desconocido",
|
||||
any: "cualquiera",
|
||||
};
|
||||
|
||||
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 `Entrada inválida: se esperaba instanceof ${issue.expected}, recibido ${received}`;
|
||||
}
|
||||
return `Entrada inválida: se esperaba ${expected}, recibido ${received}`;
|
||||
}
|
||||
case "invalid_value":
|
||||
if (issue.values.length === 1)
|
||||
return `Entrada inválida: se esperaba ${util.stringifyPrimitive(issue.values[0])}`;
|
||||
return `Opción inválida: se esperaba una de ${util.joinValues(issue.values, "|")}`;
|
||||
case "too_big": {
|
||||
const adj = issue.inclusive ? "<=" : "<";
|
||||
const sizing = getSizing(issue.origin);
|
||||
const origin = TypeDictionary[issue.origin] ?? issue.origin;
|
||||
if (sizing)
|
||||
return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementos"}`;
|
||||
return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue.maximum.toString()}`;
|
||||
}
|
||||
case "too_small": {
|
||||
const adj = issue.inclusive ? ">=" : ">";
|
||||
const sizing = getSizing(issue.origin);
|
||||
const origin = TypeDictionary[issue.origin] ?? issue.origin;
|
||||
if (sizing) {
|
||||
return `Demasiado pequeño: se esperaba que ${origin} tuviera ${adj}${issue.minimum.toString()} ${sizing.unit}`;
|
||||
}
|
||||
|
||||
return `Demasiado pequeño: se esperaba que ${origin} fuera ${adj}${issue.minimum.toString()}`;
|
||||
}
|
||||
case "invalid_format": {
|
||||
const _issue = issue as errors.$ZodStringFormatIssues;
|
||||
if (_issue.format === "starts_with") return `Cadena inválida: debe comenzar con "${_issue.prefix}"`;
|
||||
if (_issue.format === "ends_with") return `Cadena inválida: debe terminar en "${_issue.suffix}"`;
|
||||
if (_issue.format === "includes") return `Cadena inválida: debe incluir "${_issue.includes}"`;
|
||||
if (_issue.format === "regex") return `Cadena inválida: debe coincidir con el patrón ${_issue.pattern}`;
|
||||
return `Inválido ${FormatDictionary[_issue.format] ?? issue.format}`;
|
||||
}
|
||||
case "not_multiple_of":
|
||||
return `Número inválido: debe ser múltiplo de ${issue.divisor}`;
|
||||
case "unrecognized_keys":
|
||||
return `Llave${issue.keys.length > 1 ? "s" : ""} desconocida${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`;
|
||||
case "invalid_key":
|
||||
return `Llave inválida en ${TypeDictionary[issue.origin] ?? issue.origin}`;
|
||||
case "invalid_union":
|
||||
return "Entrada inválida";
|
||||
case "invalid_element":
|
||||
return `Valor inválido en ${TypeDictionary[issue.origin] ?? issue.origin}`;
|
||||
default:
|
||||
return `Entrada inválida`;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
export default function (): { localeError: errors.$ZodErrorMap } {
|
||||
return {
|
||||
localeError: error(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
var OverloadYield = require("./OverloadYield.js");
|
||||
var regeneratorDefine = require("./regeneratorDefine.js");
|
||||
function AsyncIterator(t, e) {
|
||||
function n(r, o, i, f) {
|
||||
try {
|
||||
var c = t[r](o),
|
||||
u = c.value;
|
||||
return u instanceof OverloadYield ? e.resolve(u.v).then(function (t) {
|
||||
n("next", t, i, f);
|
||||
}, function (t) {
|
||||
n("throw", t, i, f);
|
||||
}) : e.resolve(u).then(function (t) {
|
||||
c.value = t, i(c);
|
||||
}, function (t) {
|
||||
return n("throw", t, i, f);
|
||||
});
|
||||
} catch (t) {
|
||||
f(t);
|
||||
}
|
||||
}
|
||||
var r;
|
||||
this.next || (regeneratorDefine(AsyncIterator.prototype), regeneratorDefine(AsyncIterator.prototype, "function" == typeof Symbol && Symbol.asyncIterator || "@asyncIterator", function () {
|
||||
return this;
|
||||
})), regeneratorDefine(this, "_invoke", function (t, o, i) {
|
||||
function f() {
|
||||
return new e(function (e, r) {
|
||||
n(t, i, e, r);
|
||||
});
|
||||
}
|
||||
return r = r ? r.then(f, f) : f();
|
||||
}, !0);
|
||||
}
|
||||
module.exports = AsyncIterator, module.exports.__esModule = true, module.exports["default"] = module.exports;
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,9 @@
|
||||
'use strict'
|
||||
|
||||
const { parentPort } = require('worker_threads')
|
||||
|
||||
parentPort.postMessage({
|
||||
code: 'CUSTOM-WORKER-CALLED'
|
||||
})
|
||||
|
||||
require('../lib/worker')
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"main": "../../cjs/_async_to_generator.cjs",
|
||||
"module": "../../esm/_async_to_generator.js"
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/*! *****************************************************************************
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
||||
this file except in compliance with the License. You may obtain a copy of the
|
||||
License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
||||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
||||
MERCHANTABILITY OR NON-INFRINGEMENT.
|
||||
|
||||
See the Apache Version 2.0 License for specific language governing permissions
|
||||
and limitations under the License.
|
||||
***************************************************************************** */
|
||||
|
||||
|
||||
interface RegExpMatchArray {
|
||||
indices?: RegExpIndicesArray;
|
||||
}
|
||||
|
||||
interface RegExpExecArray {
|
||||
indices?: RegExpIndicesArray;
|
||||
}
|
||||
|
||||
interface RegExpIndicesArray extends Array<[number, number] | undefined> {
|
||||
groups?: {
|
||||
[key: string]: [number, number];
|
||||
};
|
||||
}
|
||||
|
||||
interface RegExp {
|
||||
/**
|
||||
* Returns a Boolean value indicating the state of the hasIndices flag (d) used with a regular expression.
|
||||
* Default is false. Read-only.
|
||||
*/
|
||||
readonly hasIndices: boolean;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export declare function parserSeemsToBeTSESLint(parser: string | undefined): boolean;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,5 @@
|
||||
'use strict'
|
||||
|
||||
module.exports.isClean = Symbol('isClean')
|
||||
|
||||
module.exports.my = Symbol('my')
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"diagnosticCategory.enum.d.ts","sourceRoot":"","sources":["../../src/enums/diagnosticCategory.enum.ts"],"names":[],"mappings":"AAEA,oBAAY,kBAAkB;IAC1B,OAAO,IAAI;IACX,KAAK,IAAI;IACT,UAAU,IAAI;IACd,OAAO,IAAI;CACd"}
|
||||
@@ -0,0 +1,420 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.blake2s = exports.BLAKE2s = exports.blake2b = exports.BLAKE2b = exports.BLAKE2 = void 0;
|
||||
exports.compress = compress;
|
||||
/**
|
||||
* blake2b (64-bit) & blake2s (8 to 32-bit) hash functions.
|
||||
* b could have been faster, but there is no fast u64 in js, so s is 1.5x faster.
|
||||
* @module
|
||||
*/
|
||||
const _blake_ts_1 = require("./_blake.js");
|
||||
const _md_ts_1 = require("./_md.js");
|
||||
const u64 = require("./_u64.js");
|
||||
// prettier-ignore
|
||||
const utils_ts_1 = require("./utils.js");
|
||||
// Same as SHA512_IV, but swapped endianness: LE instead of BE. iv[1] is iv[0], etc.
|
||||
const B2B_IV = /* @__PURE__ */ Uint32Array.from([
|
||||
0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a,
|
||||
0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19,
|
||||
]);
|
||||
// Temporary buffer
|
||||
const BBUF = /* @__PURE__ */ new Uint32Array(32);
|
||||
// Mixing function G splitted in two halfs
|
||||
function G1b(a, b, c, d, msg, x) {
|
||||
// NOTE: V is LE here
|
||||
const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore
|
||||
let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore
|
||||
let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore
|
||||
let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore
|
||||
let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore
|
||||
// v[a] = (v[a] + v[b] + x) | 0;
|
||||
let ll = u64.add3L(Al, Bl, Xl);
|
||||
Ah = u64.add3H(ll, Ah, Bh, Xh);
|
||||
Al = ll | 0;
|
||||
// v[d] = rotr(v[d] ^ v[a], 32)
|
||||
({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
|
||||
({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) });
|
||||
// v[c] = (v[c] + v[d]) | 0;
|
||||
({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));
|
||||
// v[b] = rotr(v[b] ^ v[c], 24)
|
||||
({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
|
||||
({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) });
|
||||
(BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah);
|
||||
(BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh);
|
||||
(BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch);
|
||||
(BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh);
|
||||
}
|
||||
function G2b(a, b, c, d, msg, x) {
|
||||
// NOTE: V is LE here
|
||||
const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore
|
||||
let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore
|
||||
let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore
|
||||
let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore
|
||||
let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore
|
||||
// v[a] = (v[a] + v[b] + x) | 0;
|
||||
let ll = u64.add3L(Al, Bl, Xl);
|
||||
Ah = u64.add3H(ll, Ah, Bh, Xh);
|
||||
Al = ll | 0;
|
||||
// v[d] = rotr(v[d] ^ v[a], 16)
|
||||
({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
|
||||
({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) });
|
||||
// v[c] = (v[c] + v[d]) | 0;
|
||||
({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl));
|
||||
// v[b] = rotr(v[b] ^ v[c], 63)
|
||||
({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
|
||||
({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) });
|
||||
(BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah);
|
||||
(BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh);
|
||||
(BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch);
|
||||
(BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh);
|
||||
}
|
||||
function checkBlake2Opts(outputLen, opts = {}, keyLen, saltLen, persLen) {
|
||||
(0, utils_ts_1.anumber)(keyLen);
|
||||
if (outputLen < 0 || outputLen > keyLen)
|
||||
throw new Error('outputLen bigger than keyLen');
|
||||
const { key, salt, personalization } = opts;
|
||||
if (key !== undefined && (key.length < 1 || key.length > keyLen))
|
||||
throw new Error('key length must be undefined or 1..' + keyLen);
|
||||
if (salt !== undefined && salt.length !== saltLen)
|
||||
throw new Error('salt must be undefined or ' + saltLen);
|
||||
if (personalization !== undefined && personalization.length !== persLen)
|
||||
throw new Error('personalization must be undefined or ' + persLen);
|
||||
}
|
||||
/** Class, from which others are subclassed. */
|
||||
class BLAKE2 extends utils_ts_1.Hash {
|
||||
constructor(blockLen, outputLen) {
|
||||
super();
|
||||
this.finished = false;
|
||||
this.destroyed = false;
|
||||
this.length = 0;
|
||||
this.pos = 0;
|
||||
(0, utils_ts_1.anumber)(blockLen);
|
||||
(0, utils_ts_1.anumber)(outputLen);
|
||||
this.blockLen = blockLen;
|
||||
this.outputLen = outputLen;
|
||||
this.buffer = new Uint8Array(blockLen);
|
||||
this.buffer32 = (0, utils_ts_1.u32)(this.buffer);
|
||||
}
|
||||
update(data) {
|
||||
(0, utils_ts_1.aexists)(this);
|
||||
data = (0, utils_ts_1.toBytes)(data);
|
||||
(0, utils_ts_1.abytes)(data);
|
||||
// Main difference with other hashes: there is flag for last block,
|
||||
// so we cannot process current block before we know that there
|
||||
// is the next one. This significantly complicates logic and reduces ability
|
||||
// to do zero-copy processing
|
||||
const { blockLen, buffer, buffer32 } = this;
|
||||
const len = data.length;
|
||||
const offset = data.byteOffset;
|
||||
const buf = data.buffer;
|
||||
for (let pos = 0; pos < len;) {
|
||||
// If buffer is full and we still have input (don't process last block, same as blake2s)
|
||||
if (this.pos === blockLen) {
|
||||
(0, utils_ts_1.swap32IfBE)(buffer32);
|
||||
this.compress(buffer32, 0, false);
|
||||
(0, utils_ts_1.swap32IfBE)(buffer32);
|
||||
this.pos = 0;
|
||||
}
|
||||
const take = Math.min(blockLen - this.pos, len - pos);
|
||||
const dataOffset = offset + pos;
|
||||
// full block && aligned to 4 bytes && not last in input
|
||||
if (take === blockLen && !(dataOffset % 4) && pos + take < len) {
|
||||
const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4));
|
||||
(0, utils_ts_1.swap32IfBE)(data32);
|
||||
for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) {
|
||||
this.length += blockLen;
|
||||
this.compress(data32, pos32, false);
|
||||
}
|
||||
(0, utils_ts_1.swap32IfBE)(data32);
|
||||
continue;
|
||||
}
|
||||
buffer.set(data.subarray(pos, pos + take), this.pos);
|
||||
this.pos += take;
|
||||
this.length += take;
|
||||
pos += take;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
digestInto(out) {
|
||||
(0, utils_ts_1.aexists)(this);
|
||||
(0, utils_ts_1.aoutput)(out, this);
|
||||
const { pos, buffer32 } = this;
|
||||
this.finished = true;
|
||||
// Padding
|
||||
(0, utils_ts_1.clean)(this.buffer.subarray(pos));
|
||||
(0, utils_ts_1.swap32IfBE)(buffer32);
|
||||
this.compress(buffer32, 0, true);
|
||||
(0, utils_ts_1.swap32IfBE)(buffer32);
|
||||
const out32 = (0, utils_ts_1.u32)(out);
|
||||
this.get().forEach((v, i) => (out32[i] = (0, utils_ts_1.swap8IfBE)(v)));
|
||||
}
|
||||
digest() {
|
||||
const { buffer, outputLen } = this;
|
||||
this.digestInto(buffer);
|
||||
const res = buffer.slice(0, outputLen);
|
||||
this.destroy();
|
||||
return res;
|
||||
}
|
||||
_cloneInto(to) {
|
||||
const { buffer, length, finished, destroyed, outputLen, pos } = this;
|
||||
to || (to = new this.constructor({ dkLen: outputLen }));
|
||||
to.set(...this.get());
|
||||
to.buffer.set(buffer);
|
||||
to.destroyed = destroyed;
|
||||
to.finished = finished;
|
||||
to.length = length;
|
||||
to.pos = pos;
|
||||
// @ts-ignore
|
||||
to.outputLen = outputLen;
|
||||
return to;
|
||||
}
|
||||
clone() {
|
||||
return this._cloneInto();
|
||||
}
|
||||
}
|
||||
exports.BLAKE2 = BLAKE2;
|
||||
class BLAKE2b extends BLAKE2 {
|
||||
constructor(opts = {}) {
|
||||
const olen = opts.dkLen === undefined ? 64 : opts.dkLen;
|
||||
super(128, olen);
|
||||
// Same as SHA-512, but LE
|
||||
this.v0l = B2B_IV[0] | 0;
|
||||
this.v0h = B2B_IV[1] | 0;
|
||||
this.v1l = B2B_IV[2] | 0;
|
||||
this.v1h = B2B_IV[3] | 0;
|
||||
this.v2l = B2B_IV[4] | 0;
|
||||
this.v2h = B2B_IV[5] | 0;
|
||||
this.v3l = B2B_IV[6] | 0;
|
||||
this.v3h = B2B_IV[7] | 0;
|
||||
this.v4l = B2B_IV[8] | 0;
|
||||
this.v4h = B2B_IV[9] | 0;
|
||||
this.v5l = B2B_IV[10] | 0;
|
||||
this.v5h = B2B_IV[11] | 0;
|
||||
this.v6l = B2B_IV[12] | 0;
|
||||
this.v6h = B2B_IV[13] | 0;
|
||||
this.v7l = B2B_IV[14] | 0;
|
||||
this.v7h = B2B_IV[15] | 0;
|
||||
checkBlake2Opts(olen, opts, 64, 16, 16);
|
||||
let { key, personalization, salt } = opts;
|
||||
let keyLength = 0;
|
||||
if (key !== undefined) {
|
||||
key = (0, utils_ts_1.toBytes)(key);
|
||||
keyLength = key.length;
|
||||
}
|
||||
this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);
|
||||
if (salt !== undefined) {
|
||||
salt = (0, utils_ts_1.toBytes)(salt);
|
||||
const slt = (0, utils_ts_1.u32)(salt);
|
||||
this.v4l ^= (0, utils_ts_1.swap8IfBE)(slt[0]);
|
||||
this.v4h ^= (0, utils_ts_1.swap8IfBE)(slt[1]);
|
||||
this.v5l ^= (0, utils_ts_1.swap8IfBE)(slt[2]);
|
||||
this.v5h ^= (0, utils_ts_1.swap8IfBE)(slt[3]);
|
||||
}
|
||||
if (personalization !== undefined) {
|
||||
personalization = (0, utils_ts_1.toBytes)(personalization);
|
||||
const pers = (0, utils_ts_1.u32)(personalization);
|
||||
this.v6l ^= (0, utils_ts_1.swap8IfBE)(pers[0]);
|
||||
this.v6h ^= (0, utils_ts_1.swap8IfBE)(pers[1]);
|
||||
this.v7l ^= (0, utils_ts_1.swap8IfBE)(pers[2]);
|
||||
this.v7h ^= (0, utils_ts_1.swap8IfBE)(pers[3]);
|
||||
}
|
||||
if (key !== undefined) {
|
||||
// Pad to blockLen and update
|
||||
const tmp = new Uint8Array(this.blockLen);
|
||||
tmp.set(key);
|
||||
this.update(tmp);
|
||||
}
|
||||
}
|
||||
// prettier-ignore
|
||||
get() {
|
||||
let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this;
|
||||
return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h];
|
||||
}
|
||||
// prettier-ignore
|
||||
set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) {
|
||||
this.v0l = v0l | 0;
|
||||
this.v0h = v0h | 0;
|
||||
this.v1l = v1l | 0;
|
||||
this.v1h = v1h | 0;
|
||||
this.v2l = v2l | 0;
|
||||
this.v2h = v2h | 0;
|
||||
this.v3l = v3l | 0;
|
||||
this.v3h = v3h | 0;
|
||||
this.v4l = v4l | 0;
|
||||
this.v4h = v4h | 0;
|
||||
this.v5l = v5l | 0;
|
||||
this.v5h = v5h | 0;
|
||||
this.v6l = v6l | 0;
|
||||
this.v6h = v6h | 0;
|
||||
this.v7l = v7l | 0;
|
||||
this.v7h = v7h | 0;
|
||||
}
|
||||
compress(msg, offset, isLast) {
|
||||
this.get().forEach((v, i) => (BBUF[i] = v)); // First half from state.
|
||||
BBUF.set(B2B_IV, 16); // Second half from IV.
|
||||
let { h, l } = u64.fromBig(BigInt(this.length));
|
||||
BBUF[24] = B2B_IV[8] ^ l; // Low word of the offset.
|
||||
BBUF[25] = B2B_IV[9] ^ h; // High word.
|
||||
// Invert all bits for last block
|
||||
if (isLast) {
|
||||
BBUF[28] = ~BBUF[28];
|
||||
BBUF[29] = ~BBUF[29];
|
||||
}
|
||||
let j = 0;
|
||||
const s = _blake_ts_1.BSIGMA;
|
||||
for (let i = 0; i < 12; i++) {
|
||||
G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]);
|
||||
G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]);
|
||||
G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]);
|
||||
G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]);
|
||||
G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]);
|
||||
G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]);
|
||||
G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]);
|
||||
G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]);
|
||||
G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]);
|
||||
G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]);
|
||||
G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]);
|
||||
G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]);
|
||||
G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]);
|
||||
G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]);
|
||||
G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]);
|
||||
G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]);
|
||||
}
|
||||
this.v0l ^= BBUF[0] ^ BBUF[16];
|
||||
this.v0h ^= BBUF[1] ^ BBUF[17];
|
||||
this.v1l ^= BBUF[2] ^ BBUF[18];
|
||||
this.v1h ^= BBUF[3] ^ BBUF[19];
|
||||
this.v2l ^= BBUF[4] ^ BBUF[20];
|
||||
this.v2h ^= BBUF[5] ^ BBUF[21];
|
||||
this.v3l ^= BBUF[6] ^ BBUF[22];
|
||||
this.v3h ^= BBUF[7] ^ BBUF[23];
|
||||
this.v4l ^= BBUF[8] ^ BBUF[24];
|
||||
this.v4h ^= BBUF[9] ^ BBUF[25];
|
||||
this.v5l ^= BBUF[10] ^ BBUF[26];
|
||||
this.v5h ^= BBUF[11] ^ BBUF[27];
|
||||
this.v6l ^= BBUF[12] ^ BBUF[28];
|
||||
this.v6h ^= BBUF[13] ^ BBUF[29];
|
||||
this.v7l ^= BBUF[14] ^ BBUF[30];
|
||||
this.v7h ^= BBUF[15] ^ BBUF[31];
|
||||
(0, utils_ts_1.clean)(BBUF);
|
||||
}
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
(0, utils_ts_1.clean)(this.buffer32);
|
||||
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
exports.BLAKE2b = BLAKE2b;
|
||||
/**
|
||||
* Blake2b hash function. 64-bit. 1.5x slower than blake2s in JS.
|
||||
* @param msg - message that would be hashed
|
||||
* @param opts - dkLen output length, key for MAC mode, salt, personalization
|
||||
*/
|
||||
exports.blake2b = (0, utils_ts_1.createOptHasher)((opts) => new BLAKE2b(opts));
|
||||
// prettier-ignore
|
||||
function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
|
||||
let j = 0;
|
||||
for (let i = 0; i < rounds; i++) {
|
||||
({ a: v0, b: v4, c: v8, d: v12 } = (0, _blake_ts_1.G1s)(v0, v4, v8, v12, msg[offset + s[j++]]));
|
||||
({ a: v0, b: v4, c: v8, d: v12 } = (0, _blake_ts_1.G2s)(v0, v4, v8, v12, msg[offset + s[j++]]));
|
||||
({ a: v1, b: v5, c: v9, d: v13 } = (0, _blake_ts_1.G1s)(v1, v5, v9, v13, msg[offset + s[j++]]));
|
||||
({ a: v1, b: v5, c: v9, d: v13 } = (0, _blake_ts_1.G2s)(v1, v5, v9, v13, msg[offset + s[j++]]));
|
||||
({ a: v2, b: v6, c: v10, d: v14 } = (0, _blake_ts_1.G1s)(v2, v6, v10, v14, msg[offset + s[j++]]));
|
||||
({ a: v2, b: v6, c: v10, d: v14 } = (0, _blake_ts_1.G2s)(v2, v6, v10, v14, msg[offset + s[j++]]));
|
||||
({ a: v3, b: v7, c: v11, d: v15 } = (0, _blake_ts_1.G1s)(v3, v7, v11, v15, msg[offset + s[j++]]));
|
||||
({ a: v3, b: v7, c: v11, d: v15 } = (0, _blake_ts_1.G2s)(v3, v7, v11, v15, msg[offset + s[j++]]));
|
||||
({ a: v0, b: v5, c: v10, d: v15 } = (0, _blake_ts_1.G1s)(v0, v5, v10, v15, msg[offset + s[j++]]));
|
||||
({ a: v0, b: v5, c: v10, d: v15 } = (0, _blake_ts_1.G2s)(v0, v5, v10, v15, msg[offset + s[j++]]));
|
||||
({ a: v1, b: v6, c: v11, d: v12 } = (0, _blake_ts_1.G1s)(v1, v6, v11, v12, msg[offset + s[j++]]));
|
||||
({ a: v1, b: v6, c: v11, d: v12 } = (0, _blake_ts_1.G2s)(v1, v6, v11, v12, msg[offset + s[j++]]));
|
||||
({ a: v2, b: v7, c: v8, d: v13 } = (0, _blake_ts_1.G1s)(v2, v7, v8, v13, msg[offset + s[j++]]));
|
||||
({ a: v2, b: v7, c: v8, d: v13 } = (0, _blake_ts_1.G2s)(v2, v7, v8, v13, msg[offset + s[j++]]));
|
||||
({ a: v3, b: v4, c: v9, d: v14 } = (0, _blake_ts_1.G1s)(v3, v4, v9, v14, msg[offset + s[j++]]));
|
||||
({ a: v3, b: v4, c: v9, d: v14 } = (0, _blake_ts_1.G2s)(v3, v4, v9, v14, msg[offset + s[j++]]));
|
||||
}
|
||||
return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 };
|
||||
}
|
||||
const B2S_IV = _md_ts_1.SHA256_IV;
|
||||
class BLAKE2s extends BLAKE2 {
|
||||
constructor(opts = {}) {
|
||||
const olen = opts.dkLen === undefined ? 32 : opts.dkLen;
|
||||
super(64, olen);
|
||||
// Internal state, same as SHA-256
|
||||
this.v0 = B2S_IV[0] | 0;
|
||||
this.v1 = B2S_IV[1] | 0;
|
||||
this.v2 = B2S_IV[2] | 0;
|
||||
this.v3 = B2S_IV[3] | 0;
|
||||
this.v4 = B2S_IV[4] | 0;
|
||||
this.v5 = B2S_IV[5] | 0;
|
||||
this.v6 = B2S_IV[6] | 0;
|
||||
this.v7 = B2S_IV[7] | 0;
|
||||
checkBlake2Opts(olen, opts, 32, 8, 8);
|
||||
let { key, personalization, salt } = opts;
|
||||
let keyLength = 0;
|
||||
if (key !== undefined) {
|
||||
key = (0, utils_ts_1.toBytes)(key);
|
||||
keyLength = key.length;
|
||||
}
|
||||
this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);
|
||||
if (salt !== undefined) {
|
||||
salt = (0, utils_ts_1.toBytes)(salt);
|
||||
const slt = (0, utils_ts_1.u32)(salt);
|
||||
this.v4 ^= (0, utils_ts_1.swap8IfBE)(slt[0]);
|
||||
this.v5 ^= (0, utils_ts_1.swap8IfBE)(slt[1]);
|
||||
}
|
||||
if (personalization !== undefined) {
|
||||
personalization = (0, utils_ts_1.toBytes)(personalization);
|
||||
const pers = (0, utils_ts_1.u32)(personalization);
|
||||
this.v6 ^= (0, utils_ts_1.swap8IfBE)(pers[0]);
|
||||
this.v7 ^= (0, utils_ts_1.swap8IfBE)(pers[1]);
|
||||
}
|
||||
if (key !== undefined) {
|
||||
// Pad to blockLen and update
|
||||
(0, utils_ts_1.abytes)(key);
|
||||
const tmp = new Uint8Array(this.blockLen);
|
||||
tmp.set(key);
|
||||
this.update(tmp);
|
||||
}
|
||||
}
|
||||
get() {
|
||||
const { v0, v1, v2, v3, v4, v5, v6, v7 } = this;
|
||||
return [v0, v1, v2, v3, v4, v5, v6, v7];
|
||||
}
|
||||
// prettier-ignore
|
||||
set(v0, v1, v2, v3, v4, v5, v6, v7) {
|
||||
this.v0 = v0 | 0;
|
||||
this.v1 = v1 | 0;
|
||||
this.v2 = v2 | 0;
|
||||
this.v3 = v3 | 0;
|
||||
this.v4 = v4 | 0;
|
||||
this.v5 = v5 | 0;
|
||||
this.v6 = v6 | 0;
|
||||
this.v7 = v7 | 0;
|
||||
}
|
||||
compress(msg, offset, isLast) {
|
||||
const { h, l } = u64.fromBig(BigInt(this.length));
|
||||
// prettier-ignore
|
||||
const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(_blake_ts_1.BSIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l ^ B2S_IV[4], h ^ B2S_IV[5], isLast ? ~B2S_IV[6] : B2S_IV[6], B2S_IV[7]);
|
||||
this.v0 ^= v0 ^ v8;
|
||||
this.v1 ^= v1 ^ v9;
|
||||
this.v2 ^= v2 ^ v10;
|
||||
this.v3 ^= v3 ^ v11;
|
||||
this.v4 ^= v4 ^ v12;
|
||||
this.v5 ^= v5 ^ v13;
|
||||
this.v6 ^= v6 ^ v14;
|
||||
this.v7 ^= v7 ^ v15;
|
||||
}
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
(0, utils_ts_1.clean)(this.buffer32);
|
||||
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
exports.BLAKE2s = BLAKE2s;
|
||||
/**
|
||||
* Blake2s hash function. Focuses on 8-bit to 32-bit platforms. 1.5x faster than blake2b in JS.
|
||||
* @param msg - message that would be hashed
|
||||
* @param opts - dkLen output length, key for MAC mode, salt, personalization
|
||||
*/
|
||||
exports.blake2s = (0, utils_ts_1.createOptHasher)((opts) => new BLAKE2s(opts));
|
||||
//# sourceMappingURL=blake2.js.map
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "pino-std-serializers",
|
||||
"version": "7.1.0",
|
||||
"description": "A collection of standard object serializers for Pino",
|
||||
"main": "index.js",
|
||||
"type": "commonjs",
|
||||
"types": "index.d.ts",
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint --fix .",
|
||||
"lint-ci": "eslint --max-warnings=0 .",
|
||||
"test": "borp -p 'test/**/*.js'",
|
||||
"test-ci": "borp --coverage -p 'test/**/*.js'",
|
||||
"test-types": "tsc && tsd"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+ssh://git@github.com/pinojs/pino-std-serializers.git"
|
||||
},
|
||||
"keywords": [
|
||||
"pino",
|
||||
"logging"
|
||||
],
|
||||
"author": "James Sumners <james.sumners@gmail.com>",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/pinojs/pino-std-serializers/issues"
|
||||
},
|
||||
"homepage": "https://github.com/pinojs/pino-std-serializers#readme",
|
||||
"devDependencies": {
|
||||
"@matteo.collina/tspl": "^0.2.0",
|
||||
"@types/node": "^25.0.3",
|
||||
"borp": "^0.21.0",
|
||||
"eslint": "^9.39.2",
|
||||
"neostandard": "^0.12.2",
|
||||
"tsd": "^0.33.0",
|
||||
"typescript": "~5.9.3"
|
||||
},
|
||||
"tsd": {
|
||||
"directory": "test/types"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
"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: "karakter", verb: "legyen" },
|
||||
file: { unit: "byte", verb: "legyen" },
|
||||
array: { unit: "elem", verb: "legyen" },
|
||||
set: { unit: "elem", verb: "legyen" },
|
||||
};
|
||||
function getSizing(origin) {
|
||||
return Sizable[origin] ?? null;
|
||||
}
|
||||
const FormatDictionary = {
|
||||
regex: "bemenet",
|
||||
email: "email cím",
|
||||
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 időbélyeg",
|
||||
date: "ISO dátum",
|
||||
time: "ISO idő",
|
||||
duration: "ISO időintervallum",
|
||||
ipv4: "IPv4 cím",
|
||||
ipv6: "IPv6 cím",
|
||||
cidrv4: "IPv4 tartomány",
|
||||
cidrv6: "IPv6 tartomány",
|
||||
base64: "base64-kódolt string",
|
||||
base64url: "base64url-kódolt string",
|
||||
json_string: "JSON string",
|
||||
e164: "E.164 szám",
|
||||
jwt: "JWT",
|
||||
template_literal: "bemenet",
|
||||
};
|
||||
const TypeDictionary = {
|
||||
nan: "NaN",
|
||||
number: "szám",
|
||||
array: "tömb",
|
||||
};
|
||||
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 `Érvénytelen bemenet: a várt érték instanceof ${issue.expected}, a kapott érték ${received}`;
|
||||
}
|
||||
return `Érvénytelen bemenet: a várt érték ${expected}, a kapott érték ${received}`;
|
||||
}
|
||||
case "invalid_value":
|
||||
if (issue.values.length === 1)
|
||||
return `Érvénytelen bemenet: a várt érték ${util.stringifyPrimitive(issue.values[0])}`;
|
||||
return `Érvénytelen opció: valamelyik érték várt ${util.joinValues(issue.values, "|")}`;
|
||||
case "too_big": {
|
||||
const adj = issue.inclusive ? "<=" : "<";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing)
|
||||
return `Túl nagy: ${issue.origin ?? "érték"} mérete túl nagy ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elem"}`;
|
||||
return `Túl nagy: a bemeneti érték ${issue.origin ?? "érték"} túl nagy: ${adj}${issue.maximum.toString()}`;
|
||||
}
|
||||
case "too_small": {
|
||||
const adj = issue.inclusive ? ">=" : ">";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing) {
|
||||
return `Túl kicsi: a bemeneti érték ${issue.origin} mérete túl kicsi ${adj}${issue.minimum.toString()} ${sizing.unit}`;
|
||||
}
|
||||
return `Túl kicsi: a bemeneti érték ${issue.origin} túl kicsi ${adj}${issue.minimum.toString()}`;
|
||||
}
|
||||
case "invalid_format": {
|
||||
const _issue = issue;
|
||||
if (_issue.format === "starts_with")
|
||||
return `Érvénytelen string: "${_issue.prefix}" értékkel kell kezdődnie`;
|
||||
if (_issue.format === "ends_with")
|
||||
return `Érvénytelen string: "${_issue.suffix}" értékkel kell végződnie`;
|
||||
if (_issue.format === "includes")
|
||||
return `Érvénytelen string: "${_issue.includes}" értéket kell tartalmaznia`;
|
||||
if (_issue.format === "regex")
|
||||
return `Érvénytelen string: ${_issue.pattern} mintának kell megfelelnie`;
|
||||
return `Érvénytelen ${FormatDictionary[_issue.format] ?? issue.format}`;
|
||||
}
|
||||
case "not_multiple_of":
|
||||
return `Érvénytelen szám: ${issue.divisor} többszörösének kell lennie`;
|
||||
case "unrecognized_keys":
|
||||
return `Ismeretlen kulcs${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`;
|
||||
case "invalid_key":
|
||||
return `Érvénytelen kulcs ${issue.origin}`;
|
||||
case "invalid_union":
|
||||
return "Érvénytelen bemenet";
|
||||
case "invalid_element":
|
||||
return `Érvénytelen érték: ${issue.origin}`;
|
||||
default:
|
||||
return `Érvénytelen bemenet`;
|
||||
}
|
||||
};
|
||||
};
|
||||
function default_1() {
|
||||
return {
|
||||
localeError: error(),
|
||||
};
|
||||
}
|
||||
module.exports = exports.default;
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"main": "../../cjs/_set_prototype_of.cjs",
|
||||
"module": "../../esm/_set_prototype_of.js"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
nodeLinker: pnp
|
||||
pnpMode: loose
|
||||
pnpEnableEsmLoader: false
|
||||
packageExtensions:
|
||||
debug@*:
|
||||
dependencies:
|
||||
supports-color: '*'
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Un-escape a string that has been escaped with {@link escape}.
|
||||
*
|
||||
* If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then
|
||||
* square-bracket escapes are removed, but not backslash escapes.
|
||||
*
|
||||
* For example, it will turn the string `'[*]'` into `*`, but it will not
|
||||
* turn `'\\*'` into `'*'`, because `\` is a path separator in
|
||||
* `windowsPathsNoEscape` mode.
|
||||
*
|
||||
* When `windowsPathsNoEscape` is not set, then both square-bracket escapes and
|
||||
* backslash escapes are removed.
|
||||
*
|
||||
* Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
|
||||
* or unescaped.
|
||||
*
|
||||
* When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be
|
||||
* unescaped.
|
||||
*/
|
||||
export const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true, } = {}) => {
|
||||
if (magicalBraces) {
|
||||
return windowsPathsNoEscape ?
|
||||
s.replace(/\[([^/\\])\]/g, '$1')
|
||||
: s
|
||||
.replace(/((?!\\).|^)\[([^/\\])\]/g, '$1$2')
|
||||
.replace(/\\([^/])/g, '$1');
|
||||
}
|
||||
return windowsPathsNoEscape ?
|
||||
s.replace(/\[([^/\\{}])\]/g, '$1')
|
||||
: s
|
||||
.replace(/((?!\\).|^)\[([^/\\{}])\]/g, '$1$2')
|
||||
.replace(/\\([^/{}])/g, '$1');
|
||||
};
|
||||
//# sourceMappingURL=unescape.js.map
|
||||
@@ -0,0 +1,123 @@
|
||||
declare class MockerRegistry {
|
||||
private readonly registryByUrl;
|
||||
private readonly registryById;
|
||||
clear(): void;
|
||||
keys(): IterableIterator<string>;
|
||||
add(mock: MockedModule): void;
|
||||
register(json: MockedModuleSerialized): MockedModule;
|
||||
register(type: "redirect", raw: string, id: string, url: string, redirect: string): RedirectedModule;
|
||||
register(type: "manual", raw: string, id: string, url: string, factory: () => any): ManualMockedModule;
|
||||
register(type: "automock", raw: string, id: string, url: string): AutomockedModule;
|
||||
register(type: "autospy", id: string, raw: string, url: string): AutospiedModule;
|
||||
delete(id: string): void;
|
||||
deleteById(id: string): void;
|
||||
get(id: string): MockedModule | undefined;
|
||||
getById(id: string): MockedModule | undefined;
|
||||
has(id: string): boolean;
|
||||
}
|
||||
type MockedModule = AutomockedModule | AutospiedModule | ManualMockedModule | RedirectedModule;
|
||||
type MockedModuleType = "automock" | "autospy" | "manual" | "redirect";
|
||||
type MockedModuleSerialized = AutomockedModuleSerialized | AutospiedModuleSerialized | ManualMockedModuleSerialized | RedirectedModuleSerialized;
|
||||
declare class AutomockedModule {
|
||||
raw: string;
|
||||
id: string;
|
||||
url: string;
|
||||
readonly type = "automock";
|
||||
constructor(raw: string, id: string, url: string);
|
||||
static fromJSON(data: AutomockedModuleSerialized): AutospiedModule;
|
||||
toJSON(): AutomockedModuleSerialized;
|
||||
}
|
||||
interface AutomockedModuleSerialized {
|
||||
type: "automock";
|
||||
url: string;
|
||||
raw: string;
|
||||
id: string;
|
||||
}
|
||||
declare class AutospiedModule {
|
||||
raw: string;
|
||||
id: string;
|
||||
url: string;
|
||||
readonly type = "autospy";
|
||||
constructor(raw: string, id: string, url: string);
|
||||
static fromJSON(data: AutospiedModuleSerialized): AutospiedModule;
|
||||
toJSON(): AutospiedModuleSerialized;
|
||||
}
|
||||
interface AutospiedModuleSerialized {
|
||||
type: "autospy";
|
||||
url: string;
|
||||
raw: string;
|
||||
id: string;
|
||||
}
|
||||
declare class RedirectedModule {
|
||||
raw: string;
|
||||
id: string;
|
||||
url: string;
|
||||
redirect: string;
|
||||
readonly type = "redirect";
|
||||
constructor(raw: string, id: string, url: string, redirect: string);
|
||||
static fromJSON(data: RedirectedModuleSerialized): RedirectedModule;
|
||||
toJSON(): RedirectedModuleSerialized;
|
||||
}
|
||||
interface RedirectedModuleSerialized {
|
||||
type: "redirect";
|
||||
url: string;
|
||||
id: string;
|
||||
raw: string;
|
||||
redirect: string;
|
||||
}
|
||||
declare class ManualMockedModule<T = any> {
|
||||
raw: string;
|
||||
id: string;
|
||||
url: string;
|
||||
factory: () => T;
|
||||
cache: T | undefined;
|
||||
readonly type = "manual";
|
||||
constructor(raw: string, id: string, url: string, factory: () => T);
|
||||
resolve(): T;
|
||||
static fromJSON(data: ManualMockedModuleSerialized, factory: () => any): ManualMockedModule;
|
||||
toJSON(): ManualMockedModuleSerialized;
|
||||
}
|
||||
interface ManualMockedModuleSerialized {
|
||||
type: "manual";
|
||||
url: string;
|
||||
id: string;
|
||||
raw: string;
|
||||
}
|
||||
|
||||
type Awaitable<T> = T | PromiseLike<T>;
|
||||
type ModuleMockFactoryWithHelper<M = unknown> = (importOriginal: <T extends M = M>() => Promise<T>) => Awaitable<Partial<M>>;
|
||||
type ModuleMockFactory = () => any;
|
||||
interface ModuleMockOptions {
|
||||
spy?: boolean;
|
||||
}
|
||||
interface ServerMockResolution {
|
||||
mockType: "manual" | "redirect" | "automock" | "autospy";
|
||||
resolvedId: string;
|
||||
resolvedUrl: string;
|
||||
needsInterop?: boolean;
|
||||
redirectUrl?: string | null;
|
||||
}
|
||||
interface ServerIdResolution {
|
||||
id: string;
|
||||
url: string;
|
||||
optimized: boolean;
|
||||
}
|
||||
interface ModuleMockContext {
|
||||
/**
|
||||
* When mocking with a factory, this refers to the module that imported the mock.
|
||||
*/
|
||||
callstack: null | string[];
|
||||
}
|
||||
interface TestModuleMocker {
|
||||
queueMock(id: string, importer: string, factoryOrOptions?: ModuleMockFactory | ModuleMockOptions): void;
|
||||
queueUnmock(id: string, importer: string): void;
|
||||
importActual<T>(rawId: string, importer: string, callstack?: string[] | null): Promise<T>;
|
||||
importMock(rawId: string, importer: string): Promise<any>;
|
||||
mockObject(object: Record<string | symbol, any>, moduleType?: "automock" | "autospy"): Record<string | symbol, any>;
|
||||
mockObject(object: Record<string | symbol, any>, mockExports: Record<string | symbol, any> | undefined, moduleType?: "automock" | "autospy"): Record<string | symbol, any>;
|
||||
getMockContext(): ModuleMockContext;
|
||||
reset(): void;
|
||||
}
|
||||
|
||||
export { AutomockedModule as A, MockerRegistry as M, RedirectedModule as R, AutospiedModule as h, ManualMockedModule as j };
|
||||
export type { ServerMockResolution as S, TestModuleMocker as T, MockedModule as a, ModuleMockOptions as b, ModuleMockFactoryWithHelper as c, MockedModuleType as d, ModuleMockContext as e, ServerIdResolution as f, AutomockedModuleSerialized as g, AutospiedModuleSerialized as i, ManualMockedModuleSerialized as k, MockedModuleSerialized as l, ModuleMockFactory as m, RedirectedModuleSerialized as n };
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"main": "../../cjs/_create_super.cjs",
|
||||
"module": "../../esm/_create_super.js"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import Dispatcher from './dispatcher'
|
||||
|
||||
export default Dispatcher1Wrapper
|
||||
|
||||
declare class Dispatcher1Wrapper extends Dispatcher {
|
||||
constructor (dispatcher: Dispatcher)
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
import { __exportAll, __reExport, __toCommonJS, __toESM } from './experimental-runtime-base.mjs';
|
||||
// @ts-check
|
||||
|
||||
class Module {
|
||||
/**
|
||||
* @type {{ exports: any }}
|
||||
*/
|
||||
exportsHolder = { exports: null };
|
||||
/**
|
||||
* @type {string}
|
||||
*/
|
||||
id;
|
||||
|
||||
/**
|
||||
* @param {string} id
|
||||
*/
|
||||
constructor(id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
get exports() {
|
||||
return this.exportsHolder.exports;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiler-emitted module-graph delta — pure topology (static + dynamic edges).
|
||||
* `ids[0, localCount)` are the modules this payload carries; `ids[localCount, …)` are foreign edge targets.
|
||||
* `edges[i]` / `dynamicEdges[i]` are the static / dynamic-`import()` out-edges of `ids[i]`.
|
||||
* @typedef {{ ids: string[], localCount: number, edges: number[][], dynamicEdges?: number[][] }} ModuleGraphDelta
|
||||
* @typedef {{ createModuleHotContext(moduleId: string): any, onModuleCacheRemoval(moduleId: string): void }} DevRuntimeHooks
|
||||
*/
|
||||
|
||||
export class MissingFactoryError extends Error {
|
||||
/**
|
||||
* @param {string} id
|
||||
*/
|
||||
constructor(id) {
|
||||
super(`No factory registered for module ${id}`);
|
||||
this.id = id;
|
||||
}
|
||||
}
|
||||
|
||||
export class DevRuntime {
|
||||
/**
|
||||
* Client ID generated at runtime initialization, used for lazy compilation requests.
|
||||
* @type {string}
|
||||
*/
|
||||
clientId;
|
||||
|
||||
/**
|
||||
* @param {string} clientId
|
||||
*/
|
||||
constructor(clientId) {
|
||||
this.clientId = clientId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Static import edges from `registerGraph` — entries persist across `removeModuleCache`
|
||||
* and change only by replacement from a newer payload (last write wins).
|
||||
* @type {Map<string, { edges: string[] }>}
|
||||
*/
|
||||
staticImports = new Map();
|
||||
/**
|
||||
* Reverse index over the static imports.
|
||||
* @type {Map<string, Set<string>>}
|
||||
*/
|
||||
importers = new Map();
|
||||
/**
|
||||
* Dynamic `import()` edges from `registerGraph`, keyed by importer — mirror of
|
||||
* `staticImports` for the dynamic reverse index.
|
||||
* @type {Map<string, { edges: string[] }>}
|
||||
*/
|
||||
dynamicImports = new Map();
|
||||
/**
|
||||
* Reverse index over the dynamic imports.
|
||||
* @type {Map<string, Set<string>>}
|
||||
*/
|
||||
dynamicImporters = new Map();
|
||||
/**
|
||||
* The module cache. Membership means "this module's side effects ran in this tab" —
|
||||
* registration is emitted ahead of every module body, and nothing un-registers on
|
||||
* unwind, so a factory that throws mid-body stays registered. A `Map` rather than a
|
||||
* plain object: HMR eviction deletes entries, and a `delete` on an object drops V8
|
||||
* into dictionary mode, taxing every later lookup on the hottest read path.
|
||||
* @type {Map<string, Module>}
|
||||
*/
|
||||
moduleCache = new Map();
|
||||
/**
|
||||
* Re-runnable factories from HMR patches and lazy chunks. The initial bundle stays
|
||||
* scope-hoisted and contributes none.
|
||||
* @type {Map<string, { kind: 'esm' | 'cjs', fn: (id: string) => void }>}
|
||||
*/
|
||||
factories = new Map();
|
||||
/**
|
||||
* Installed by the dev client at boot. The runtime is a store + executor and makes
|
||||
* no HMR decisions; accepting, disposing, and reloading live behind these hooks.
|
||||
* @type {DevRuntimeHooks | null}
|
||||
*/
|
||||
hooks = null;
|
||||
|
||||
/**
|
||||
* @param {ModuleGraphDelta} delta
|
||||
*/
|
||||
registerGraph(delta) {
|
||||
for (let i = 0; i < delta.localCount; i++) {
|
||||
const id = delta.ids[i];
|
||||
const edges = delta.edges[i].map((j) => delta.ids[j]);
|
||||
for (const target of this.staticImports.get(id)?.edges ?? []) {
|
||||
this.importers.get(target)?.delete(id);
|
||||
}
|
||||
for (const target of edges) {
|
||||
let importerSet = this.importers.get(target);
|
||||
if (!importerSet) {
|
||||
importerSet = new Set();
|
||||
this.importers.set(target, importerSet);
|
||||
}
|
||||
importerSet.add(id);
|
||||
}
|
||||
this.staticImports.set(id, { edges });
|
||||
|
||||
// Dynamic `import()` edges are maintained in a parallel reverse index with the same
|
||||
// last-write-wins bookkeeping; `getImporters` unions the two.
|
||||
const dynamicEdges = (delta.dynamicEdges?.[i] ?? []).map((j) => delta.ids[j]);
|
||||
for (const target of this.dynamicImports.get(id)?.edges ?? []) {
|
||||
this.dynamicImporters.get(target)?.delete(id);
|
||||
}
|
||||
for (const target of dynamicEdges) {
|
||||
let importerSet = this.dynamicImporters.get(target);
|
||||
if (!importerSet) {
|
||||
importerSet = new Set();
|
||||
this.dynamicImporters.set(target, importerSet);
|
||||
}
|
||||
importerSet.add(id);
|
||||
}
|
||||
this.dynamicImports.set(id, { edges: dynamicEdges });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} id
|
||||
* @param {'esm' | 'cjs'} kind
|
||||
* @param {(id: string) => void} fn
|
||||
*/
|
||||
registerFactory(id, kind, fn) {
|
||||
this.factories.set(id, { kind, fn });
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} id
|
||||
* @param {{ exports: any }} exportsHolder
|
||||
*/
|
||||
registerModule(id, exportsHolder) {
|
||||
const module = new Module(id);
|
||||
module.exportsHolder = exportsHolder;
|
||||
this.moduleCache.set(id, module);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} id
|
||||
* @returns {string[]}
|
||||
*/
|
||||
getImporters(id) {
|
||||
// Static ∪ dynamic importers — the boundary walk treats both kinds the same (parity
|
||||
// with Vite `node.importers` / webpack `module.parents`). Deduped so a module that
|
||||
// imports `id` both statically and via `import()` appears once.
|
||||
const dynamic = this.dynamicImporters.get(id);
|
||||
if (!dynamic || dynamic.size === 0) {
|
||||
return [...(this.importers.get(id) ?? [])];
|
||||
}
|
||||
return [...new Set([...(this.importers.get(id) ?? []), ...dynamic])];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} id
|
||||
*/
|
||||
isExecuted(id) {
|
||||
return this.moduleCache.has(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} id
|
||||
*/
|
||||
hasFactory(id) {
|
||||
return this.factories.has(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Module-cache delete only — static imports and factories persist. Removal is what
|
||||
* re-arms a cache-gated factory for `initModule`.
|
||||
* @param {string} id
|
||||
*/
|
||||
removeModuleCache(id) {
|
||||
this.moduleCache.delete(id);
|
||||
this.hooks?.onModuleCacheRemoval(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* The one re-execution gate: registered → return the live exports; otherwise run the
|
||||
* mapped factory (which registers itself first, then runs the body).
|
||||
* @param {string} id
|
||||
*/
|
||||
initModule(id) {
|
||||
if (this.moduleCache.has(id)) {
|
||||
return this.loadExports(id);
|
||||
}
|
||||
const factory = this.factories.get(id);
|
||||
if (!factory) {
|
||||
throw new MissingFactoryError(id);
|
||||
}
|
||||
factory.fn(id);
|
||||
return this.loadExports(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} id
|
||||
*/
|
||||
loadExports(id) {
|
||||
const module = this.moduleCache.get(id);
|
||||
if (module) {
|
||||
return module.exportsHolder.exports;
|
||||
} else {
|
||||
console.warn(`Module ${id} not found`);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} moduleId
|
||||
*/
|
||||
createModuleHotContext(moduleId) {
|
||||
if (this.hooks) {
|
||||
return this.hooks.createModuleHotContext(moduleId);
|
||||
}
|
||||
throw new Error('createModuleHotContext requires installed hooks or an override');
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
// @ts-expect-error The variable will be injected at build time.
|
||||
__toESM = __toESM;
|
||||
/** @internal */
|
||||
// @ts-expect-error The variable will be injected at build time.
|
||||
__toCommonJS = __toCommonJS;
|
||||
/** @internal */
|
||||
// @ts-expect-error The variable will be injected at build time.
|
||||
__exportAll = __exportAll;
|
||||
/**
|
||||
* @param {boolean} [isNodeMode]
|
||||
* @returns {(mod: any) => any}
|
||||
* @internal
|
||||
*/
|
||||
// @ts-expect-error The variable will be injected at build time.
|
||||
__toDynamicImportESM = (isNodeMode) => (mod) => __toESM(mod.default, isNodeMode);
|
||||
/** @internal */
|
||||
// @ts-expect-error The variable will be injected at build time.
|
||||
__reExport = __reExport;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
'use strict'
|
||||
|
||||
const build = require('pino-abstract-transport')
|
||||
const { pipeline, Transform } = require('node:stream')
|
||||
module.exports = () => {
|
||||
return build(function (source) {
|
||||
const myTransportStream = new Transform({
|
||||
autoDestroy: true,
|
||||
objectMode: true,
|
||||
transform (chunk, enc, cb) {
|
||||
const {
|
||||
time,
|
||||
level,
|
||||
[source.messageKey]: body,
|
||||
[source.errorKey]: error,
|
||||
...attributes
|
||||
} = chunk
|
||||
this.push(JSON.stringify({
|
||||
severityText: source.levels.labels[level],
|
||||
body,
|
||||
attributes,
|
||||
...(error && { error })
|
||||
}))
|
||||
cb()
|
||||
}
|
||||
})
|
||||
pipeline(source, myTransportStream, () => {})
|
||||
return myTransportStream
|
||||
}, {
|
||||
enablePipelining: true,
|
||||
expectPinoConfig: true
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,924 @@
|
||||
/*! *****************************************************************************
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
||||
this file except in compliance with the License. You may obtain a copy of the
|
||||
License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
||||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
||||
MERCHANTABLITY OR NON-INFRINGEMENT.
|
||||
|
||||
See the Apache Version 2.0 License for specific language governing permissions
|
||||
and limitations under the License.
|
||||
***************************************************************************** */
|
||||
|
||||
|
||||
/// <reference no-default-lib="true"/>
|
||||
|
||||
interface Array<T> {
|
||||
/**
|
||||
* Returns the value of the last element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate findLast calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, findLast
|
||||
* immediately returns that element value. Otherwise, findLast returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLast<S extends T>(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S | undefined;
|
||||
findLast(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the last element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLastIndex(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): number;
|
||||
|
||||
/**
|
||||
* Returns a copy of an array with its elements reversed.
|
||||
*/
|
||||
toReversed(): T[];
|
||||
|
||||
/**
|
||||
* Returns a copy of an array with its elements sorted.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
|
||||
* ```ts
|
||||
* [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22]
|
||||
* ```
|
||||
*/
|
||||
toSorted(compareFn?: (a: T, b: T) => number): T[];
|
||||
|
||||
/**
|
||||
* Copies an array and removes elements and, if necessary, inserts new elements in their place. Returns the copied array.
|
||||
* @param start The zero-based location in the array from which to start removing elements.
|
||||
* @param deleteCount The number of elements to remove.
|
||||
* @param items Elements to insert into the copied array in place of the deleted elements.
|
||||
* @returns The copied array.
|
||||
*/
|
||||
toSpliced(start: number, deleteCount: number, ...items: T[]): T[];
|
||||
|
||||
/**
|
||||
* Copies an array and removes elements while returning the remaining elements.
|
||||
* @param start The zero-based location in the array from which to start removing elements.
|
||||
* @param deleteCount The number of elements to remove.
|
||||
* @returns A copy of the original array with the remaining elements.
|
||||
*/
|
||||
toSpliced(start: number, deleteCount?: number): T[];
|
||||
|
||||
/**
|
||||
* Copies an array, then overwrites the value at the provided index with the
|
||||
* given value. If the index is negative, then it replaces from the end
|
||||
* of the array.
|
||||
* @param index The index of the value to overwrite. If the index is
|
||||
* negative, then it replaces from the end of the array.
|
||||
* @param value The value to write into the copied array.
|
||||
* @returns The copied array with the updated value.
|
||||
*/
|
||||
with(index: number, value: T): T[];
|
||||
}
|
||||
|
||||
interface ReadonlyArray<T> {
|
||||
/**
|
||||
* Returns the value of the last element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate findLast calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, findLast
|
||||
* immediately returns that element value. Otherwise, findLast returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLast<S extends T>(
|
||||
predicate: (value: T, index: number, array: readonly T[]) => value is S,
|
||||
thisArg?: any,
|
||||
): S | undefined;
|
||||
findLast(
|
||||
predicate: (value: T, index: number, array: readonly T[]) => unknown,
|
||||
thisArg?: any,
|
||||
): T | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the last element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLastIndex(
|
||||
predicate: (value: T, index: number, array: readonly T[]) => unknown,
|
||||
thisArg?: any,
|
||||
): number;
|
||||
|
||||
/**
|
||||
* Copies the array and returns the copied array with all of its elements reversed.
|
||||
*/
|
||||
toReversed(): T[];
|
||||
|
||||
/**
|
||||
* Copies and sorts the array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
|
||||
* ```ts
|
||||
* [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22]
|
||||
* ```
|
||||
*/
|
||||
toSorted(compareFn?: (a: T, b: T) => number): T[];
|
||||
|
||||
/**
|
||||
* Copies an array and removes elements while, if necessary, inserting new elements in their place, returning the remaining elements.
|
||||
* @param start The zero-based location in the array from which to start removing elements.
|
||||
* @param deleteCount The number of elements to remove.
|
||||
* @param items Elements to insert into the copied array in place of the deleted elements.
|
||||
* @returns A copy of the original array with the remaining elements.
|
||||
*/
|
||||
toSpliced(start: number, deleteCount: number, ...items: T[]): T[];
|
||||
|
||||
/**
|
||||
* Copies an array and removes elements while returning the remaining elements.
|
||||
* @param start The zero-based location in the array from which to start removing elements.
|
||||
* @param deleteCount The number of elements to remove.
|
||||
* @returns A copy of the original array with the remaining elements.
|
||||
*/
|
||||
toSpliced(start: number, deleteCount?: number): T[];
|
||||
|
||||
/**
|
||||
* Copies an array, then overwrites the value at the provided index with the
|
||||
* given value. If the index is negative, then it replaces from the end
|
||||
* of the array
|
||||
* @param index The index of the value to overwrite. If the index is
|
||||
* negative, then it replaces from the end of the array.
|
||||
* @param value The value to insert into the copied array.
|
||||
* @returns A copy of the original array with the inserted value.
|
||||
*/
|
||||
with(index: number, value: T): T[];
|
||||
}
|
||||
|
||||
interface Int8Array {
|
||||
/**
|
||||
* Returns the value of the last element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate findLast calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, findLast
|
||||
* immediately returns that element value. Otherwise, findLast returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLast<S extends number>(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Int8Array,
|
||||
) => value is S,
|
||||
thisArg?: any,
|
||||
): S | undefined;
|
||||
findLast(
|
||||
predicate: (value: number, index: number, array: Int8Array) => unknown,
|
||||
thisArg?: any,
|
||||
): number | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the last element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLastIndex(
|
||||
predicate: (value: number, index: number, array: Int8Array) => unknown,
|
||||
thisArg?: any,
|
||||
): number;
|
||||
|
||||
/**
|
||||
* Copies the array and returns the copy with the elements in reverse order.
|
||||
*/
|
||||
toReversed(): Int8Array;
|
||||
|
||||
/**
|
||||
* Copies and sorts the array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* const myNums = Int8Array.from([11, 2, 22, 1]);
|
||||
* myNums.toSorted((a, b) => a - b) // Int8Array(4) [1, 2, 11, 22]
|
||||
* ```
|
||||
*/
|
||||
toSorted(compareFn?: (a: number, b: number) => number): Int8Array;
|
||||
|
||||
/**
|
||||
* Copies the array and inserts the given number at the provided index.
|
||||
* @param index The index of the value to overwrite. If the index is
|
||||
* negative, then it replaces from the end of the array.
|
||||
* @param value The value to insert into the copied array.
|
||||
* @returns A copy of the original array with the inserted value.
|
||||
*/
|
||||
with(index: number, value: number): Int8Array;
|
||||
}
|
||||
|
||||
interface Uint8Array {
|
||||
/**
|
||||
* Returns the value of the last element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate findLast calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, findLast
|
||||
* immediately returns that element value. Otherwise, findLast returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLast<S extends number>(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Uint8Array,
|
||||
) => value is S,
|
||||
thisArg?: any,
|
||||
): S | undefined;
|
||||
findLast(
|
||||
predicate: (value: number, index: number, array: Uint8Array) => unknown,
|
||||
thisArg?: any,
|
||||
): number | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the last element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLastIndex(
|
||||
predicate: (value: number, index: number, array: Uint8Array) => unknown,
|
||||
thisArg?: any,
|
||||
): number;
|
||||
|
||||
/**
|
||||
* Copies the array and returns the copy with the elements in reverse order.
|
||||
*/
|
||||
toReversed(): Uint8Array;
|
||||
|
||||
/**
|
||||
* Copies and sorts the array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* const myNums = Uint8Array.from([11, 2, 22, 1]);
|
||||
* myNums.toSorted((a, b) => a - b) // Uint8Array(4) [1, 2, 11, 22]
|
||||
* ```
|
||||
*/
|
||||
toSorted(compareFn?: (a: number, b: number) => number): Uint8Array;
|
||||
|
||||
/**
|
||||
* Copies the array and inserts the given number at the provided index.
|
||||
* @param index The index of the value to overwrite. If the index is
|
||||
* negative, then it replaces from the end of the array.
|
||||
* @param value The value to insert into the copied array.
|
||||
* @returns A copy of the original array with the inserted value.
|
||||
*/
|
||||
with(index: number, value: number): Uint8Array;
|
||||
}
|
||||
|
||||
interface Uint8ClampedArray {
|
||||
/**
|
||||
* Returns the value of the last element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate findLast calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, findLast
|
||||
* immediately returns that element value. Otherwise, findLast returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLast<S extends number>(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Uint8ClampedArray,
|
||||
) => value is S,
|
||||
thisArg?: any,
|
||||
): S | undefined;
|
||||
findLast(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Uint8ClampedArray,
|
||||
) => unknown,
|
||||
thisArg?: any,
|
||||
): number | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the last element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLastIndex(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Uint8ClampedArray,
|
||||
) => unknown,
|
||||
thisArg?: any,
|
||||
): number;
|
||||
|
||||
/**
|
||||
* Copies the array and returns the copy with the elements in reverse order.
|
||||
*/
|
||||
toReversed(): Uint8ClampedArray;
|
||||
|
||||
/**
|
||||
* Copies and sorts the array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* const myNums = Uint8ClampedArray.from([11, 2, 22, 1]);
|
||||
* myNums.toSorted((a, b) => a - b) // Uint8ClampedArray(4) [1, 2, 11, 22]
|
||||
* ```
|
||||
*/
|
||||
toSorted(compareFn?: (a: number, b: number) => number): Uint8ClampedArray;
|
||||
|
||||
/**
|
||||
* Copies the array and inserts the given number at the provided index.
|
||||
* @param index The index of the value to overwrite. If the index is
|
||||
* negative, then it replaces from the end of the array.
|
||||
* @param value The value to insert into the copied array.
|
||||
* @returns A copy of the original array with the inserted value.
|
||||
*/
|
||||
with(index: number, value: number): Uint8ClampedArray;
|
||||
}
|
||||
|
||||
interface Int16Array {
|
||||
/**
|
||||
* Returns the value of the last element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate findLast calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, findLast
|
||||
* immediately returns that element value. Otherwise, findLast returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLast<S extends number>(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Int16Array,
|
||||
) => value is S,
|
||||
thisArg?: any,
|
||||
): S | undefined;
|
||||
findLast(
|
||||
predicate: (value: number, index: number, array: Int16Array) => unknown,
|
||||
thisArg?: any,
|
||||
): number | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the last element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLastIndex(
|
||||
predicate: (value: number, index: number, array: Int16Array) => unknown,
|
||||
thisArg?: any,
|
||||
): number;
|
||||
|
||||
/**
|
||||
* Copies the array and returns the copy with the elements in reverse order.
|
||||
*/
|
||||
toReversed(): Int16Array;
|
||||
|
||||
/**
|
||||
* Copies and sorts the array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* const myNums = Int16Array.from([11, 2, -22, 1]);
|
||||
* myNums.toSorted((a, b) => a - b) // Int16Array(4) [-22, 1, 2, 11]
|
||||
* ```
|
||||
*/
|
||||
toSorted(compareFn?: (a: number, b: number) => number): Int16Array;
|
||||
|
||||
/**
|
||||
* Copies the array and inserts the given number at the provided index.
|
||||
* @param index The index of the value to overwrite. If the index is
|
||||
* negative, then it replaces from the end of the array.
|
||||
* @param value The value to insert into the copied array.
|
||||
* @returns A copy of the original array with the inserted value.
|
||||
*/
|
||||
with(index: number, value: number): Int16Array;
|
||||
}
|
||||
|
||||
interface Uint16Array {
|
||||
/**
|
||||
* Returns the value of the last element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate findLast calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, findLast
|
||||
* immediately returns that element value. Otherwise, findLast returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLast<S extends number>(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Uint16Array,
|
||||
) => value is S,
|
||||
thisArg?: any,
|
||||
): S | undefined;
|
||||
findLast(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Uint16Array,
|
||||
) => unknown,
|
||||
thisArg?: any,
|
||||
): number | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the last element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLastIndex(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Uint16Array,
|
||||
) => unknown,
|
||||
thisArg?: any,
|
||||
): number;
|
||||
|
||||
/**
|
||||
* Copies the array and returns the copy with the elements in reverse order.
|
||||
*/
|
||||
toReversed(): Uint16Array;
|
||||
|
||||
/**
|
||||
* Copies and sorts the array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* const myNums = Uint16Array.from([11, 2, 22, 1]);
|
||||
* myNums.toSorted((a, b) => a - b) // Uint16Array(4) [1, 2, 11, 22]
|
||||
* ```
|
||||
*/
|
||||
toSorted(compareFn?: (a: number, b: number) => number): Uint16Array;
|
||||
|
||||
/**
|
||||
* Copies the array and inserts the given number at the provided index.
|
||||
* @param index The index of the value to overwrite. If the index is
|
||||
* negative, then it replaces from the end of the array.
|
||||
* @param value The value to insert into the copied array.
|
||||
* @returns A copy of the original array with the inserted value.
|
||||
*/
|
||||
with(index: number, value: number): Uint16Array;
|
||||
}
|
||||
|
||||
interface Int32Array {
|
||||
/**
|
||||
* Returns the value of the last element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate findLast calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, findLast
|
||||
* immediately returns that element value. Otherwise, findLast returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLast<S extends number>(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Int32Array,
|
||||
) => value is S,
|
||||
thisArg?: any,
|
||||
): S | undefined;
|
||||
findLast(
|
||||
predicate: (value: number, index: number, array: Int32Array) => unknown,
|
||||
thisArg?: any,
|
||||
): number | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the last element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLastIndex(
|
||||
predicate: (value: number, index: number, array: Int32Array) => unknown,
|
||||
thisArg?: any,
|
||||
): number;
|
||||
|
||||
/**
|
||||
* Copies the array and returns the copy with the elements in reverse order.
|
||||
*/
|
||||
toReversed(): Int32Array;
|
||||
|
||||
/**
|
||||
* Copies and sorts the array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* const myNums = Int32Array.from([11, 2, -22, 1]);
|
||||
* myNums.toSorted((a, b) => a - b) // Int32Array(4) [-22, 1, 2, 11]
|
||||
* ```
|
||||
*/
|
||||
toSorted(compareFn?: (a: number, b: number) => number): Int32Array;
|
||||
|
||||
/**
|
||||
* Copies the array and inserts the given number at the provided index.
|
||||
* @param index The index of the value to overwrite. If the index is
|
||||
* negative, then it replaces from the end of the array.
|
||||
* @param value The value to insert into the copied array.
|
||||
* @returns A copy of the original array with the inserted value.
|
||||
*/
|
||||
with(index: number, value: number): Int32Array;
|
||||
}
|
||||
|
||||
interface Uint32Array {
|
||||
/**
|
||||
* Returns the value of the last element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate findLast calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, findLast
|
||||
* immediately returns that element value. Otherwise, findLast returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLast<S extends number>(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Uint32Array,
|
||||
) => value is S,
|
||||
thisArg?: any,
|
||||
): S | undefined;
|
||||
findLast(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Uint32Array,
|
||||
) => unknown,
|
||||
thisArg?: any,
|
||||
): number | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the last element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLastIndex(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Uint32Array,
|
||||
) => unknown,
|
||||
thisArg?: any,
|
||||
): number;
|
||||
|
||||
/**
|
||||
* Copies the array and returns the copy with the elements in reverse order.
|
||||
*/
|
||||
toReversed(): Uint32Array;
|
||||
|
||||
/**
|
||||
* Copies and sorts the array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* const myNums = Uint32Array.from([11, 2, 22, 1]);
|
||||
* myNums.toSorted((a, b) => a - b) // Uint32Array(4) [1, 2, 11, 22]
|
||||
* ```
|
||||
*/
|
||||
toSorted(compareFn?: (a: number, b: number) => number): Uint32Array;
|
||||
|
||||
/**
|
||||
* Copies the array and inserts the given number at the provided index.
|
||||
* @param index The index of the value to overwrite. If the index is
|
||||
* negative, then it replaces from the end of the array.
|
||||
* @param value The value to insert into the copied array.
|
||||
* @returns A copy of the original array with the inserted value.
|
||||
*/
|
||||
with(index: number, value: number): Uint32Array;
|
||||
}
|
||||
|
||||
interface Float32Array {
|
||||
/**
|
||||
* Returns the value of the last element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate findLast calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, findLast
|
||||
* immediately returns that element value. Otherwise, findLast returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLast<S extends number>(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Float32Array,
|
||||
) => value is S,
|
||||
thisArg?: any,
|
||||
): S | undefined;
|
||||
findLast(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Float32Array,
|
||||
) => unknown,
|
||||
thisArg?: any,
|
||||
): number | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the last element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLastIndex(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Float32Array,
|
||||
) => unknown,
|
||||
thisArg?: any,
|
||||
): number;
|
||||
|
||||
/**
|
||||
* Copies the array and returns the copy with the elements in reverse order.
|
||||
*/
|
||||
toReversed(): Float32Array;
|
||||
|
||||
/**
|
||||
* Copies and sorts the array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* const myNums = Float32Array.from([11.25, 2, -22.5, 1]);
|
||||
* myNums.toSorted((a, b) => a - b) // Float32Array(4) [-22.5, 1, 2, 11.5]
|
||||
* ```
|
||||
*/
|
||||
toSorted(compareFn?: (a: number, b: number) => number): Float32Array;
|
||||
|
||||
/**
|
||||
* Copies the array and inserts the given number at the provided index.
|
||||
* @param index The index of the value to overwrite. If the index is
|
||||
* negative, then it replaces from the end of the array.
|
||||
* @param value The value to insert into the copied array.
|
||||
* @returns A copy of the original array with the inserted value.
|
||||
*/
|
||||
with(index: number, value: number): Float32Array;
|
||||
}
|
||||
|
||||
interface Float64Array {
|
||||
/**
|
||||
* Returns the value of the last element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate findLast calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, findLast
|
||||
* immediately returns that element value. Otherwise, findLast returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLast<S extends number>(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Float64Array,
|
||||
) => value is S,
|
||||
thisArg?: any,
|
||||
): S | undefined;
|
||||
findLast(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Float64Array,
|
||||
) => unknown,
|
||||
thisArg?: any,
|
||||
): number | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the last element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLastIndex(
|
||||
predicate: (
|
||||
value: number,
|
||||
index: number,
|
||||
array: Float64Array,
|
||||
) => unknown,
|
||||
thisArg?: any,
|
||||
): number;
|
||||
|
||||
/**
|
||||
* Copies the array and returns the copy with the elements in reverse order.
|
||||
*/
|
||||
toReversed(): Float64Array;
|
||||
|
||||
/**
|
||||
* Copies and sorts the array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* const myNums = Float64Array.from([11.25, 2, -22.5, 1]);
|
||||
* myNums.toSorted((a, b) => a - b) // Float64Array(4) [-22.5, 1, 2, 11.5]
|
||||
* ```
|
||||
*/
|
||||
toSorted(compareFn?: (a: number, b: number) => number): Float64Array;
|
||||
|
||||
/**
|
||||
* Copies the array and inserts the given number at the provided index.
|
||||
* @param index The index of the value to overwrite. If the index is
|
||||
* negative, then it replaces from the end of the array.
|
||||
* @param value The value to insert into the copied array.
|
||||
* @returns A copy of the original array with the inserted value.
|
||||
*/
|
||||
with(index: number, value: number): Float64Array;
|
||||
}
|
||||
|
||||
interface BigInt64Array {
|
||||
/**
|
||||
* Returns the value of the last element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate findLast calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, findLast
|
||||
* immediately returns that element value. Otherwise, findLast returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLast<S extends bigint>(
|
||||
predicate: (
|
||||
value: bigint,
|
||||
index: number,
|
||||
array: BigInt64Array,
|
||||
) => value is S,
|
||||
thisArg?: any,
|
||||
): S | undefined;
|
||||
findLast(
|
||||
predicate: (
|
||||
value: bigint,
|
||||
index: number,
|
||||
array: BigInt64Array,
|
||||
) => unknown,
|
||||
thisArg?: any,
|
||||
): bigint | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the last element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLastIndex(
|
||||
predicate: (
|
||||
value: bigint,
|
||||
index: number,
|
||||
array: BigInt64Array,
|
||||
) => unknown,
|
||||
thisArg?: any,
|
||||
): number;
|
||||
|
||||
/**
|
||||
* Copies the array and returns the copy with the elements in reverse order.
|
||||
*/
|
||||
toReversed(): BigInt64Array;
|
||||
|
||||
/**
|
||||
* Copies and sorts the array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* const myNums = BigInt64Array.from([11n, 2n, -22n, 1n]);
|
||||
* myNums.toSorted((a, b) => Number(a - b)) // BigInt64Array(4) [-22n, 1n, 2n, 11n]
|
||||
* ```
|
||||
*/
|
||||
toSorted(compareFn?: (a: bigint, b: bigint) => number): BigInt64Array;
|
||||
|
||||
/**
|
||||
* Copies the array and inserts the given bigint at the provided index.
|
||||
* @param index The index of the value to overwrite. If the index is
|
||||
* negative, then it replaces from the end of the array.
|
||||
* @param value The value to insert into the copied array.
|
||||
* @returns A copy of the original array with the inserted value.
|
||||
*/
|
||||
with(index: number, value: bigint): BigInt64Array;
|
||||
}
|
||||
|
||||
interface BigUint64Array {
|
||||
/**
|
||||
* Returns the value of the last element in the array where predicate is true, and undefined
|
||||
* otherwise.
|
||||
* @param predicate findLast calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found, findLast
|
||||
* immediately returns that element value. Otherwise, findLast returns undefined.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLast<S extends bigint>(
|
||||
predicate: (
|
||||
value: bigint,
|
||||
index: number,
|
||||
array: BigUint64Array,
|
||||
) => value is S,
|
||||
thisArg?: any,
|
||||
): S | undefined;
|
||||
findLast(
|
||||
predicate: (
|
||||
value: bigint,
|
||||
index: number,
|
||||
array: BigUint64Array,
|
||||
) => unknown,
|
||||
thisArg?: any,
|
||||
): bigint | undefined;
|
||||
|
||||
/**
|
||||
* Returns the index of the last element in the array where predicate is true, and -1
|
||||
* otherwise.
|
||||
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
|
||||
* order, until it finds one where predicate returns true. If such an element is found,
|
||||
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
|
||||
* @param thisArg If provided, it will be used as the this value for each invocation of
|
||||
* predicate. If it is not provided, undefined is used instead.
|
||||
*/
|
||||
findLastIndex(
|
||||
predicate: (
|
||||
value: bigint,
|
||||
index: number,
|
||||
array: BigUint64Array,
|
||||
) => unknown,
|
||||
thisArg?: any,
|
||||
): number;
|
||||
|
||||
/**
|
||||
* Copies the array and returns the copy with the elements in reverse order.
|
||||
*/
|
||||
toReversed(): BigUint64Array;
|
||||
|
||||
/**
|
||||
* Copies and sorts the array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* const myNums = BigUint64Array.from([11n, 2n, 22n, 1n]);
|
||||
* myNums.toSorted((a, b) => Number(a - b)) // BigUint64Array(4) [1n, 2n, 11n, 22n]
|
||||
* ```
|
||||
*/
|
||||
toSorted(compareFn?: (a: bigint, b: bigint) => number): BigUint64Array;
|
||||
|
||||
/**
|
||||
* Copies the array and inserts the given bigint at the provided index.
|
||||
* @param index The index of the value to overwrite. If the index is
|
||||
* negative, then it replaces from the end of the array.
|
||||
* @param value The value to insert into the copied array.
|
||||
* @returns A copy of the original array with the inserted value.
|
||||
*/
|
||||
with(index: number, value: bigint): BigUint64Array;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
'use strict'
|
||||
|
||||
const { test } = require('tap')
|
||||
const fs = require('fs')
|
||||
const proxyquire = require('proxyquire')
|
||||
const { file } = require('./helper')
|
||||
|
||||
test('fsync with sync', (t) => {
|
||||
t.plan(5)
|
||||
|
||||
const fakeFs = Object.create(fs)
|
||||
fakeFs.fsyncSync = function (fd) {
|
||||
t.pass('fake fs.fsyncSync called')
|
||||
return fs.fsyncSync(fd)
|
||||
}
|
||||
const SonicBoom = proxyquire('../', {
|
||||
fs: fakeFs
|
||||
})
|
||||
|
||||
const dest = file()
|
||||
const fd = fs.openSync(dest, 'w')
|
||||
const stream = new SonicBoom({ fd, sync: true, fsync: true })
|
||||
|
||||
t.ok(stream.write('hello world\n'))
|
||||
t.ok(stream.write('something else\n'))
|
||||
|
||||
stream.end()
|
||||
|
||||
const data = fs.readFileSync(dest, 'utf8')
|
||||
t.equal(data, 'hello world\nsomething else\n')
|
||||
})
|
||||
|
||||
test('fsync with async', (t) => {
|
||||
t.plan(7)
|
||||
|
||||
const fakeFs = Object.create(fs)
|
||||
fakeFs.fsyncSync = function (fd) {
|
||||
t.pass('fake fs.fsyncSync called')
|
||||
return fs.fsyncSync(fd)
|
||||
}
|
||||
const SonicBoom = proxyquire('../', {
|
||||
fs: fakeFs
|
||||
})
|
||||
|
||||
const dest = file()
|
||||
const fd = fs.openSync(dest, 'w')
|
||||
const stream = new SonicBoom({ fd, fsync: true })
|
||||
|
||||
t.ok(stream.write('hello world\n'))
|
||||
t.ok(stream.write('something else\n'))
|
||||
|
||||
stream.end()
|
||||
|
||||
stream.on('finish', () => {
|
||||
fs.readFile(dest, 'utf8', (err, data) => {
|
||||
t.error(err)
|
||||
t.equal(data, 'hello world\nsomething else\n')
|
||||
})
|
||||
})
|
||||
stream.on('close', () => {
|
||||
t.pass('close emitted')
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* @fileoverview Define 2 token factories; forward and backward.
|
||||
* @author Toru Nagashima
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const BackwardTokenCommentCursor = require("./backward-token-comment-cursor");
|
||||
const BackwardTokenCursor = require("./backward-token-cursor");
|
||||
const FilterCursor = require("./filter-cursor");
|
||||
const ForwardTokenCommentCursor = require("./forward-token-comment-cursor");
|
||||
const ForwardTokenCursor = require("./forward-token-cursor");
|
||||
const LimitCursor = require("./limit-cursor");
|
||||
const SkipCursor = require("./skip-cursor");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The cursor factory.
|
||||
* @private
|
||||
*/
|
||||
class CursorFactory {
|
||||
/**
|
||||
* Initializes this cursor.
|
||||
* @param {Function} TokenCursor The class of the cursor which iterates tokens only.
|
||||
* @param {Function} TokenCommentCursor The class of the cursor which iterates the mix of tokens and comments.
|
||||
*/
|
||||
constructor(TokenCursor, TokenCommentCursor) {
|
||||
this.TokenCursor = TokenCursor;
|
||||
this.TokenCommentCursor = TokenCommentCursor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a base cursor instance that can be decorated by createCursor.
|
||||
* @param {Token[]} tokens The array of tokens.
|
||||
* @param {Comment[]} comments The array of comments.
|
||||
* @param {Object} indexMap The map from locations to indices in `tokens`.
|
||||
* @param {number} startLoc The start location of the iteration range.
|
||||
* @param {number} endLoc The end location of the iteration range.
|
||||
* @param {boolean} includeComments The flag to iterate comments as well.
|
||||
* @returns {Cursor} The created base cursor.
|
||||
*/
|
||||
createBaseCursor(
|
||||
tokens,
|
||||
comments,
|
||||
indexMap,
|
||||
startLoc,
|
||||
endLoc,
|
||||
includeComments,
|
||||
) {
|
||||
const Cursor = includeComments
|
||||
? this.TokenCommentCursor
|
||||
: this.TokenCursor;
|
||||
|
||||
return new Cursor(tokens, comments, indexMap, startLoc, endLoc);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a cursor that iterates tokens with normalized options.
|
||||
* @param {Token[]} tokens The array of tokens.
|
||||
* @param {Comment[]} comments The array of comments.
|
||||
* @param {Object} indexMap The map from locations to indices in `tokens`.
|
||||
* @param {number} startLoc The start location of the iteration range.
|
||||
* @param {number} endLoc The end location of the iteration range.
|
||||
* @param {boolean} includeComments The flag to iterate comments as well.
|
||||
* @param {Function|null} filter The predicate function to choose tokens.
|
||||
* @param {number} skip The count of tokens the cursor skips.
|
||||
* @param {number} count The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility.
|
||||
* @returns {Cursor} The created cursor.
|
||||
*/
|
||||
createCursor(
|
||||
tokens,
|
||||
comments,
|
||||
indexMap,
|
||||
startLoc,
|
||||
endLoc,
|
||||
includeComments,
|
||||
filter,
|
||||
skip,
|
||||
count,
|
||||
) {
|
||||
let cursor = this.createBaseCursor(
|
||||
tokens,
|
||||
comments,
|
||||
indexMap,
|
||||
startLoc,
|
||||
endLoc,
|
||||
includeComments,
|
||||
);
|
||||
|
||||
if (filter) {
|
||||
cursor = new FilterCursor(cursor, filter);
|
||||
}
|
||||
if (skip >= 1) {
|
||||
cursor = new SkipCursor(cursor, skip);
|
||||
}
|
||||
if (count >= 0) {
|
||||
cursor = new LimitCursor(cursor, count);
|
||||
}
|
||||
|
||||
return cursor;
|
||||
}
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Exports
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
module.exports = {
|
||||
forward: new CursorFactory(ForwardTokenCursor, ForwardTokenCommentCursor),
|
||||
backward: new CursorFactory(
|
||||
BackwardTokenCursor,
|
||||
BackwardTokenCommentCursor,
|
||||
),
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
"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 = void 0;
|
||||
const es2017_1 = require("./es2017");
|
||||
const es2018_asyncgenerator_1 = require("./es2018.asyncgenerator");
|
||||
const es2018_asynciterable_1 = require("./es2018.asynciterable");
|
||||
const es2018_intl_1 = require("./es2018.intl");
|
||||
const es2018_promise_1 = require("./es2018.promise");
|
||||
const es2018_regexp_1 = require("./es2018.regexp");
|
||||
exports.es2018 = {
|
||||
libs: [
|
||||
es2017_1.es2017,
|
||||
es2018_asynciterable_1.es2018_asynciterable,
|
||||
es2018_asyncgenerator_1.es2018_asyncgenerator,
|
||||
es2018_promise_1.es2018_promise,
|
||||
es2018_regexp_1.es2018_regexp,
|
||||
es2018_intl_1.es2018_intl,
|
||||
],
|
||||
variables: [],
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
export {};
|
||||
|
||||
import { webcrypto } from "crypto";
|
||||
|
||||
type _Crypto = typeof globalThis extends { onmessage: any } ? {} : webcrypto.Crypto;
|
||||
type _CryptoKey = typeof globalThis extends { onmessage: any } ? {} : webcrypto.CryptoKey;
|
||||
type _SubtleCrypto = typeof globalThis extends { onmessage: any } ? {} : webcrypto.SubtleCrypto;
|
||||
|
||||
declare global {
|
||||
interface Crypto extends _Crypto {}
|
||||
var Crypto: typeof globalThis extends { onmessage: any; Crypto: infer T } ? T : {
|
||||
prototype: webcrypto.Crypto;
|
||||
new(): webcrypto.Crypto;
|
||||
};
|
||||
|
||||
interface CryptoKey extends _CryptoKey {}
|
||||
var CryptoKey: typeof globalThis extends { onmessage: any; CryptoKey: infer T } ? T : {
|
||||
prototype: webcrypto.CryptoKey;
|
||||
new(): webcrypto.CryptoKey;
|
||||
};
|
||||
|
||||
interface SubtleCrypto extends _SubtleCrypto {}
|
||||
var SubtleCrypto: typeof globalThis extends { onmessage: any; SubtleCrypto: infer T } ? T : {
|
||||
prototype: webcrypto.SubtleCrypto;
|
||||
new(): webcrypto.SubtleCrypto;
|
||||
supports(
|
||||
operation: string,
|
||||
algorithm: webcrypto.AlgorithmIdentifier,
|
||||
length?: number,
|
||||
): boolean;
|
||||
supports(
|
||||
operation: string,
|
||||
algorithm: webcrypto.AlgorithmIdentifier,
|
||||
additionalAlgorithm: webcrypto.AlgorithmIdentifier,
|
||||
): boolean;
|
||||
};
|
||||
|
||||
var crypto: typeof globalThis extends { onmessage: any; crypto: infer T } ? T : webcrypto.Crypto;
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
const tsutils = __importStar(require("ts-api-utils"));
|
||||
const ts = __importStar(require("typescript"));
|
||||
const util_1 = require("../util");
|
||||
var Usefulness;
|
||||
(function (Usefulness) {
|
||||
Usefulness["Always"] = "always";
|
||||
Usefulness["Never"] = "will";
|
||||
Usefulness["Sometimes"] = "may";
|
||||
})(Usefulness || (Usefulness = {}));
|
||||
const canHaveTypeParameters = (declaration) => {
|
||||
return (ts.isTypeAliasDeclaration(declaration) ||
|
||||
ts.isInterfaceDeclaration(declaration) ||
|
||||
ts.isClassDeclaration(declaration));
|
||||
};
|
||||
exports.default = (0, util_1.createRule)({
|
||||
name: 'no-base-to-string',
|
||||
meta: {
|
||||
type: 'suggestion',
|
||||
docs: {
|
||||
description: 'Require `.toString()` and `.toLocaleString()` to only be called on objects which provide useful information when stringified',
|
||||
recommended: 'recommended',
|
||||
requiresTypeChecking: true,
|
||||
},
|
||||
messages: {
|
||||
baseArrayJoin: "Using `join()` for {{name}} {{certainty}} use Object's default stringification format ('[object Object]') when stringified.",
|
||||
baseToString: "'{{name}}' {{certainty}} use Object's default stringification format ('[object Object]') when stringified.",
|
||||
},
|
||||
schema: [
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
checkUnknown: {
|
||||
type: 'boolean',
|
||||
description: 'Whether to also check values of type `unknown`',
|
||||
},
|
||||
ignoredTypeNames: {
|
||||
type: 'array',
|
||||
description: 'Stringified type names to ignore.',
|
||||
items: {
|
||||
type: 'string',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
defaultOptions: [
|
||||
{
|
||||
checkUnknown: false,
|
||||
ignoredTypeNames: ['Error', 'RegExp', 'URL', 'URLSearchParams'],
|
||||
},
|
||||
],
|
||||
create(context, [option]) {
|
||||
const services = (0, util_1.getParserServices)(context);
|
||||
const { program } = services;
|
||||
const checker = program.getTypeChecker();
|
||||
const ignoredTypeNames = option.ignoredTypeNames ?? [];
|
||||
function checkExpression(node, type) {
|
||||
if (node.type === utils_1.AST_NODE_TYPES.Literal) {
|
||||
return;
|
||||
}
|
||||
const certainty = collectToStringCertainty(type ?? services.getTypeAtLocation(node), new Set());
|
||||
if (certainty === Usefulness.Always) {
|
||||
return;
|
||||
}
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'baseToString',
|
||||
data: {
|
||||
name: context.sourceCode.getText(node),
|
||||
certainty,
|
||||
},
|
||||
});
|
||||
}
|
||||
function checkExpressionForArrayJoin(node, type) {
|
||||
const certainty = collectJoinCertainty(type, new Set());
|
||||
if (certainty === Usefulness.Always) {
|
||||
return;
|
||||
}
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'baseArrayJoin',
|
||||
data: {
|
||||
name: context.sourceCode.getText(node),
|
||||
certainty,
|
||||
},
|
||||
});
|
||||
}
|
||||
function collectUnionTypeCertainty(type, collectSubTypeCertainty) {
|
||||
const certainties = type.types.map(t => collectSubTypeCertainty(t));
|
||||
if (certainties.every(certainty => certainty === Usefulness.Never)) {
|
||||
return Usefulness.Never;
|
||||
}
|
||||
if (certainties.every(certainty => certainty === Usefulness.Always)) {
|
||||
return Usefulness.Always;
|
||||
}
|
||||
return Usefulness.Sometimes;
|
||||
}
|
||||
function collectIntersectionTypeCertainty(type, collectSubTypeCertainty) {
|
||||
for (const subType of type.types) {
|
||||
const subtypeUsefulness = collectSubTypeCertainty(subType);
|
||||
if (subtypeUsefulness === Usefulness.Always) {
|
||||
return Usefulness.Always;
|
||||
}
|
||||
}
|
||||
return Usefulness.Never;
|
||||
}
|
||||
function collectTupleCertainty(type, visited) {
|
||||
const typeArgs = checker.getTypeArguments(type);
|
||||
const certainties = typeArgs.map(t => collectToStringCertainty(t, visited));
|
||||
if (certainties.some(certainty => certainty === Usefulness.Never)) {
|
||||
return Usefulness.Never;
|
||||
}
|
||||
if (certainties.some(certainty => certainty === Usefulness.Sometimes)) {
|
||||
return Usefulness.Sometimes;
|
||||
}
|
||||
return Usefulness.Always;
|
||||
}
|
||||
function collectArrayCertainty(type, visited) {
|
||||
const elemType = (0, util_1.nullThrows)(type.getNumberIndexType(), 'array should have number index type');
|
||||
return collectToStringCertainty(elemType, visited);
|
||||
}
|
||||
function collectJoinCertainty(type, visited) {
|
||||
if (tsutils.isUnionType(type)) {
|
||||
return collectUnionTypeCertainty(type, t => collectJoinCertainty(t, visited));
|
||||
}
|
||||
if (tsutils.isIntersectionType(type)) {
|
||||
return collectIntersectionTypeCertainty(type, t => collectJoinCertainty(t, visited));
|
||||
}
|
||||
if (checker.isTupleType(type)) {
|
||||
return collectTupleCertainty(type, visited);
|
||||
}
|
||||
if (checker.isArrayType(type)) {
|
||||
return collectArrayCertainty(type, visited);
|
||||
}
|
||||
return Usefulness.Always;
|
||||
}
|
||||
function collectToStringCertainty(type, visited) {
|
||||
if (visited.has(type)) {
|
||||
// don't report if this is a self referencing array or tuple type
|
||||
return Usefulness.Always;
|
||||
}
|
||||
if (tsutils.isTypeParameter(type)) {
|
||||
const constraint = type.getConstraint();
|
||||
if (constraint) {
|
||||
return collectToStringCertainty(constraint, visited);
|
||||
}
|
||||
// unconstrained generic means `unknown`
|
||||
return option.checkUnknown ? Usefulness.Sometimes : Usefulness.Always;
|
||||
}
|
||||
// the Boolean type definition missing toString()
|
||||
if (tsutils.isTypeFlagSet(type, ts.TypeFlags.Boolean) ||
|
||||
tsutils.isTypeFlagSet(type, ts.TypeFlags.BooleanLiteral)) {
|
||||
return Usefulness.Always;
|
||||
}
|
||||
const symbol = type.aliasSymbol ?? type.getSymbol();
|
||||
const decl = symbol?.getDeclarations()?.[0];
|
||||
if (decl &&
|
||||
canHaveTypeParameters(decl) &&
|
||||
decl.typeParameters &&
|
||||
ignoredTypeNames.includes(symbol.name)) {
|
||||
return Usefulness.Always;
|
||||
}
|
||||
if ((0, util_1.matchesTypeOrBaseType)(services, type => ignoredTypeNames.includes((0, util_1.getTypeName)(checker, type)), type)) {
|
||||
return Usefulness.Always;
|
||||
}
|
||||
if (type.isIntersection()) {
|
||||
return collectIntersectionTypeCertainty(type, t => collectToStringCertainty(t, visited));
|
||||
}
|
||||
if (type.isUnion()) {
|
||||
return collectUnionTypeCertainty(type, t => collectToStringCertainty(t, visited));
|
||||
}
|
||||
if (checker.isTupleType(type)) {
|
||||
return collectTupleCertainty(type, new Set([...visited, type]));
|
||||
}
|
||||
if (checker.isArrayType(type)) {
|
||||
return collectArrayCertainty(type, new Set([...visited, type]));
|
||||
}
|
||||
switch (isToStringLikeFromObject(type)) {
|
||||
case undefined:
|
||||
// unknown
|
||||
if (option.checkUnknown && type.flags === ts.TypeFlags.Unknown) {
|
||||
return Usefulness.Sometimes;
|
||||
}
|
||||
// e.g. any
|
||||
return Usefulness.Always;
|
||||
case true:
|
||||
return Usefulness.Never;
|
||||
case false:
|
||||
return Usefulness.Always;
|
||||
}
|
||||
}
|
||||
function isBuiltInStringCall(node) {
|
||||
if (node.callee.type === utils_1.AST_NODE_TYPES.Identifier &&
|
||||
// eslint-disable-next-line @typescript-eslint/internal/prefer-ast-types-enum
|
||||
node.callee.name === 'String' &&
|
||||
node.arguments[0]) {
|
||||
const scope = context.sourceCode.getScope(node);
|
||||
// eslint-disable-next-line @typescript-eslint/internal/prefer-ast-types-enum
|
||||
const variable = utils_1.ASTUtils.findVariable(scope, 'String');
|
||||
return !variable?.defs.length;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function isSymbolToPrimitiveMethod(node) {
|
||||
return (ts.isMethodSignature(node) &&
|
||||
ts.isComputedPropertyName(node.name) &&
|
||||
ts.isPropertyAccessExpression(node.name.expression) &&
|
||||
ts.isIdentifier(node.name.expression.expression) &&
|
||||
node.name.expression.expression.text === 'Symbol' &&
|
||||
ts.isIdentifier(node.name.expression.name) &&
|
||||
node.name.expression.name.text === 'toPrimitive' &&
|
||||
(0, util_1.isSymbolFromDefaultLibrary)(program, checker.getSymbolAtLocation(node.name.expression.expression)));
|
||||
}
|
||||
function isToStringLikeFromObject(type) {
|
||||
// An explicit [Symbol.toPrimitive] declaration is always user-defined
|
||||
if (type
|
||||
.getProperties()
|
||||
.some(property => property.valueDeclaration &&
|
||||
isSymbolToPrimitiveMethod(property.valueDeclaration))) {
|
||||
return false;
|
||||
}
|
||||
// Otherwise, we check for known methods used in type coercion.
|
||||
// We'll try to find one that's not declared on Object itself.
|
||||
// Failing that, we'll fall back to one that is.
|
||||
let foundFallbackOnObject = false;
|
||||
for (const propertyName of ['toLocaleString', 'toString', 'valueOf']) {
|
||||
const candidate = checker.getPropertyOfType(type, propertyName);
|
||||
if (!candidate) {
|
||||
continue;
|
||||
}
|
||||
const declarations = candidate.getDeclarations();
|
||||
if (!declarations?.length) {
|
||||
continue;
|
||||
}
|
||||
// If any declaration is not from the Object interface, this is
|
||||
// user-defined (e.g. overloaded toString on a class or module).
|
||||
// see https://github.com/typescript-eslint/typescript-eslint/issues/8585
|
||||
// see https://github.com/typescript-eslint/typescript-eslint/issues/11945
|
||||
if (declarations.some(declaration => !(ts.isInterfaceDeclaration(declaration.parent) &&
|
||||
declaration.parent.name.text === 'Object'))) {
|
||||
return false;
|
||||
}
|
||||
foundFallbackOnObject = true;
|
||||
}
|
||||
return foundFallbackOnObject ? true : undefined;
|
||||
}
|
||||
return {
|
||||
'AssignmentExpression[operator = "+="], BinaryExpression[operator = "+"]'(node) {
|
||||
const leftType = services.getTypeAtLocation(node.left);
|
||||
const rightType = services.getTypeAtLocation(node.right);
|
||||
if ((0, util_1.getTypeName)(checker, leftType) === 'string') {
|
||||
checkExpression(node.right, rightType);
|
||||
}
|
||||
else if (node.left.type !== utils_1.AST_NODE_TYPES.PrivateIdentifier &&
|
||||
(0, util_1.getTypeName)(checker, rightType) === 'string') {
|
||||
checkExpression(node.left, leftType);
|
||||
}
|
||||
},
|
||||
CallExpression(node) {
|
||||
if (isBuiltInStringCall(node) &&
|
||||
node.arguments[0].type !== utils_1.AST_NODE_TYPES.SpreadElement) {
|
||||
checkExpression(node.arguments[0]);
|
||||
}
|
||||
},
|
||||
'CallExpression > MemberExpression.callee > Identifier[name = "join"].property'(node) {
|
||||
const memberExpr = node.parent;
|
||||
const type = (0, util_1.getConstrainedTypeAtLocation)(services, memberExpr.object);
|
||||
checkExpressionForArrayJoin(memberExpr.object, type);
|
||||
},
|
||||
'CallExpression > MemberExpression.callee > Identifier[name = /^(toLocaleString|toString)$/].property'(node) {
|
||||
const memberExpr = node.parent;
|
||||
checkExpression(memberExpr.object);
|
||||
},
|
||||
TemplateLiteral(node) {
|
||||
if (node.parent.type === utils_1.AST_NODE_TYPES.TaggedTemplateExpression) {
|
||||
return;
|
||||
}
|
||||
for (const expression of node.expressions) {
|
||||
checkExpression(expression);
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
range-set ::= range ( logical-or range ) *
|
||||
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
|
||||
range ::= hyphen | simple ( ' ' simple ) * | ''
|
||||
hyphen ::= partial ' - ' partial
|
||||
simple ::= primitive | partial | tilde | caret
|
||||
primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
|
||||
partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
|
||||
xr ::= 'x' | 'X' | '*' | nr
|
||||
nr ::= '0' | [1-9] ( [0-9] ) *
|
||||
tilde ::= '~' partial
|
||||
caret ::= '^' partial
|
||||
qualifier ::= ( '-' pre )? ( '+' build )?
|
||||
pre ::= prepart ( '.' prepart ) *
|
||||
prepart ::= nr | alphanumid
|
||||
build ::= buildid ( '.' buildid ) *
|
||||
alphanumid ::= ( [0-9] ) * [A-Za-z-] [-0-9A-Za-z] *
|
||||
buildid ::= [-0-9A-Za-z]+
|
||||
@@ -0,0 +1,72 @@
|
||||
'use strict';
|
||||
|
||||
const net = require('net');
|
||||
const utils = require('../utils');
|
||||
|
||||
/**
|
||||
* Constructor for a Jayson TCP server
|
||||
* @class ServerTcp
|
||||
* @extends require('net').Server
|
||||
* @param {Server} server Server instance
|
||||
* @param {Object} [options] Options for this instance
|
||||
* @return {ServerTcp}
|
||||
*/
|
||||
const ServerTcp = function(server, options) {
|
||||
if(!(this instanceof ServerTcp)) {
|
||||
return new ServerTcp(server, options);
|
||||
}
|
||||
|
||||
this.options = utils.merge(server.options, options || {});
|
||||
|
||||
net.Server.call(this, getTcpListener(this, server));
|
||||
};
|
||||
require('util').inherits(ServerTcp, net.Server);
|
||||
|
||||
module.exports = ServerTcp;
|
||||
|
||||
/**
|
||||
* Returns a TCP connection listener bound to the server in the argument.
|
||||
* @param {Server} server Instance of JaysonServer
|
||||
* @param {net.Server} self Instance of net.Server
|
||||
* @return {Function}
|
||||
* @private
|
||||
* @ignore
|
||||
*/
|
||||
function getTcpListener(self, server) {
|
||||
return function(conn) {
|
||||
const options = self.options || {};
|
||||
|
||||
utils.parseStream(conn, options, function(err, request) {
|
||||
if(err) {
|
||||
return respondError(err);
|
||||
}
|
||||
|
||||
server.call(request, function(error, success) {
|
||||
const response = error || success;
|
||||
if(response) {
|
||||
utils.JSON.stringify(response, options, function(err, body) {
|
||||
if(err) {
|
||||
return respondError(err);
|
||||
}
|
||||
conn.write(body);
|
||||
});
|
||||
} else {
|
||||
// no response received at all, must be a notification
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ends the request with an error code
|
||||
function respondError(err) {
|
||||
const error = server.error(-32700, null, String(err));
|
||||
const response = utils.response(error, undefined, undefined, self.options.version);
|
||||
utils.JSON.stringify(response, options, function(err, body) {
|
||||
if(err) {
|
||||
body = ''; // we tried our best.
|
||||
}
|
||||
conn.end(body);
|
||||
});
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,204 @@
|
||||
/**
|
||||
* @fileoverview Rule to warn when a function expression does not have a name.
|
||||
* @author Kyle T. Nunery
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Types
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @typedef {import("eslint-scope").Variable} Variable */
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Checks whether or not a given variable is a function name.
|
||||
* @param {Variable} variable A variable to check.
|
||||
* @returns {boolean} `true` if the variable is a function name.
|
||||
*/
|
||||
function isFunctionName(variable) {
|
||||
return variable && variable.defs[0].type === "FunctionName";
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "suggestion",
|
||||
|
||||
defaultOptions: ["always", {}],
|
||||
|
||||
docs: {
|
||||
description: "Require or disallow named `function` expressions",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/latest/rules/func-names",
|
||||
},
|
||||
|
||||
schema: {
|
||||
definitions: {
|
||||
value: {
|
||||
enum: ["always", "as-needed", "never"],
|
||||
},
|
||||
},
|
||||
type: "array",
|
||||
items: [
|
||||
{
|
||||
$ref: "#/definitions/value",
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
generators: {
|
||||
$ref: "#/definitions/value",
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
additionalItems: false,
|
||||
},
|
||||
|
||||
messages: {
|
||||
unnamed: "Unexpected unnamed {{name}}.",
|
||||
named: "Unexpected named {{name}}.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const sourceCode = context.sourceCode;
|
||||
|
||||
/**
|
||||
* Returns the config option for the given node.
|
||||
* @param {ASTNode} node A node to get the config for.
|
||||
* @returns {string} The config option.
|
||||
*/
|
||||
function getConfigForNode(node) {
|
||||
if (node.generator && context.options[1].generators) {
|
||||
return context.options[1].generators;
|
||||
}
|
||||
|
||||
return context.options[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the current FunctionExpression node is a get, set, or
|
||||
* shorthand method in an object literal or a class.
|
||||
* @param {ASTNode} node A node to check.
|
||||
* @returns {boolean} True if the node is a get, set, or shorthand method.
|
||||
*/
|
||||
function isObjectOrClassMethod(node) {
|
||||
const parent = node.parent;
|
||||
|
||||
return (
|
||||
parent.type === "MethodDefinition" ||
|
||||
(parent.type === "Property" &&
|
||||
(parent.method ||
|
||||
parent.kind === "get" ||
|
||||
parent.kind === "set"))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the current FunctionExpression node has a name that would be
|
||||
* inferred from context in a conforming ES6 environment.
|
||||
* @param {ASTNode} node A node to check.
|
||||
* @returns {boolean} True if the node would have a name assigned automatically.
|
||||
*/
|
||||
function hasInferredName(node) {
|
||||
const parent = node.parent;
|
||||
|
||||
return (
|
||||
isObjectOrClassMethod(node) ||
|
||||
(parent.type === "VariableDeclarator" &&
|
||||
parent.id.type === "Identifier" &&
|
||||
parent.init === node) ||
|
||||
(parent.type === "Property" && parent.value === node) ||
|
||||
(parent.type === "PropertyDefinition" &&
|
||||
parent.value === node) ||
|
||||
(parent.type === "AssignmentExpression" &&
|
||||
parent.left.type === "Identifier" &&
|
||||
parent.right === node) ||
|
||||
(parent.type === "AssignmentPattern" &&
|
||||
parent.left.type === "Identifier" &&
|
||||
parent.right === node)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports that an unnamed function should be named
|
||||
* @param {ASTNode} node The node to report in the event of an error.
|
||||
* @returns {void}
|
||||
*/
|
||||
function reportUnexpectedUnnamedFunction(node) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "unnamed",
|
||||
loc: astUtils.getFunctionHeadLoc(node, sourceCode),
|
||||
data: { name: astUtils.getFunctionNameWithKind(node) },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports that a named function should be unnamed
|
||||
* @param {ASTNode} node The node to report in the event of an error.
|
||||
* @returns {void}
|
||||
*/
|
||||
function reportUnexpectedNamedFunction(node) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "named",
|
||||
loc: astUtils.getFunctionHeadLoc(node, sourceCode),
|
||||
data: { name: astUtils.getFunctionNameWithKind(node) },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The listener for function nodes.
|
||||
* @param {ASTNode} node function node
|
||||
* @returns {void}
|
||||
*/
|
||||
function handleFunction(node) {
|
||||
// Skip recursive functions.
|
||||
const nameVar = sourceCode.getDeclaredVariables(node)[0];
|
||||
|
||||
if (isFunctionName(nameVar) && nameVar.references.length > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const hasName = Boolean(node.id && node.id.name);
|
||||
const config = getConfigForNode(node);
|
||||
|
||||
if (config === "never") {
|
||||
if (hasName && node.type !== "FunctionDeclaration") {
|
||||
reportUnexpectedNamedFunction(node);
|
||||
}
|
||||
} else if (config === "as-needed") {
|
||||
if (!hasName && !hasInferredName(node)) {
|
||||
reportUnexpectedUnnamedFunction(node);
|
||||
}
|
||||
} else {
|
||||
if (!hasName && !isObjectOrClassMethod(node)) {
|
||||
reportUnexpectedUnnamedFunction(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
"FunctionExpression:exit": handleFunction,
|
||||
"ExportDefaultDeclaration > FunctionDeclaration": handleFunction,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import * as core from "../core/index.js";
|
||||
import * as schemas from "./schemas.js";
|
||||
|
||||
export interface ZodCoercedString<T = unknown> extends schemas._ZodString<core.$ZodStringInternals<T>> {}
|
||||
export function string<T = unknown>(params?: string | core.$ZodStringParams): ZodCoercedString<T> {
|
||||
return core._coercedString(schemas.ZodString, params) as any;
|
||||
}
|
||||
|
||||
export interface ZodCoercedNumber<T = unknown> extends schemas._ZodNumber<core.$ZodNumberInternals<T>> {}
|
||||
export function number<T = unknown>(params?: string | core.$ZodNumberParams): ZodCoercedNumber<T> {
|
||||
return core._coercedNumber(schemas.ZodNumber, params) as ZodCoercedNumber<T>;
|
||||
}
|
||||
|
||||
export interface ZodCoercedBoolean<T = unknown> extends schemas._ZodBoolean<core.$ZodBooleanInternals<T>> {}
|
||||
export function boolean<T = unknown>(params?: string | core.$ZodBooleanParams): ZodCoercedBoolean<T> {
|
||||
return core._coercedBoolean(schemas.ZodBoolean, params) as ZodCoercedBoolean<T>;
|
||||
}
|
||||
|
||||
export interface ZodCoercedBigInt<T = unknown> extends schemas._ZodBigInt<core.$ZodBigIntInternals<T>> {}
|
||||
export function bigint<T = unknown>(params?: string | core.$ZodBigIntParams): ZodCoercedBigInt<T> {
|
||||
return core._coercedBigint(schemas.ZodBigInt, params) as ZodCoercedBigInt<T>;
|
||||
}
|
||||
|
||||
export interface ZodCoercedDate<T = unknown> extends schemas._ZodDate<core.$ZodDateInternals<T>> {}
|
||||
export function date<T = unknown>(params?: string | core.$ZodDateParams): ZodCoercedDate<T> {
|
||||
return core._coercedDate(schemas.ZodDate, params) as ZodCoercedDate<T>;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"main": "../../cjs/_class_check_private_static_field_descriptor.cjs",
|
||||
"module": "../../esm/_class_check_private_static_field_descriptor.js"
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
global.process = { __proto__: process, pid: 123456 }
|
||||
Date.now = function () { return 1459875739796 }
|
||||
require('node:os').hostname = function () { return 'abcdefghijklmnopqr' }
|
||||
const pino = require(require.resolve('./../../'))
|
||||
const dest = pino.destination({ dest: 1, minLength: 4096, sync: false })
|
||||
const logger = pino({}, dest)
|
||||
logger.info('hello')
|
||||
logger.info('world')
|
||||
dest.flushSync()
|
||||
process.exit(0)
|
||||
@@ -0,0 +1,249 @@
|
||||
/**
|
||||
* @fileoverview Require spaces around infix operators
|
||||
* @author Michael Ficarra
|
||||
* @deprecated in ESLint v8.53.0
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
const { isEqToken } = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
deprecated: {
|
||||
message: "Formatting rules are being moved out of ESLint core.",
|
||||
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
|
||||
deprecatedSince: "8.53.0",
|
||||
availableUntil: "11.0.0",
|
||||
replacedBy: [
|
||||
{
|
||||
message:
|
||||
"ESLint Stylistic now maintains deprecated stylistic core rules.",
|
||||
url: "https://eslint.style/guide/migration",
|
||||
plugin: {
|
||||
name: "@stylistic/eslint-plugin",
|
||||
url: "https://eslint.style",
|
||||
},
|
||||
rule: {
|
||||
name: "space-infix-ops",
|
||||
url: "https://eslint.style/rules/space-infix-ops",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
type: "layout",
|
||||
|
||||
docs: {
|
||||
description: "Require spacing around infix operators",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/latest/rules/space-infix-ops",
|
||||
},
|
||||
|
||||
fixable: "whitespace",
|
||||
|
||||
schema: [
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
int32Hint: {
|
||||
type: "boolean",
|
||||
default: false,
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
|
||||
messages: {
|
||||
missingSpace: "Operator '{{operator}}' must be spaced.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const int32Hint = context.options[0]
|
||||
? context.options[0].int32Hint === true
|
||||
: false;
|
||||
const sourceCode = context.sourceCode;
|
||||
|
||||
/**
|
||||
* Returns the first token which violates the rule
|
||||
* @param {ASTNode} left The left node of the main node
|
||||
* @param {ASTNode} right The right node of the main node
|
||||
* @param {string} op The operator of the main node
|
||||
* @returns {Object} The violator token or null
|
||||
* @private
|
||||
*/
|
||||
function getFirstNonSpacedToken(left, right, op) {
|
||||
const operator = sourceCode.getFirstTokenBetween(
|
||||
left,
|
||||
right,
|
||||
token => token.value === op,
|
||||
);
|
||||
const prev = sourceCode.getTokenBefore(operator);
|
||||
const next = sourceCode.getTokenAfter(operator);
|
||||
|
||||
if (
|
||||
!sourceCode.isSpaceBetween(prev, operator) ||
|
||||
!sourceCode.isSpaceBetween(operator, next)
|
||||
) {
|
||||
return operator;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports an AST node as a rule violation
|
||||
* @param {ASTNode} mainNode The node to report
|
||||
* @param {Object} culpritToken The token which has a problem
|
||||
* @returns {void}
|
||||
* @private
|
||||
*/
|
||||
function report(mainNode, culpritToken) {
|
||||
context.report({
|
||||
node: mainNode,
|
||||
loc: culpritToken.loc,
|
||||
messageId: "missingSpace",
|
||||
data: {
|
||||
operator: culpritToken.value,
|
||||
},
|
||||
fix(fixer) {
|
||||
const previousToken =
|
||||
sourceCode.getTokenBefore(culpritToken);
|
||||
const afterToken = sourceCode.getTokenAfter(culpritToken);
|
||||
let fixString = "";
|
||||
|
||||
if (culpritToken.range[0] - previousToken.range[1] === 0) {
|
||||
fixString = " ";
|
||||
}
|
||||
|
||||
fixString += culpritToken.value;
|
||||
|
||||
if (afterToken.range[0] - culpritToken.range[1] === 0) {
|
||||
fixString += " ";
|
||||
}
|
||||
|
||||
return fixer.replaceText(culpritToken, fixString);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the node is binary then report
|
||||
* @param {ASTNode} node node to evaluate
|
||||
* @returns {void}
|
||||
* @private
|
||||
*/
|
||||
function checkBinary(node) {
|
||||
const leftNode = node.left.typeAnnotation
|
||||
? node.left.typeAnnotation
|
||||
: node.left;
|
||||
const rightNode = node.right;
|
||||
|
||||
// search for = in AssignmentPattern nodes
|
||||
const operator = node.operator || "=";
|
||||
|
||||
const nonSpacedNode = getFirstNonSpacedToken(
|
||||
leftNode,
|
||||
rightNode,
|
||||
operator,
|
||||
);
|
||||
|
||||
if (nonSpacedNode) {
|
||||
if (!(int32Hint && sourceCode.getText(node).endsWith("|0"))) {
|
||||
report(node, nonSpacedNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the node is conditional
|
||||
* @param {ASTNode} node node to evaluate
|
||||
* @returns {void}
|
||||
* @private
|
||||
*/
|
||||
function checkConditional(node) {
|
||||
const nonSpacedConsequentNode = getFirstNonSpacedToken(
|
||||
node.test,
|
||||
node.consequent,
|
||||
"?",
|
||||
);
|
||||
const nonSpacedAlternateNode = getFirstNonSpacedToken(
|
||||
node.consequent,
|
||||
node.alternate,
|
||||
":",
|
||||
);
|
||||
|
||||
if (nonSpacedConsequentNode) {
|
||||
report(node, nonSpacedConsequentNode);
|
||||
}
|
||||
|
||||
if (nonSpacedAlternateNode) {
|
||||
report(node, nonSpacedAlternateNode);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the node is a variable
|
||||
* @param {ASTNode} node node to evaluate
|
||||
* @returns {void}
|
||||
* @private
|
||||
*/
|
||||
function checkVar(node) {
|
||||
const leftNode = node.id.typeAnnotation
|
||||
? node.id.typeAnnotation
|
||||
: node.id;
|
||||
const rightNode = node.init;
|
||||
|
||||
if (rightNode) {
|
||||
const nonSpacedNode = getFirstNonSpacedToken(
|
||||
leftNode,
|
||||
rightNode,
|
||||
"=",
|
||||
);
|
||||
|
||||
if (nonSpacedNode) {
|
||||
report(node, nonSpacedNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
AssignmentExpression: checkBinary,
|
||||
AssignmentPattern: checkBinary,
|
||||
BinaryExpression: checkBinary,
|
||||
LogicalExpression: checkBinary,
|
||||
ConditionalExpression: checkConditional,
|
||||
VariableDeclarator: checkVar,
|
||||
|
||||
PropertyDefinition(node) {
|
||||
if (!node.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
* Because of computed properties and type annotations, some
|
||||
* tokens may exist between `node.key` and `=`.
|
||||
* Therefore, find the `=` from the right.
|
||||
*/
|
||||
const operatorToken = sourceCode.getTokenBefore(
|
||||
node.value,
|
||||
isEqToken,
|
||||
);
|
||||
const leftToken = sourceCode.getTokenBefore(operatorToken);
|
||||
const rightToken = sourceCode.getTokenAfter(operatorToken);
|
||||
|
||||
if (
|
||||
!sourceCode.isSpaceBetween(leftToken, operatorToken) ||
|
||||
!sourceCode.isSpaceBetween(operatorToken, rightToken)
|
||||
) {
|
||||
report(node, operatorToken);
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
import index from './index.js';
|
||||
|
||||
const { transform, transformStyleAttribute, bundle, bundleAsync, browserslistToTargets, composeVisitors, Features } = index;
|
||||
export { transform, transformStyleAttribute, bundle, bundleAsync, browserslistToTargets, composeVisitors, Features };
|
||||
@@ -0,0 +1,50 @@
|
||||
|
||||
# TypeScript
|
||||
|
||||
[](https://github.com/microsoft/TypeScript/actions?query=workflow%3ACI)
|
||||
[](https://www.npmjs.com/package/typescript)
|
||||
[](https://www.npmjs.com/package/typescript)
|
||||
[](https://securityscorecards.dev/viewer/?uri=github.com/microsoft/TypeScript)
|
||||
|
||||
|
||||
[TypeScript](https://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](https://www.typescriptlang.org/play/), and stay up to date via [our blog](https://blogs.msdn.microsoft.com/typescript) and [Twitter account](https://twitter.com/typescript).
|
||||
|
||||
Find others who are using TypeScript at [our community page](https://www.typescriptlang.org/community/).
|
||||
|
||||
## Installing
|
||||
|
||||
For the latest stable version:
|
||||
|
||||
```bash
|
||||
npm install -D typescript
|
||||
```
|
||||
|
||||
For our nightly builds:
|
||||
|
||||
```bash
|
||||
npm install -D typescript@next
|
||||
```
|
||||
|
||||
## Contribute
|
||||
|
||||
There are many ways to [contribute](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md) to TypeScript.
|
||||
* [Submit bugs](https://github.com/microsoft/TypeScript/issues) and help us verify fixes as they are checked in.
|
||||
* Review the [source code changes](https://github.com/microsoft/TypeScript/pulls).
|
||||
* Engage with other TypeScript users and developers on [StackOverflow](https://stackoverflow.com/questions/tagged/typescript).
|
||||
* Help each other in the [TypeScript Community Discord](https://discord.gg/typescript).
|
||||
* Join the [#typescript](https://twitter.com/search?q=%23TypeScript) discussion on Twitter.
|
||||
* [Contribute bug fixes](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md).
|
||||
|
||||
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see
|
||||
the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com)
|
||||
with any additional questions or comments.
|
||||
|
||||
## Documentation
|
||||
|
||||
* [TypeScript in 5 minutes](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html)
|
||||
* [Programming handbook](https://www.typescriptlang.org/docs/handbook/intro.html)
|
||||
* [Homepage](https://www.typescriptlang.org/)
|
||||
|
||||
## Roadmap
|
||||
|
||||
For details on our planned features and future direction, please refer to our [roadmap](https://github.com/microsoft/TypeScript/wiki/Roadmap).
|
||||
@@ -0,0 +1,519 @@
|
||||
/**
|
||||
* Experimental implementation of NTT / FFT (Fast Fourier Transform) over finite fields.
|
||||
* API may change at any time. The code has not been audited. Feature requests are welcome.
|
||||
* @module
|
||||
*/
|
||||
import type { IField } from './modular.ts';
|
||||
|
||||
export interface MutableArrayLike<T> {
|
||||
[index: number]: T;
|
||||
length: number;
|
||||
slice(start?: number, end?: number): this;
|
||||
[Symbol.iterator](): Iterator<T>;
|
||||
}
|
||||
|
||||
function checkU32(n: number) {
|
||||
// 0xff_ff_ff_ff
|
||||
if (!Number.isSafeInteger(n) || n < 0 || n > 0xffffffff)
|
||||
throw new Error('wrong u32 integer:' + n);
|
||||
return n;
|
||||
}
|
||||
|
||||
/** Checks if integer is in form of `1 << X` */
|
||||
export function isPowerOfTwo(x: number): boolean {
|
||||
checkU32(x);
|
||||
return (x & (x - 1)) === 0 && x !== 0;
|
||||
}
|
||||
|
||||
export function nextPowerOfTwo(n: number): number {
|
||||
checkU32(n);
|
||||
if (n <= 1) return 1;
|
||||
return (1 << (log2(n - 1) + 1)) >>> 0;
|
||||
}
|
||||
|
||||
export function reverseBits(n: number, bits: number): number {
|
||||
checkU32(n);
|
||||
let reversed = 0;
|
||||
for (let i = 0; i < bits; i++, n >>>= 1) reversed = (reversed << 1) | (n & 1);
|
||||
return reversed;
|
||||
}
|
||||
|
||||
/** Similar to `bitLen(x)-1` but much faster for small integers, like indices */
|
||||
export function log2(n: number): number {
|
||||
checkU32(n);
|
||||
return 31 - Math.clz32(n);
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves lowest bit to highest position, which at first step splits
|
||||
* array on even and odd indices, then it applied again to each part,
|
||||
* which is core of fft
|
||||
*/
|
||||
export function bitReversalInplace<T extends MutableArrayLike<any>>(values: T): T {
|
||||
const n = values.length;
|
||||
if (n < 2 || !isPowerOfTwo(n))
|
||||
throw new Error('n must be a power of 2 and greater than 1. Got ' + n);
|
||||
const bits = log2(n);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const j = reverseBits(i, bits);
|
||||
if (i < j) {
|
||||
const tmp = values[i];
|
||||
values[i] = values[j];
|
||||
values[j] = tmp;
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
export function bitReversalPermutation<T>(values: T[]): T[] {
|
||||
return bitReversalInplace(values.slice()) as T[];
|
||||
}
|
||||
|
||||
const _1n = /** @__PURE__ */ BigInt(1);
|
||||
function findGenerator(field: IField<bigint>) {
|
||||
let G = BigInt(2);
|
||||
for (; field.eql(field.pow(G, field.ORDER >> _1n), field.ONE); G++);
|
||||
return G;
|
||||
}
|
||||
|
||||
export type RootsOfUnity = {
|
||||
roots: (bits: number) => bigint[];
|
||||
brp(bits: number): bigint[];
|
||||
inverse(bits: number): bigint[];
|
||||
omega: (bits: number) => bigint;
|
||||
clear: () => void;
|
||||
};
|
||||
/** We limit roots up to 2**31, which is a lot: 2-billion polynomimal should be rare. */
|
||||
export function rootsOfUnity(field: IField<bigint>, generator?: bigint): RootsOfUnity {
|
||||
// Factor field.ORDER-1 as oddFactor * 2^powerOfTwo
|
||||
let oddFactor = field.ORDER - _1n;
|
||||
let powerOfTwo = 0;
|
||||
for (; (oddFactor & _1n) !== _1n; powerOfTwo++, oddFactor >>= _1n);
|
||||
|
||||
// Find non quadratic residue
|
||||
let G = generator !== undefined ? BigInt(generator) : findGenerator(field);
|
||||
// Powers of generator
|
||||
const omegas: bigint[] = new Array(powerOfTwo + 1);
|
||||
omegas[powerOfTwo] = field.pow(G, oddFactor);
|
||||
for (let i = powerOfTwo; i > 0; i--) omegas[i - 1] = field.sqr(omegas[i]);
|
||||
// Compute all roots of unity for powers up to maxPower
|
||||
const rootsCache: bigint[][] = [];
|
||||
const checkBits = (bits: number) => {
|
||||
checkU32(bits);
|
||||
if (bits > 31 || bits > powerOfTwo)
|
||||
throw new Error('rootsOfUnity: wrong bits ' + bits + ' powerOfTwo=' + powerOfTwo);
|
||||
return bits;
|
||||
};
|
||||
const precomputeRoots = (maxPower: number) => {
|
||||
checkBits(maxPower);
|
||||
for (let power = maxPower; power >= 0; power--) {
|
||||
if (rootsCache[power]) continue; // Skip if we've already computed roots for this power
|
||||
const rootsAtPower: bigint[] = [];
|
||||
for (let j = 0, cur = field.ONE; j < 2 ** power; j++, cur = field.mul(cur, omegas[power]))
|
||||
rootsAtPower.push(cur);
|
||||
rootsCache[power] = rootsAtPower;
|
||||
}
|
||||
return rootsCache[maxPower];
|
||||
};
|
||||
const brpCache = new Map<number, bigint[]>();
|
||||
const inverseCache = new Map<number, bigint[]>();
|
||||
|
||||
// NOTE: we use bits instead of power, because power = 2**bits,
|
||||
// but power is not neccesary isPowerOfTwo(power)!
|
||||
return {
|
||||
roots: (bits: number): bigint[] => {
|
||||
const b = checkBits(bits);
|
||||
return precomputeRoots(b);
|
||||
},
|
||||
brp(bits: number): bigint[] {
|
||||
const b = checkBits(bits);
|
||||
if (brpCache.has(b)) return brpCache.get(b)!;
|
||||
else {
|
||||
const res = bitReversalPermutation(this.roots(b));
|
||||
brpCache.set(b, res);
|
||||
return res;
|
||||
}
|
||||
},
|
||||
inverse(bits: number): bigint[] {
|
||||
const b = checkBits(bits);
|
||||
if (inverseCache.has(b)) return inverseCache.get(b)!;
|
||||
else {
|
||||
const res = field.invertBatch(this.roots(b));
|
||||
inverseCache.set(b, res);
|
||||
return res;
|
||||
}
|
||||
},
|
||||
omega: (bits: number): bigint => omegas[checkBits(bits)],
|
||||
clear: (): void => {
|
||||
rootsCache.splice(0, rootsCache.length);
|
||||
brpCache.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type Polynomial<T> = MutableArrayLike<T>;
|
||||
|
||||
/**
|
||||
* Maps great to Field<bigint>, but not to Group (EC points):
|
||||
* - inv from scalar field
|
||||
* - we need multiplyUnsafe here, instead of multiply for speed
|
||||
* - multiplyUnsafe is safe in the context: we do mul(rootsOfUnity), which are public and sparse
|
||||
*/
|
||||
export type FFTOpts<T, R> = {
|
||||
add: (a: T, b: T) => T;
|
||||
sub: (a: T, b: T) => T;
|
||||
mul: (a: T, scalar: R) => T;
|
||||
inv: (a: R) => R;
|
||||
};
|
||||
|
||||
export type FFTCoreOpts<R> = {
|
||||
N: number;
|
||||
roots: Polynomial<R>;
|
||||
dit: boolean;
|
||||
invertButterflies?: boolean;
|
||||
skipStages?: number;
|
||||
brp?: boolean;
|
||||
};
|
||||
|
||||
export type FFTCoreLoop<T> = <P extends Polynomial<T>>(values: P) => P;
|
||||
|
||||
/**
|
||||
* Constructs different flavors of FFT. radix2 implementation of low level mutating API. Flavors:
|
||||
*
|
||||
* - DIT (Decimation-in-Time): Bottom-Up (leaves -> root), Cool-Turkey
|
||||
* - DIF (Decimation-in-Frequency): Top-Down (root -> leaves), Gentleman–Sande
|
||||
*
|
||||
* DIT takes brp input, returns natural output.
|
||||
* DIF takes natural input, returns brp output.
|
||||
*
|
||||
* The output is actually identical. Time / frequence distinction is not meaningful
|
||||
* for Polynomial multiplication in fields.
|
||||
* Which means if protocol supports/needs brp output/inputs, then we can skip this step.
|
||||
*
|
||||
* Cyclic NTT: Rq = Zq[x]/(x^n-1). butterfly_DIT+loop_DIT OR butterfly_DIF+loop_DIT, roots are omega
|
||||
* Negacyclic NTT: Rq = Zq[x]/(x^n+1). butterfly_DIT+loop_DIF, at least for mlkem / mldsa
|
||||
*/
|
||||
export const FFTCore = <T, R>(F: FFTOpts<T, R>, coreOpts: FFTCoreOpts<R>): FFTCoreLoop<T> => {
|
||||
const { N, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;
|
||||
const bits = log2(N);
|
||||
if (!isPowerOfTwo(N)) throw new Error('FFT: Polynomial size should be power of two');
|
||||
const isDit = dit !== invertButterflies;
|
||||
isDit;
|
||||
return <P extends Polynomial<T>>(values: P): P => {
|
||||
if (values.length !== N) throw new Error('FFT: wrong Polynomial length');
|
||||
if (dit && brp) bitReversalInplace(values);
|
||||
for (let i = 0, g = 1; i < bits - skipStages; i++) {
|
||||
// For each stage s (sub-FFT length m = 2^s)
|
||||
const s = dit ? i + 1 + skipStages : bits - i;
|
||||
const m = 1 << s;
|
||||
const m2 = m >> 1;
|
||||
const stride = N >> s;
|
||||
// Loop over each subarray of length m
|
||||
for (let k = 0; k < N; k += m) {
|
||||
// Loop over each butterfly within the subarray
|
||||
for (let j = 0, grp = g++; j < m2; j++) {
|
||||
const rootPos = invertButterflies ? (dit ? N - grp : grp) : j * stride;
|
||||
const i0 = k + j;
|
||||
const i1 = k + j + m2;
|
||||
const omega = roots[rootPos];
|
||||
const b = values[i1];
|
||||
const a = values[i0];
|
||||
// Inlining gives us 10% perf in kyber vs functions
|
||||
if (isDit) {
|
||||
const t = F.mul(b, omega); // Standard DIT butterfly
|
||||
values[i0] = F.add(a, t);
|
||||
values[i1] = F.sub(a, t);
|
||||
} else if (invertButterflies) {
|
||||
values[i0] = F.add(b, a); // DIT loop + inverted butterflies (Kyber decode)
|
||||
values[i1] = F.mul(F.sub(b, a), omega);
|
||||
} else {
|
||||
values[i0] = F.add(a, b); // Standard DIF butterfly
|
||||
values[i1] = F.mul(F.sub(a, b), omega);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!dit && brp) bitReversalInplace(values);
|
||||
return values;
|
||||
};
|
||||
};
|
||||
|
||||
export type FFTMethods<T> = {
|
||||
direct<P extends Polynomial<T>>(values: P, brpInput?: boolean, brpOutput?: boolean): P;
|
||||
inverse<P extends Polynomial<T>>(values: P, brpInput?: boolean, brpOutput?: boolean): P;
|
||||
};
|
||||
|
||||
/**
|
||||
* NTT aka FFT over finite field (NOT over complex numbers).
|
||||
* Naming mirrors other libraries.
|
||||
*/
|
||||
export function FFT<T>(roots: RootsOfUnity, opts: FFTOpts<T, bigint>): FFTMethods<T> {
|
||||
const getLoop = (
|
||||
N: number,
|
||||
roots: Polynomial<bigint>,
|
||||
brpInput = false,
|
||||
brpOutput = false
|
||||
): (<P extends Polynomial<T>>(values: P) => P) => {
|
||||
if (brpInput && brpOutput) {
|
||||
// we cannot optimize this case, but lets support it anyway
|
||||
return (values) =>
|
||||
FFTCore(opts, { N, roots, dit: false, brp: false })(bitReversalInplace(values));
|
||||
}
|
||||
if (brpInput) return FFTCore(opts, { N, roots, dit: true, brp: false });
|
||||
if (brpOutput) return FFTCore(opts, { N, roots, dit: false, brp: false });
|
||||
return FFTCore(opts, { N, roots, dit: true, brp: true }); // all natural
|
||||
};
|
||||
return {
|
||||
direct<P extends Polynomial<T>>(values: P, brpInput = false, brpOutput = false): P {
|
||||
const N = values.length;
|
||||
if (!isPowerOfTwo(N)) throw new Error('FFT: Polynomial size should be power of two');
|
||||
const bits = log2(N);
|
||||
return getLoop(N, roots.roots(bits), brpInput, brpOutput)<P>(values.slice());
|
||||
},
|
||||
inverse<P extends Polynomial<T>>(values: P, brpInput = false, brpOutput = false): P {
|
||||
const N = values.length;
|
||||
const bits = log2(N);
|
||||
const res = getLoop(N, roots.inverse(bits), brpInput, brpOutput)(values.slice());
|
||||
const ivm = opts.inv(BigInt(values.length)); // scale
|
||||
// we can get brp output if we use dif instead of dit!
|
||||
for (let i = 0; i < res.length; i++) res[i] = opts.mul(res[i], ivm);
|
||||
// Allows to re-use non-inverted roots, but is VERY fragile
|
||||
// return [res[0]].concat(res.slice(1).reverse());
|
||||
// inverse calculated as pow(-1), which transforms into ω^{-kn} (-> reverses indices)
|
||||
return res;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type CreatePolyFn<P extends Polynomial<T>, T> = (len: number, elm?: T) => P;
|
||||
|
||||
export type PolyFn<P extends Polynomial<T>, T> = {
|
||||
roots: RootsOfUnity;
|
||||
create: CreatePolyFn<P, T>;
|
||||
length?: number; // optional enforced size
|
||||
|
||||
degree: (a: P) => number;
|
||||
extend: (a: P, len: number) => P;
|
||||
add: (a: P, b: P) => P; // fc(x) = fa(x) + fb(x)
|
||||
sub: (a: P, b: P) => P; // fc(x) = fa(x) - fb(x)
|
||||
mul: (a: P, b: P | T) => P; // fc(x) = fa(x) * fb(x) OR fc(x) = fa(x) * scalar (same as field)
|
||||
dot: (a: P, b: P) => P; // point-wise coeff multiplication
|
||||
convolve: (a: P, b: P) => P;
|
||||
shift: (p: P, factor: bigint) => P; // point-wise coeffcient shift
|
||||
clone: (a: P) => P;
|
||||
// Eval
|
||||
eval: (a: P, basis: P) => T; // y = fc(x)
|
||||
monomial: {
|
||||
basis: (x: T, n: number) => P;
|
||||
eval: (a: P, x: T) => T;
|
||||
};
|
||||
lagrange: {
|
||||
basis: (x: T, n: number, brp?: boolean) => P;
|
||||
eval: (a: P, x: T, brp?: boolean) => T;
|
||||
};
|
||||
// Complex
|
||||
vanishing: (roots: P) => P; // f(x) = 0 for every x in roots
|
||||
};
|
||||
|
||||
/**
|
||||
* Poly wants a cracker.
|
||||
*
|
||||
* Polynomials are functions like `y=f(x)`, which means when we multiply two polynomials, result is
|
||||
* function `f3(x) = f1(x) * f2(x)`, we don't multiply values. Key takeaways:
|
||||
*
|
||||
* - **Polynomial** is an array of coefficients: `f(x) = sum(coeff[i] * basis[i](x))`
|
||||
* - **Basis** is array of functions
|
||||
* - **Monominal** is Polynomial where `basis[i](x) == x**i` (powers)
|
||||
* - **Array size** is domain size
|
||||
* - **Lattice** is matrix (Polynomial of Polynomials)
|
||||
*/
|
||||
export function poly<T>(
|
||||
field: IField<T>,
|
||||
roots: RootsOfUnity,
|
||||
create?: undefined,
|
||||
fft?: FFTMethods<T>,
|
||||
length?: number
|
||||
): PolyFn<T[], T>;
|
||||
export function poly<T, P extends Polynomial<T>>(
|
||||
field: IField<T>,
|
||||
roots: RootsOfUnity,
|
||||
create: CreatePolyFn<P, T>,
|
||||
fft?: FFTMethods<T>,
|
||||
length?: number
|
||||
): PolyFn<P, T>;
|
||||
export function poly<T, P extends Polynomial<T>>(
|
||||
field: IField<T>,
|
||||
roots: RootsOfUnity,
|
||||
create?: CreatePolyFn<P, T>,
|
||||
fft?: FFTMethods<T>,
|
||||
length?: number
|
||||
): PolyFn<any, T> {
|
||||
const F = field;
|
||||
const _create =
|
||||
create ||
|
||||
(((len: number, elm?: T): Polynomial<T> => new Array(len).fill(elm ?? F.ZERO)) as CreatePolyFn<
|
||||
P,
|
||||
T
|
||||
>);
|
||||
|
||||
const isPoly = (x: any): x is P => Array.isArray(x) || ArrayBuffer.isView(x);
|
||||
const checkLength = (...lst: P[]): number => {
|
||||
if (!lst.length) return 0;
|
||||
for (const i of lst) if (!isPoly(i)) throw new Error('poly: not polynomial: ' + i);
|
||||
const L = lst[0].length;
|
||||
for (let i = 1; i < lst.length; i++)
|
||||
if (lst[i].length !== L) throw new Error(`poly: mismatched lengths ${L} vs ${lst[i].length}`);
|
||||
if (length !== undefined && L !== length)
|
||||
throw new Error(`poly: expected fixed length ${length}, got ${L}`);
|
||||
return L;
|
||||
};
|
||||
function findOmegaIndex(x: T, n: number, brp = false): number {
|
||||
const bits = log2(n);
|
||||
const omega = brp ? roots.brp(bits) : roots.roots(bits);
|
||||
for (let i = 0; i < n; i++) if (F.eql(x, omega[i] as T)) return i;
|
||||
return -1;
|
||||
}
|
||||
// TODO: mutating versions for mlkem/mldsa
|
||||
return {
|
||||
roots,
|
||||
create: _create,
|
||||
length,
|
||||
extend: (a: P, len: number): P => {
|
||||
checkLength(a);
|
||||
const out = _create(len, F.ZERO);
|
||||
for (let i = 0; i < a.length; i++) out[i] = a[i];
|
||||
return out;
|
||||
},
|
||||
degree: (a: P): number => {
|
||||
checkLength(a);
|
||||
for (let i = a.length - 1; i >= 0; i--) if (!F.is0(a[i])) return i;
|
||||
return -1;
|
||||
},
|
||||
add: (a: P, b: P): P => {
|
||||
const len = checkLength(a, b);
|
||||
const out = _create(len);
|
||||
for (let i = 0; i < len; i++) out[i] = F.add(a[i], b[i]);
|
||||
return out;
|
||||
},
|
||||
sub: (a: P, b: P): P => {
|
||||
const len = checkLength(a, b);
|
||||
const out = _create(len);
|
||||
for (let i = 0; i < len; i++) out[i] = F.sub(a[i], b[i]);
|
||||
return out;
|
||||
},
|
||||
dot: (a: P, b: P): P => {
|
||||
const len = checkLength(a, b);
|
||||
const out = _create(len);
|
||||
for (let i = 0; i < len; i++) out[i] = F.mul(a[i], b[i]);
|
||||
return out;
|
||||
},
|
||||
mul: (a: P, b: P | T): P => {
|
||||
if (isPoly(b)) {
|
||||
const len = checkLength(a, b);
|
||||
if (fft) {
|
||||
const A = fft.direct(a, false, true);
|
||||
const B = fft.direct(b, false, true);
|
||||
for (let i = 0; i < A.length; i++) A[i] = F.mul(A[i], B[i]);
|
||||
return fft.inverse(A, true, false) as P;
|
||||
} else {
|
||||
// NOTE: this is quadratic and mostly for compat tests with FFT
|
||||
const res = _create(len);
|
||||
for (let i = 0; i < len; i++) {
|
||||
for (let j = 0; j < len; j++) {
|
||||
const k = (i + j) % len; // wrap mod length
|
||||
res[k] = F.add(res[k], F.mul(a[i], b[j]));
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
} else {
|
||||
const out = _create(checkLength(a));
|
||||
for (let i = 0; i < out.length; i++) out[i] = F.mul(a[i], b);
|
||||
return out;
|
||||
}
|
||||
},
|
||||
convolve(a: P, b: P): P {
|
||||
const len = nextPowerOfTwo(a.length + b.length - 1);
|
||||
return this.mul(this.extend(a, len), this.extend(b, len));
|
||||
},
|
||||
shift(p: P, factor: bigint): P {
|
||||
const out = _create(checkLength(p));
|
||||
out[0] = p[0];
|
||||
for (let i = 1, power = F.ONE; i < p.length; i++) {
|
||||
power = F.mul(power, factor);
|
||||
out[i] = F.mul(p[i], power);
|
||||
}
|
||||
return out;
|
||||
},
|
||||
clone: (a: P): P => {
|
||||
checkLength(a);
|
||||
const out = _create(a.length);
|
||||
for (let i = 0; i < a.length; i++) out[i] = a[i];
|
||||
return out;
|
||||
},
|
||||
eval: (a: P, basis: P): T => {
|
||||
checkLength(a);
|
||||
let acc = F.ZERO;
|
||||
for (let i = 0; i < a.length; i++) acc = F.add(acc, F.mul(a[i], basis[i]));
|
||||
return acc;
|
||||
},
|
||||
monomial: {
|
||||
basis: (x: T, n: number): P => {
|
||||
const out = _create(n);
|
||||
let pow = F.ONE;
|
||||
for (let i = 0; i < n; i++) {
|
||||
out[i] = pow;
|
||||
pow = F.mul(pow, x);
|
||||
}
|
||||
return out;
|
||||
},
|
||||
eval: (a: P, x: T): T => {
|
||||
checkLength(a);
|
||||
// Same as eval(a, monomialBasis(x, a.length)), but it is faster this way
|
||||
let acc = F.ZERO;
|
||||
for (let i = a.length - 1; i >= 0; i--) acc = F.add(F.mul(acc, x), a[i]);
|
||||
return acc;
|
||||
},
|
||||
},
|
||||
lagrange: {
|
||||
basis: (x: T, n: number, brp = false, weights?: P): P => {
|
||||
const bits = log2(n);
|
||||
const cache = weights || brp ? roots.brp(bits) : roots.roots(bits); // [ω⁰, ω¹, ..., ωⁿ⁻¹]
|
||||
const out = _create(n);
|
||||
// Fast Kronecker-δ shortcut
|
||||
const idx = findOmegaIndex(x, n, brp);
|
||||
if (idx !== -1) {
|
||||
out[idx] = F.ONE;
|
||||
return out;
|
||||
}
|
||||
const tm = F.pow(x, BigInt(n));
|
||||
const c = F.mul(F.sub(tm, F.ONE), F.inv(BigInt(n) as T)); // c = (xⁿ - 1)/n
|
||||
const denom = _create(n);
|
||||
for (let i = 0; i < n; i++) denom[i] = F.sub(x, cache[i] as T);
|
||||
const inv = F.invertBatch(denom as any as T[]);
|
||||
for (let i = 0; i < n; i++) out[i] = F.mul(c, F.mul(cache[i] as T, inv[i]));
|
||||
return out;
|
||||
},
|
||||
eval(a: P, x: T, brp = false): T {
|
||||
checkLength(a);
|
||||
const idx = findOmegaIndex(x, a.length, brp);
|
||||
if (idx !== -1) return a[idx]; // fast path
|
||||
const L = this.basis(x, a.length, brp); // Lᵢ(x)
|
||||
let acc = F.ZERO;
|
||||
for (let i = 0; i < a.length; i++) if (!F.is0(a[i])) acc = F.add(acc, F.mul(a[i], L[i]));
|
||||
return acc;
|
||||
},
|
||||
},
|
||||
vanishing(roots: P): P {
|
||||
checkLength(roots);
|
||||
const out = _create(roots.length + 1, F.ZERO);
|
||||
out[0] = F.ONE;
|
||||
for (const r of roots) {
|
||||
const neg = F.neg(r);
|
||||
for (let j = out.length - 1; j > 0; j--) out[j] = F.add(F.mul(out[j], neg), out[j - 1]);
|
||||
out[0] = F.mul(out[0], neg);
|
||||
}
|
||||
return out;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* HKDF (RFC 5869): extract + expand in one step.
|
||||
* See https://soatok.blog/2021/11/17/understanding-hkdf/.
|
||||
* @module
|
||||
*/
|
||||
import { hmac } from "./hmac.js";
|
||||
import { ahash, anumber, clean, toBytes } from "./utils.js";
|
||||
/**
|
||||
* HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`
|
||||
* Arguments position differs from spec (IKM is first one, since it is not optional)
|
||||
* @param hash - hash function that would be used (e.g. sha256)
|
||||
* @param ikm - input keying material, the initial key
|
||||
* @param salt - optional salt value (a non-secret random value)
|
||||
*/
|
||||
export function extract(hash, ikm, salt) {
|
||||
ahash(hash);
|
||||
// NOTE: some libraries treat zero-length array as 'not provided';
|
||||
// we don't, since we have undefined as 'not provided'
|
||||
// https://github.com/RustCrypto/KDFs/issues/15
|
||||
if (salt === undefined)
|
||||
salt = new Uint8Array(hash.outputLen);
|
||||
return hmac(hash, toBytes(salt), toBytes(ikm));
|
||||
}
|
||||
const HKDF_COUNTER = /* @__PURE__ */ Uint8Array.from([0]);
|
||||
const EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
|
||||
/**
|
||||
* HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`
|
||||
* @param hash - hash function that would be used (e.g. sha256)
|
||||
* @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)
|
||||
* @param info - optional context and application specific information (can be a zero-length string)
|
||||
* @param length - length of output keying material in bytes
|
||||
*/
|
||||
export function expand(hash, prk, info, length = 32) {
|
||||
ahash(hash);
|
||||
anumber(length);
|
||||
const olen = hash.outputLen;
|
||||
if (length > 255 * olen)
|
||||
throw new Error('Length should be <= 255*HashLen');
|
||||
const blocks = Math.ceil(length / olen);
|
||||
if (info === undefined)
|
||||
info = EMPTY_BUFFER;
|
||||
// first L(ength) octets of T
|
||||
const okm = new Uint8Array(blocks * olen);
|
||||
// Re-use HMAC instance between blocks
|
||||
const HMAC = hmac.create(hash, prk);
|
||||
const HMACTmp = HMAC._cloneInto();
|
||||
const T = new Uint8Array(HMAC.outputLen);
|
||||
for (let counter = 0; counter < blocks; counter++) {
|
||||
HKDF_COUNTER[0] = counter + 1;
|
||||
// T(0) = empty string (zero length)
|
||||
// T(N) = HMAC-Hash(PRK, T(N-1) | info | N)
|
||||
HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)
|
||||
.update(info)
|
||||
.update(HKDF_COUNTER)
|
||||
.digestInto(T);
|
||||
okm.set(T, olen * counter);
|
||||
HMAC._cloneInto(HMACTmp);
|
||||
}
|
||||
HMAC.destroy();
|
||||
HMACTmp.destroy();
|
||||
clean(T, HKDF_COUNTER);
|
||||
return okm.slice(0, length);
|
||||
}
|
||||
/**
|
||||
* HKDF (RFC 5869): derive keys from an initial input.
|
||||
* Combines hkdf_extract + hkdf_expand in one step
|
||||
* @param hash - hash function that would be used (e.g. sha256)
|
||||
* @param ikm - input keying material, the initial key
|
||||
* @param salt - optional salt value (a non-secret random value)
|
||||
* @param info - optional context and application specific information (can be a zero-length string)
|
||||
* @param length - length of output keying material in bytes
|
||||
* @example
|
||||
* import { hkdf } from '@noble/hashes/hkdf';
|
||||
* import { sha256 } from '@noble/hashes/sha2';
|
||||
* import { randomBytes } from '@noble/hashes/utils';
|
||||
* const inputKey = randomBytes(32);
|
||||
* const salt = randomBytes(32);
|
||||
* const info = 'application-key';
|
||||
* const hk1 = hkdf(sha256, inputKey, salt, info, 32);
|
||||
*/
|
||||
export const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);
|
||||
//# sourceMappingURL=hkdf.js.map
|
||||
@@ -0,0 +1,96 @@
|
||||
import { VariableSizeCodec, VariableSizeDecoder, VariableSizeEncoder } from '@solana/codecs-core';
|
||||
/**
|
||||
* Returns an encoder for `shortU16` values.
|
||||
*
|
||||
* This encoder serializes `shortU16` values using **1 to 3 bytes**.
|
||||
* Smaller values use fewer bytes, while larger values take up more space.
|
||||
*
|
||||
* For more details, see {@link getShortU16Codec}.
|
||||
*
|
||||
* @returns A `VariableSizeEncoder<number | bigint>` for encoding `shortU16` values.
|
||||
*
|
||||
* @example
|
||||
* Encoding a `shortU16` value.
|
||||
* ```ts
|
||||
* const encoder = getShortU16Encoder();
|
||||
* encoder.encode(42); // 0x2a
|
||||
* encoder.encode(128); // 0x8001
|
||||
* encoder.encode(16384); // 0x808001
|
||||
* ```
|
||||
*
|
||||
* @see {@link getShortU16Codec}
|
||||
*/
|
||||
export declare const getShortU16Encoder: () => VariableSizeEncoder<bigint | number>;
|
||||
/**
|
||||
* Returns a decoder for `shortU16` values.
|
||||
*
|
||||
* This decoder deserializes `shortU16` values from **1 to 3 bytes**.
|
||||
* The number of bytes used depends on the encoded value.
|
||||
*
|
||||
* For more details, see {@link getShortU16Codec}.
|
||||
*
|
||||
* @returns A `VariableSizeDecoder<number>` for decoding `shortU16` values.
|
||||
*
|
||||
* @example
|
||||
* Decoding a `shortU16` value.
|
||||
* ```ts
|
||||
* const decoder = getShortU16Decoder();
|
||||
* decoder.decode(new Uint8Array([0x2a])); // 42
|
||||
* decoder.decode(new Uint8Array([0x80, 0x01])); // 128
|
||||
* decoder.decode(new Uint8Array([0x80, 0x80, 0x01])); // 16384
|
||||
* ```
|
||||
*
|
||||
* @see {@link getShortU16Codec}
|
||||
*/
|
||||
export declare const getShortU16Decoder: () => VariableSizeDecoder<number>;
|
||||
/**
|
||||
* Returns a codec for encoding and decoding `shortU16` values.
|
||||
*
|
||||
* It serializes unsigned integers using **1 to 3 bytes** based on the encoded value.
|
||||
* The larger the value, the more bytes it uses.
|
||||
*
|
||||
* - If the value is `<= 0x7f` (127), it is stored in a **single byte**
|
||||
* and the first bit is set to `0` to indicate the end of the value.
|
||||
* - Otherwise, the first bit is set to `1` to indicate that the value continues in the next byte, which follows the same pattern.
|
||||
* - This process repeats until the value is fully encoded in up to 3 bytes. The third and last byte, if needed, uses all 8 bits to store the remaining value.
|
||||
*
|
||||
* In other words, the encoding scheme follows this structure:
|
||||
*
|
||||
* ```txt
|
||||
* 0XXXXXXX <- Values 0 to 127 (1 byte)
|
||||
* 1XXXXXXX 0XXXXXXX <- Values 128 to 16,383 (2 bytes)
|
||||
* 1XXXXXXX 1XXXXXXX XXXXXXXX <- Values 16,384 to 4,194,303 (3 bytes)
|
||||
* ```
|
||||
*
|
||||
* @returns A `VariableSizeCodec<number | bigint, number>` for encoding and decoding `shortU16` values.
|
||||
*
|
||||
* @example
|
||||
* Encoding and decoding `shortU16` values.
|
||||
* ```ts
|
||||
* const codec = getShortU16Codec();
|
||||
* const bytes1 = codec.encode(42); // 0x2a
|
||||
* const bytes2 = codec.encode(128); // 0x8001
|
||||
* const bytes3 = codec.encode(16384); // 0x808001
|
||||
*
|
||||
* codec.decode(bytes1); // 42
|
||||
* codec.decode(bytes2); // 128
|
||||
* codec.decode(bytes3); // 16384
|
||||
* ```
|
||||
*
|
||||
* @remarks
|
||||
* This codec efficiently stores small numbers, making it useful for transactions and compact representations.
|
||||
*
|
||||
* If you need a fixed-size `u16` codec, consider using {@link getU16Codec}.
|
||||
*
|
||||
* Separate {@link getShortU16Encoder} and {@link getShortU16Decoder} functions are available.
|
||||
*
|
||||
* ```ts
|
||||
* const bytes = getShortU16Encoder().encode(42);
|
||||
* const value = getShortU16Decoder().decode(bytes);
|
||||
* ```
|
||||
*
|
||||
* @see {@link getShortU16Encoder}
|
||||
* @see {@link getShortU16Decoder}
|
||||
*/
|
||||
export declare const getShortU16Codec: () => VariableSizeCodec<bigint | number, number>;
|
||||
//# sourceMappingURL=short-u16.d.ts.map
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"pbkdf2.js","sourceRoot":"","sources":["../src/pbkdf2.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,kBAAkB;AAClB,OAAO,EACL,KAAK,EAAE,OAAO,EACd,SAAS,EAAE,SAAS,EAAE,KAAK,EAAE,UAAU,EAAE,IAAI,EAAE,eAAe,EAG/D,MAAM,YAAY,CAAC;AAOpB,wDAAwD;AACxD,SAAS,UAAU,CAAC,IAAW,EAAE,SAAmB,EAAE,KAAe,EAAE,KAAgB;IACrF,KAAK,CAAC,IAAI,CAAC,CAAC;IACZ,MAAM,IAAI,GAAG,SAAS,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IAC5D,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;IACrC,OAAO,CAAC,CAAC,CAAC,CAAC;IACX,OAAO,CAAC,KAAK,CAAC,CAAC;IACf,OAAO,CAAC,SAAS,CAAC,CAAC;IACnB,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;IAC5D,MAAM,QAAQ,GAAG,eAAe,CAAC,SAAS,CAAC,CAAC;IAC5C,MAAM,IAAI,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;IACpC,8CAA8C;IAC9C,MAAM,EAAE,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;IACjC,0CAA0C;IAC1C,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IACxC,MAAM,OAAO,GAAG,GAAG,CAAC,UAAU,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC9C,OAAO,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC;AACnD,CAAC;AAED,SAAS,YAAY,CACnB,GAAY,EACZ,OAAgB,EAChB,EAAc,EACd,IAAa,EACb,CAAa;IAEb,GAAG,CAAC,OAAO,EAAE,CAAC;IACd,OAAO,CAAC,OAAO,EAAE,CAAC;IAClB,IAAI,IAAI;QAAE,IAAI,CAAC,OAAO,EAAE,CAAC;IACzB,KAAK,CAAC,CAAC,CAAC,CAAC;IACT,OAAO,EAAE,CAAC;AACZ,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,MAAM,CACpB,IAAW,EACX,QAAkB,EAClB,IAAc,EACd,IAAe;IAEf,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,UAAU,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAC9E,IAAI,IAAS,CAAC,CAAC,eAAe;IAC9B,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;IAC9B,MAAM,IAAI,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC;IAC7B,MAAM,CAAC,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACxC,iCAAiC;IACjC,KAAK,IAAI,EAAE,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,EAAE,GAAG,GAAG,KAAK,EAAE,EAAE,EAAE,EAAE,GAAG,IAAI,GAAG,CAAC,SAAS,EAAE,CAAC;QAClE,+BAA+B;QAC/B,MAAM,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,GAAG,EAAE,GAAG,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC;QACjD,IAAI,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;QAC5B,6CAA6C;QAC7C,0CAA0C;QAC1C,CAAC,IAAI,GAAG,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC5D,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;QACjC,KAAK,IAAI,EAAE,GAAG,CAAC,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,CAAC;YAC9B,2BAA2B;YAC3B,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YAC7C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,EAAE;gBAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACpD,CAAC;IACH,CAAC;IACD,OAAO,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACjD,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,IAAW,EACX,QAAkB,EAClB,IAAc,EACd,IAAe;IAEf,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,UAAU,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IACzF,IAAI,IAAS,CAAC,CAAC,eAAe;IAC9B,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;IAC9B,MAAM,IAAI,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC;IAC7B,MAAM,CAAC,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACxC,iCAAiC;IACjC,KAAK,IAAI,EAAE,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,EAAE,GAAG,GAAG,KAAK,EAAE,EAAE,EAAE,EAAE,GAAG,IAAI,GAAG,CAAC,SAAS,EAAE,CAAC;QAClE,+BAA+B;QAC/B,MAAM,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,GAAG,EAAE,GAAG,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC;QACjD,IAAI,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;QAC5B,6CAA6C;QAC7C,0CAA0C;QAC1C,CAAC,IAAI,GAAG,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC5D,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;QACjC,MAAM,SAAS,CAAC,CAAC,GAAG,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE;YACrC,2BAA2B;YAC3B,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YAC7C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,EAAE;gBAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACpD,CAAC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACjD,CAAC"}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"regularExpressionFlags.enum.d.ts","sourceRoot":"","sources":["../../src/enums/regularExpressionFlags.enum.ts"],"names":[],"mappings":"AAAA,oBAAY,sBAAsB;IAC9B,IAAI,IAAI;IACR,UAAU,IAAS;IACnB,MAAM,IAAS;IACf,UAAU,IAAS;IACnB,SAAS,IAAS;IAClB,MAAM,KAAS;IACf,OAAO,KAAS;IAChB,WAAW,KAAS;IACpB,MAAM,MAAS;IACf,cAAc,KAAwB;CACzC"}
|
||||
@@ -0,0 +1,497 @@
|
||||
/**
|
||||
* @fileoverview Rule to check for max length on a line.
|
||||
* @author Matt DuVall <http://www.mattduvall.com>
|
||||
* @deprecated in ESLint v8.53.0
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Constants
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const OPTIONS_SCHEMA = {
|
||||
type: "object",
|
||||
properties: {
|
||||
code: {
|
||||
type: "integer",
|
||||
minimum: 0,
|
||||
},
|
||||
comments: {
|
||||
type: "integer",
|
||||
minimum: 0,
|
||||
},
|
||||
tabWidth: {
|
||||
type: "integer",
|
||||
minimum: 0,
|
||||
},
|
||||
ignorePattern: {
|
||||
type: "string",
|
||||
},
|
||||
ignoreComments: {
|
||||
type: "boolean",
|
||||
},
|
||||
ignoreStrings: {
|
||||
type: "boolean",
|
||||
},
|
||||
ignoreUrls: {
|
||||
type: "boolean",
|
||||
},
|
||||
ignoreTemplateLiterals: {
|
||||
type: "boolean",
|
||||
},
|
||||
ignoreRegExpLiterals: {
|
||||
type: "boolean",
|
||||
},
|
||||
ignoreTrailingComments: {
|
||||
type: "boolean",
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
};
|
||||
|
||||
const OPTIONS_OR_INTEGER_SCHEMA = {
|
||||
anyOf: [
|
||||
OPTIONS_SCHEMA,
|
||||
{
|
||||
type: "integer",
|
||||
minimum: 0,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
deprecated: {
|
||||
message: "Formatting rules are being moved out of ESLint core.",
|
||||
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
|
||||
deprecatedSince: "8.53.0",
|
||||
availableUntil: "11.0.0",
|
||||
replacedBy: [
|
||||
{
|
||||
message:
|
||||
"ESLint Stylistic now maintains deprecated stylistic core rules.",
|
||||
url: "https://eslint.style/guide/migration",
|
||||
plugin: {
|
||||
name: "@stylistic/eslint-plugin",
|
||||
url: "https://eslint.style",
|
||||
},
|
||||
rule: {
|
||||
name: "max-len",
|
||||
url: "https://eslint.style/rules/max-len",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
type: "layout",
|
||||
|
||||
docs: {
|
||||
description: "Enforce a maximum line length",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/latest/rules/max-len",
|
||||
},
|
||||
|
||||
schema: [
|
||||
OPTIONS_OR_INTEGER_SCHEMA,
|
||||
OPTIONS_OR_INTEGER_SCHEMA,
|
||||
OPTIONS_SCHEMA,
|
||||
],
|
||||
messages: {
|
||||
max: "This line has a length of {{lineLength}}. Maximum allowed is {{maxLength}}.",
|
||||
maxComment:
|
||||
"This line has a comment length of {{lineLength}}. Maximum allowed is {{maxCommentLength}}.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
/*
|
||||
* Inspired by https://datatracker.ietf.org/doc/html/rfc3986#appendix-B, however:
|
||||
* - They're matching an entire string that we know is a URI
|
||||
* - We're matching part of a string where we think there *might* be a URL
|
||||
* - We're only concerned about URLs, as picking out any URI would cause
|
||||
* too many false positives
|
||||
* - We don't care about matching the entire URL, any small segment is fine
|
||||
*/
|
||||
const URL_REGEXP = /[^:/?#]:\/\/[^?#]/u;
|
||||
|
||||
const sourceCode = context.sourceCode;
|
||||
|
||||
/**
|
||||
* Computes the length of a line that may contain tabs. The width of each
|
||||
* tab will be the number of spaces to the next tab stop.
|
||||
* @param {string} line The line.
|
||||
* @param {number} tabWidth The width of each tab stop in spaces.
|
||||
* @returns {number} The computed line length.
|
||||
* @private
|
||||
*/
|
||||
function computeLineLength(line, tabWidth) {
|
||||
let extraCharacterCount = 0;
|
||||
|
||||
line.replace(/\t/gu, (match, offset) => {
|
||||
const totalOffset = offset + extraCharacterCount,
|
||||
previousTabStopOffset = tabWidth
|
||||
? totalOffset % tabWidth
|
||||
: 0,
|
||||
spaceCount = tabWidth - previousTabStopOffset;
|
||||
|
||||
extraCharacterCount += spaceCount - 1; // -1 for the replaced tab
|
||||
});
|
||||
return Array.from(line).length + extraCharacterCount;
|
||||
}
|
||||
|
||||
// The options object must be the last option specified…
|
||||
const options = Object.assign({}, context.options.at(-1));
|
||||
|
||||
// …but max code length…
|
||||
if (typeof context.options[0] === "number") {
|
||||
options.code = context.options[0];
|
||||
}
|
||||
|
||||
// …and tabWidth can be optionally specified directly as integers.
|
||||
if (typeof context.options[1] === "number") {
|
||||
options.tabWidth = context.options[1];
|
||||
}
|
||||
|
||||
const maxLength = typeof options.code === "number" ? options.code : 80,
|
||||
tabWidth =
|
||||
typeof options.tabWidth === "number" ? options.tabWidth : 4,
|
||||
ignoreComments = !!options.ignoreComments,
|
||||
ignoreStrings = !!options.ignoreStrings,
|
||||
ignoreTemplateLiterals = !!options.ignoreTemplateLiterals,
|
||||
ignoreRegExpLiterals = !!options.ignoreRegExpLiterals,
|
||||
ignoreTrailingComments =
|
||||
!!options.ignoreTrailingComments || !!options.ignoreComments,
|
||||
ignoreUrls = !!options.ignoreUrls,
|
||||
maxCommentLength = options.comments;
|
||||
let ignorePattern = options.ignorePattern || null;
|
||||
|
||||
if (ignorePattern) {
|
||||
ignorePattern = new RegExp(ignorePattern, "u");
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Tells if a given comment is trailing: it starts on the current line and
|
||||
* extends to or past the end of the current line.
|
||||
* @param {string} line The source line we want to check for a trailing comment on
|
||||
* @param {number} lineNumber The one-indexed line number for line
|
||||
* @param {ASTNode} comment The comment to inspect
|
||||
* @returns {boolean} If the comment is trailing on the given line
|
||||
*/
|
||||
function isTrailingComment(line, lineNumber, comment) {
|
||||
return (
|
||||
comment &&
|
||||
comment.loc.start.line === lineNumber &&
|
||||
lineNumber <= comment.loc.end.line &&
|
||||
(comment.loc.end.line > lineNumber ||
|
||||
comment.loc.end.column === line.length)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if a comment encompasses the entire line.
|
||||
* @param {string} line The source line with a trailing comment
|
||||
* @param {number} lineNumber The one-indexed line number this is on
|
||||
* @param {ASTNode} comment The comment to remove
|
||||
* @returns {boolean} If the comment covers the entire line
|
||||
*/
|
||||
function isFullLineComment(line, lineNumber, comment) {
|
||||
const start = comment.loc.start,
|
||||
end = comment.loc.end,
|
||||
isFirstTokenOnLine = !line
|
||||
.slice(0, comment.loc.start.column)
|
||||
.trim();
|
||||
|
||||
return (
|
||||
comment &&
|
||||
(start.line < lineNumber ||
|
||||
(start.line === lineNumber && isFirstTokenOnLine)) &&
|
||||
(end.line > lineNumber ||
|
||||
(end.line === lineNumber && end.column === line.length))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a node is a JSXEmptyExpression contained in a single line JSXExpressionContainer.
|
||||
* @param {ASTNode} node A node to check.
|
||||
* @returns {boolean} True if the node is a JSXEmptyExpression contained in a single line JSXExpressionContainer.
|
||||
*/
|
||||
function isJSXEmptyExpressionInSingleLineContainer(node) {
|
||||
if (
|
||||
!node ||
|
||||
!node.parent ||
|
||||
node.type !== "JSXEmptyExpression" ||
|
||||
node.parent.type !== "JSXExpressionContainer"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const parent = node.parent;
|
||||
|
||||
return parent.loc.start.line === parent.loc.end.line;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the line after the comment and any remaining trailing whitespace is
|
||||
* stripped.
|
||||
* @param {string} line The source line with a trailing comment
|
||||
* @param {ASTNode} comment The comment to remove
|
||||
* @returns {string} Line without comment and trailing whitespace
|
||||
*/
|
||||
function stripTrailingComment(line, comment) {
|
||||
// loc.column is zero-indexed
|
||||
return line.slice(0, comment.loc.start.column).replace(/\s+$/u, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure that an array exists at [key] on `object`, and add `value` to it.
|
||||
* @param {Object} object the object to mutate
|
||||
* @param {string} key the object's key
|
||||
* @param {any} value the value to add
|
||||
* @returns {void}
|
||||
* @private
|
||||
*/
|
||||
function ensureArrayAndPush(object, key, value) {
|
||||
if (!Array.isArray(object[key])) {
|
||||
object[key] = [];
|
||||
}
|
||||
object[key].push(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves an array containing all strings (" or ') in the source code.
|
||||
* @returns {ASTNode[]} An array of string nodes.
|
||||
*/
|
||||
function getAllStrings() {
|
||||
return sourceCode.ast.tokens.filter(
|
||||
token =>
|
||||
token.type === "String" ||
|
||||
(token.type === "JSXText" &&
|
||||
sourceCode.getNodeByRangeIndex(token.range[0] - 1)
|
||||
.type === "JSXAttribute"),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves an array containing all template literals in the source code.
|
||||
* @returns {ASTNode[]} An array of template literal nodes.
|
||||
*/
|
||||
function getAllTemplateLiterals() {
|
||||
return sourceCode.ast.tokens.filter(
|
||||
token => token.type === "Template",
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves an array containing all RegExp literals in the source code.
|
||||
* @returns {ASTNode[]} An array of RegExp literal nodes.
|
||||
*/
|
||||
function getAllRegExpLiterals() {
|
||||
return sourceCode.ast.tokens.filter(
|
||||
token => token.type === "RegularExpression",
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* reduce an array of AST nodes by line number, both start and end.
|
||||
* @param {ASTNode[]} arr array of AST nodes
|
||||
* @returns {Object} accululated AST nodes
|
||||
*/
|
||||
function groupArrayByLineNumber(arr) {
|
||||
const obj = {};
|
||||
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
const node = arr[i];
|
||||
|
||||
for (let j = node.loc.start.line; j <= node.loc.end.line; ++j) {
|
||||
ensureArrayAndPush(obj, j, node);
|
||||
}
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of all comments in the source code.
|
||||
* If the element in the array is a JSXEmptyExpression contained with a single line JSXExpressionContainer,
|
||||
* the element is changed with JSXExpressionContainer node.
|
||||
* @returns {ASTNode[]} An array of comment nodes
|
||||
*/
|
||||
function getAllComments() {
|
||||
const comments = [];
|
||||
|
||||
sourceCode.getAllComments().forEach(commentNode => {
|
||||
const containingNode = sourceCode.getNodeByRangeIndex(
|
||||
commentNode.range[0],
|
||||
);
|
||||
|
||||
if (isJSXEmptyExpressionInSingleLineContainer(containingNode)) {
|
||||
// push a unique node only
|
||||
if (comments.at(-1) !== containingNode.parent) {
|
||||
comments.push(containingNode.parent);
|
||||
}
|
||||
} else {
|
||||
comments.push(commentNode);
|
||||
}
|
||||
});
|
||||
|
||||
return comments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the program for max length
|
||||
* @param {ASTNode} node Node to examine
|
||||
* @returns {void}
|
||||
* @private
|
||||
*/
|
||||
function checkProgramForMaxLength(node) {
|
||||
// split (honors line-ending)
|
||||
const lines = sourceCode.lines,
|
||||
// list of comments to ignore
|
||||
comments =
|
||||
ignoreComments || maxCommentLength || ignoreTrailingComments
|
||||
? getAllComments()
|
||||
: [];
|
||||
|
||||
// we iterate over comments in parallel with the lines
|
||||
let commentsIndex = 0;
|
||||
|
||||
const strings = getAllStrings();
|
||||
const stringsByLine = groupArrayByLineNumber(strings);
|
||||
|
||||
const templateLiterals = getAllTemplateLiterals();
|
||||
const templateLiteralsByLine =
|
||||
groupArrayByLineNumber(templateLiterals);
|
||||
|
||||
const regExpLiterals = getAllRegExpLiterals();
|
||||
const regExpLiteralsByLine = groupArrayByLineNumber(regExpLiterals);
|
||||
|
||||
lines.forEach((line, i) => {
|
||||
// i is zero-indexed, line numbers are one-indexed
|
||||
const lineNumber = i + 1;
|
||||
|
||||
/*
|
||||
* if we're checking comment length; we need to know whether this
|
||||
* line is a comment
|
||||
*/
|
||||
let lineIsComment = false;
|
||||
let textToMeasure;
|
||||
|
||||
/*
|
||||
* We can short-circuit the comment checks if we're already out of
|
||||
* comments to check.
|
||||
*/
|
||||
if (commentsIndex < comments.length) {
|
||||
let comment;
|
||||
|
||||
// iterate over comments until we find one past the current line
|
||||
do {
|
||||
comment = comments[++commentsIndex];
|
||||
} while (comment && comment.loc.start.line <= lineNumber);
|
||||
|
||||
// and step back by one
|
||||
comment = comments[--commentsIndex];
|
||||
|
||||
if (isFullLineComment(line, lineNumber, comment)) {
|
||||
lineIsComment = true;
|
||||
textToMeasure = line;
|
||||
} else if (
|
||||
ignoreTrailingComments &&
|
||||
isTrailingComment(line, lineNumber, comment)
|
||||
) {
|
||||
textToMeasure = stripTrailingComment(line, comment);
|
||||
|
||||
// ignore multiple trailing comments in the same line
|
||||
let lastIndex = commentsIndex;
|
||||
|
||||
while (
|
||||
isTrailingComment(
|
||||
textToMeasure,
|
||||
lineNumber,
|
||||
comments[--lastIndex],
|
||||
)
|
||||
) {
|
||||
textToMeasure = stripTrailingComment(
|
||||
textToMeasure,
|
||||
comments[lastIndex],
|
||||
);
|
||||
}
|
||||
} else {
|
||||
textToMeasure = line;
|
||||
}
|
||||
} else {
|
||||
textToMeasure = line;
|
||||
}
|
||||
if (
|
||||
(ignorePattern && ignorePattern.test(textToMeasure)) ||
|
||||
(ignoreUrls && URL_REGEXP.test(textToMeasure)) ||
|
||||
(ignoreStrings && stringsByLine[lineNumber]) ||
|
||||
(ignoreTemplateLiterals &&
|
||||
templateLiteralsByLine[lineNumber]) ||
|
||||
(ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber])
|
||||
) {
|
||||
// ignore this line
|
||||
return;
|
||||
}
|
||||
|
||||
const lineLength = computeLineLength(textToMeasure, tabWidth);
|
||||
const commentLengthApplies = lineIsComment && maxCommentLength;
|
||||
|
||||
if (lineIsComment && ignoreComments) {
|
||||
return;
|
||||
}
|
||||
|
||||
const loc = {
|
||||
start: {
|
||||
line: lineNumber,
|
||||
column: 0,
|
||||
},
|
||||
end: {
|
||||
line: lineNumber,
|
||||
column: textToMeasure.length,
|
||||
},
|
||||
};
|
||||
|
||||
if (commentLengthApplies) {
|
||||
if (lineLength > maxCommentLength) {
|
||||
context.report({
|
||||
node,
|
||||
loc,
|
||||
messageId: "maxComment",
|
||||
data: {
|
||||
lineLength,
|
||||
maxCommentLength,
|
||||
},
|
||||
});
|
||||
}
|
||||
} else if (lineLength > maxLength) {
|
||||
context.report({
|
||||
node,
|
||||
loc,
|
||||
messageId: "max",
|
||||
data: {
|
||||
lineLength,
|
||||
maxLength,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Public API
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
return {
|
||||
Program: checkProgramForMaxLength,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
"use strict";
|
||||
|
||||
function _class_extract_field_descriptor(receiver, privateMap, action) {
|
||||
if (!privateMap.has(receiver)) throw new TypeError("attempted to " + action + " private field on non-instance");
|
||||
|
||||
return privateMap.get(receiver);
|
||||
}
|
||||
exports._ = _class_extract_field_descriptor;
|
||||
@@ -0,0 +1,135 @@
|
||||
"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: "caratteri", verb: "avere" },
|
||||
file: { unit: "byte", verb: "avere" },
|
||||
array: { unit: "elementi", verb: "avere" },
|
||||
set: { unit: "elementi", verb: "avere" },
|
||||
};
|
||||
function getSizing(origin) {
|
||||
return Sizable[origin] ?? null;
|
||||
}
|
||||
const FormatDictionary = {
|
||||
regex: "input",
|
||||
email: "indirizzo 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: "data e ora ISO",
|
||||
date: "data ISO",
|
||||
time: "ora ISO",
|
||||
duration: "durata ISO",
|
||||
ipv4: "indirizzo IPv4",
|
||||
ipv6: "indirizzo IPv6",
|
||||
cidrv4: "intervallo IPv4",
|
||||
cidrv6: "intervallo IPv6",
|
||||
base64: "stringa codificata in base64",
|
||||
base64url: "URL codificata in base64",
|
||||
json_string: "stringa JSON",
|
||||
e164: "numero E.164",
|
||||
jwt: "JWT",
|
||||
template_literal: "input",
|
||||
};
|
||||
const TypeDictionary = {
|
||||
nan: "NaN",
|
||||
number: "numero",
|
||||
array: "vettore",
|
||||
};
|
||||
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 `Input non valido: atteso instanceof ${issue.expected}, ricevuto ${received}`;
|
||||
}
|
||||
return `Input non valido: atteso ${expected}, ricevuto ${received}`;
|
||||
}
|
||||
case "invalid_value":
|
||||
if (issue.values.length === 1)
|
||||
return `Input non valido: atteso ${util.stringifyPrimitive(issue.values[0])}`;
|
||||
return `Opzione non valida: atteso uno tra ${util.joinValues(issue.values, "|")}`;
|
||||
case "too_big": {
|
||||
const adj = issue.inclusive ? "<=" : "<";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing)
|
||||
return `Troppo grande: ${issue.origin ?? "valore"} deve avere ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementi"}`;
|
||||
return `Troppo grande: ${issue.origin ?? "valore"} deve essere ${adj}${issue.maximum.toString()}`;
|
||||
}
|
||||
case "too_small": {
|
||||
const adj = issue.inclusive ? ">=" : ">";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing) {
|
||||
return `Troppo piccolo: ${issue.origin} deve avere ${adj}${issue.minimum.toString()} ${sizing.unit}`;
|
||||
}
|
||||
return `Troppo piccolo: ${issue.origin} deve essere ${adj}${issue.minimum.toString()}`;
|
||||
}
|
||||
case "invalid_format": {
|
||||
const _issue = issue;
|
||||
if (_issue.format === "starts_with")
|
||||
return `Stringa non valida: deve iniziare con "${_issue.prefix}"`;
|
||||
if (_issue.format === "ends_with")
|
||||
return `Stringa non valida: deve terminare con "${_issue.suffix}"`;
|
||||
if (_issue.format === "includes")
|
||||
return `Stringa non valida: deve includere "${_issue.includes}"`;
|
||||
if (_issue.format === "regex")
|
||||
return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;
|
||||
return `Input non valido: ${FormatDictionary[_issue.format] ?? issue.format}`;
|
||||
}
|
||||
case "not_multiple_of":
|
||||
return `Numero non valido: deve essere un multiplo di ${issue.divisor}`;
|
||||
case "unrecognized_keys":
|
||||
return `Chiav${issue.keys.length > 1 ? "i" : "e"} non riconosciut${issue.keys.length > 1 ? "e" : "a"}: ${util.joinValues(issue.keys, ", ")}`;
|
||||
case "invalid_key":
|
||||
return `Chiave non valida in ${issue.origin}`;
|
||||
case "invalid_union":
|
||||
return "Input non valido";
|
||||
case "invalid_element":
|
||||
return `Valore non valido in ${issue.origin}`;
|
||||
default:
|
||||
return `Input non valido`;
|
||||
}
|
||||
};
|
||||
};
|
||||
function default_1() {
|
||||
return {
|
||||
localeError: error(),
|
||||
};
|
||||
}
|
||||
module.exports = exports.default;
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "@types/estree",
|
||||
"version": "1.0.9",
|
||||
"description": "TypeScript definitions for estree",
|
||||
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree",
|
||||
"license": "MIT",
|
||||
"contributors": [
|
||||
{
|
||||
"name": "RReverser",
|
||||
"githubUsername": "RReverser",
|
||||
"url": "https://github.com/RReverser"
|
||||
}
|
||||
],
|
||||
"main": "",
|
||||
"types": "index.d.ts",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
|
||||
"directory": "types/estree"
|
||||
},
|
||||
"scripts": {},
|
||||
"dependencies": {},
|
||||
"peerDependencies": {},
|
||||
"typesPublisherContentHash": "db16da859cb0bee641414117047a4becba2e9f39d3e14a6745f887c47ef68482",
|
||||
"typeScriptVersion": "5.3",
|
||||
"nonNpm": true
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import type { Lib, TSESTree } from '@typescript-eslint/types';
|
||||
import type { Scope } from '../scope';
|
||||
import type { ScopeManager } from '../ScopeManager';
|
||||
import type { ReferenceImplicitGlobal } from './Reference';
|
||||
import type { VisitorOptions } from './Visitor';
|
||||
import { Visitor } from './Visitor';
|
||||
export interface ReferencerOptions extends VisitorOptions {
|
||||
jsxFragmentName: string | null;
|
||||
jsxPragma: string | null;
|
||||
lib: Lib[];
|
||||
}
|
||||
export declare class Referencer extends Visitor {
|
||||
#private;
|
||||
readonly scopeManager: ScopeManager;
|
||||
constructor(options: ReferencerOptions, scopeManager: ScopeManager);
|
||||
private populateGlobalsFromLib;
|
||||
/**
|
||||
* Resolves lib names into a deduplicated set of LibDefinitions,
|
||||
* including all transitive dependencies.
|
||||
*/
|
||||
private resolveLibDefinitions;
|
||||
close(node: TSESTree.Node): void;
|
||||
currentScope(): Scope;
|
||||
currentScope(throwOnNull: true): Scope | null;
|
||||
referencingDefaultValue(pattern: TSESTree.Identifier, assignments: (TSESTree.AssignmentExpression | TSESTree.AssignmentPattern)[], maybeImplicitGlobal: ReferenceImplicitGlobal | null, init: boolean): void;
|
||||
/**
|
||||
* Searches for a variable named "name" in the upper scopes and adds a pseudo-reference from itself to itself
|
||||
*/
|
||||
private referenceInSomeUpperScope;
|
||||
private referenceJsxFragment;
|
||||
private referenceJsxPragma;
|
||||
protected visitClass(node: TSESTree.ClassDeclaration | TSESTree.ClassExpression): void;
|
||||
protected visitForIn(node: TSESTree.ForInStatement | TSESTree.ForOfStatement): void;
|
||||
protected visitFunction(node: TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclaration | TSESTree.FunctionExpression | TSESTree.TSDeclareFunction | TSESTree.TSEmptyBodyFunctionExpression): void;
|
||||
protected visitFunctionParameterTypeAnnotation(node: TSESTree.Parameter): void;
|
||||
protected visitJSXElement(node: TSESTree.JSXClosingElement | TSESTree.JSXOpeningElement): void;
|
||||
protected visitProperty(node: TSESTree.Property): void;
|
||||
protected visitType(node: TSESTree.Node | null | undefined): void;
|
||||
protected visitTypeAssertion(node: TSESTree.TSAsExpression | TSESTree.TSSatisfiesExpression | TSESTree.TSTypeAssertion): void;
|
||||
protected ArrowFunctionExpression(node: TSESTree.ArrowFunctionExpression): void;
|
||||
protected AssignmentExpression(node: TSESTree.AssignmentExpression): void;
|
||||
protected BlockStatement(node: TSESTree.BlockStatement): void;
|
||||
protected BreakStatement(): void;
|
||||
protected CallExpression(node: TSESTree.CallExpression): void;
|
||||
protected CatchClause(node: TSESTree.CatchClause): void;
|
||||
protected ClassDeclaration(node: TSESTree.ClassDeclaration): void;
|
||||
protected ClassExpression(node: TSESTree.ClassExpression): void;
|
||||
protected ContinueStatement(): void;
|
||||
protected ExportAllDeclaration(): void;
|
||||
protected ExportDefaultDeclaration(node: TSESTree.ExportDefaultDeclaration): void;
|
||||
protected ExportNamedDeclaration(node: TSESTree.ExportNamedDeclaration): void;
|
||||
protected ForInStatement(node: TSESTree.ForInStatement): void;
|
||||
protected ForOfStatement(node: TSESTree.ForOfStatement): void;
|
||||
protected ForStatement(node: TSESTree.ForStatement): void;
|
||||
protected FunctionDeclaration(node: TSESTree.FunctionDeclaration): void;
|
||||
protected FunctionExpression(node: TSESTree.FunctionExpression): void;
|
||||
protected Identifier(node: TSESTree.Identifier): void;
|
||||
protected ImportAttribute(): void;
|
||||
protected ImportDeclaration(node: TSESTree.ImportDeclaration): void;
|
||||
protected JSXAttribute(node: TSESTree.JSXAttribute): void;
|
||||
protected JSXClosingElement(node: TSESTree.JSXClosingElement): void;
|
||||
protected JSXFragment(node: TSESTree.JSXFragment): void;
|
||||
protected JSXIdentifier(node: TSESTree.JSXIdentifier): void;
|
||||
protected JSXMemberExpression(node: TSESTree.JSXMemberExpression): void;
|
||||
protected JSXOpeningElement(node: TSESTree.JSXOpeningElement): void;
|
||||
protected LabeledStatement(node: TSESTree.LabeledStatement): void;
|
||||
protected MemberExpression(node: TSESTree.MemberExpression): void;
|
||||
protected MetaProperty(): void;
|
||||
protected NewExpression(node: TSESTree.NewExpression): void;
|
||||
protected PrivateIdentifier(): void;
|
||||
protected Program(node: TSESTree.Program): void;
|
||||
protected Property(node: TSESTree.Property): void;
|
||||
protected SwitchStatement(node: TSESTree.SwitchStatement): void;
|
||||
protected TaggedTemplateExpression(node: TSESTree.TaggedTemplateExpression): void;
|
||||
protected TSAsExpression(node: TSESTree.TSAsExpression): void;
|
||||
protected TSDeclareFunction(node: TSESTree.TSDeclareFunction): void;
|
||||
protected TSEmptyBodyFunctionExpression(node: TSESTree.TSEmptyBodyFunctionExpression): void;
|
||||
protected TSEnumDeclaration(node: TSESTree.TSEnumDeclaration): void;
|
||||
protected TSExportAssignment(node: TSESTree.TSExportAssignment): void;
|
||||
protected TSImportEqualsDeclaration(node: TSESTree.TSImportEqualsDeclaration): void;
|
||||
protected TSInstantiationExpression(node: TSESTree.TSInstantiationExpression): void;
|
||||
protected TSInterfaceDeclaration(node: TSESTree.TSInterfaceDeclaration): void;
|
||||
protected TSModuleDeclaration(node: TSESTree.TSModuleDeclaration): void;
|
||||
protected TSSatisfiesExpression(node: TSESTree.TSSatisfiesExpression): void;
|
||||
protected TSTypeAliasDeclaration(node: TSESTree.TSTypeAliasDeclaration): void;
|
||||
protected TSTypeAssertion(node: TSESTree.TSTypeAssertion): void;
|
||||
protected UpdateExpression(node: TSESTree.UpdateExpression): void;
|
||||
protected VariableDeclaration(node: TSESTree.VariableDeclaration): void;
|
||||
protected WithStatement(node: TSESTree.WithStatement): void;
|
||||
private visitExpressionTarget;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"crypto.js","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAOA,MAAM,CAAC,MAAM,MAAM,GACjB,OAAO,UAAU,KAAK,QAAQ,IAAI,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC"}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"sha3-addons.d.ts","sourceRoot":"","sources":["src/sha3-addons.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,MAAM,EAAE,KAAK,SAAS,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAGL,KAAK,MAAM,EACX,KAAK,OAAO,EAGZ,IAAI,EACJ,KAAK,OAAO,EACZ,KAAK,KAAK,EAGX,MAAM,YAAY,CAAC;AAoCpB,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG;IAAE,eAAe,CAAC,EAAE,KAAK,CAAC;IAAC,MAAM,CAAC,EAAE,KAAK,CAAA;CAAE,CAAC;AA0BjF,MAAM,MAAM,OAAO,GAAG;IACpB,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,UAAU,GAAG,UAAU,CAAC;IAC5C,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CAC3C,CAAC;AACF,MAAM,MAAM,UAAU,GAAG;IACvB,CAAC,QAAQ,EAAE,KAAK,EAAE,EAAE,IAAI,CAAC,EAAE,UAAU,GAAG,UAAU,CAAC;IACnD,MAAM,CAAC,IAAI,CAAC,EAAE,UAAU,GAAG,SAAS,CAAC;CACtC,CAAC;AACF,MAAM,MAAM,QAAQ,GAAG;IACrB,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,YAAY,GAAG,UAAU,CAAC;IAClD,MAAM,CAAC,IAAI,CAAC,EAAE,YAAY,GAAG,YAAY,CAAC;CAC3C,CAAC;AACF,eAAO,MAAM,SAAS,EAAE,OAAiE,CAAC;AAC1F,eAAO,MAAM,SAAS,EAAE,OAAiE,CAAC;AAE1F,qBAAa,IAAK,SAAQ,MAAO,YAAW,OAAO,CAAC,IAAI,CAAC;gBAErD,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,OAAO,EAClB,GAAG,EAAE,KAAK,EACV,IAAI,GAAE,UAAe;IAavB,SAAS,CAAC,MAAM,IAAI,IAAI;IAIxB,UAAU,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,IAAI;IAW3B,KAAK,IAAI,IAAI;CAGd;AAUD,eAAO,MAAM,OAAO,EAAE;IACpB,CAAC,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,UAAU,GAAG,UAAU,CAAC;IAC5D,MAAM,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,UAAU,GAAG,IAAI,CAAC;CACK,CAAC;AACpD,eAAO,MAAM,OAAO,EAAE;IACpB,CAAC,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,UAAU,GAAG,UAAU,CAAC;IAC5D,MAAM,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,UAAU,GAAG,IAAI,CAAC;CACK,CAAC;AACpD,eAAO,MAAM,UAAU,EAAE;IACvB,CAAC,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,UAAU,GAAG,UAAU,CAAC;IAC5D,MAAM,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,UAAU,GAAG,IAAI,CAAC;CACW,CAAC;AAC1D,eAAO,MAAM,UAAU,EAAE;IACvB,CAAC,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,UAAU,GAAG,UAAU,CAAC;IAC5D,MAAM,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,UAAU,GAAG,IAAI,CAAC;CACW,CAAC;AAI1D,qBAAa,SAAU,SAAQ,MAAO,YAAW,OAAO,CAAC,SAAS,CAAC;gBACrD,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,GAAE,UAAe;IAY1F,SAAS,CAAC,MAAM,IAAI,IAAI;IAKxB,UAAU,CAAC,EAAE,CAAC,EAAE,SAAS,GAAG,SAAS;IAIrC,KAAK,IAAI,SAAS;CAGnB;AAaD,yBAAyB;AACzB,eAAO,MAAM,YAAY,EAAE,UAA6D,CAAC;AACzF,yBAAyB;AACzB,eAAO,MAAM,YAAY,EAAE,UAA6D,CAAC;AACzF,6BAA6B;AAC7B,eAAO,MAAM,eAAe,EAAE,UAAmE,CAAC;AAClG,6BAA6B;AAC7B,eAAO,MAAM,eAAe,EAAE,UAAmE,CAAC;AAGlG,KAAK,YAAY,GAAG,UAAU,GAAG;IAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAEvD,qBAAa,YAAa,SAAQ,MAAO,YAAW,OAAO,CAAC,YAAY,CAAC;IACvE,OAAO,CAAC,QAAQ,CAAC,CAAe;IAChC,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAI,CAAC,MAAM,CAAC,CAAC;IACvC,OAAO,CAAC,QAAQ,CAAK;IACrB,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,QAAQ,CAAS;gBAEvB,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,IAAI,CAAC,MAAM,CAAC,EAC5B,SAAS,EAAE,OAAO,EAClB,IAAI,GAAE,YAAiB;IAgCzB,SAAS,CAAC,MAAM,IAAI,IAAI;IAUxB,UAAU,CAAC,EAAE,CAAC,EAAE,YAAY,GAAG,YAAY;IAQ3C,OAAO,IAAI,IAAI;IAIf,KAAK,IAAI,YAAY;CAGtB;AAqBD,uDAAuD;AACvD,eAAO,MAAM,eAAe,EAAE,QAAoE,CAAC;AACnG,uDAAuD;AACvD,eAAO,MAAM,eAAe,EAAE,QAAoE,CAAC;AACnG,2DAA2D;AAC3D,eAAO,MAAM,kBAAkB,EAAE,QACS,CAAC;AAC3C,uDAAuD;AACvD,eAAO,MAAM,kBAAkB,EAAE,QACS,CAAC;AAG3C,MAAM,MAAM,cAAc,GAAG,SAAS,GAAG;IACvC,CAAC,CAAC,EAAE,MAAM,CAAC;CACZ,CAAC;AAWF,mDAAmD;AACnD,eAAO,MAAM,aAAa,EAAE,OAAqD,CAAC;AAClF,mDAAmD;AACnD,eAAO,MAAM,aAAa,EAAE,OAAqD,CAAC;AAYlF,MAAM,MAAM,YAAY,GAAG;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,eAAe,CAAC,EAAE,KAAK,CAAA;CAAE,CAAC;AAGvE,qBAAa,cAAe,SAAQ,MAAO,YAAW,OAAO,CAAC,cAAc,CAAC;IAC3E,QAAQ,CAAC,QAAQ,QAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,CAAS;IAC1B,SAAS,CAAC,OAAO,EAAE,MAAM,CAAC;IAC1B,OAAO,CAAC,eAAe,CAAa;IACpC,OAAO,CAAC,QAAQ,CAAK;IACrB,OAAO,CAAC,UAAU,CAAK;gBAErB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,YAAY;IAMpB,MAAM,CAAC,IAAI,EAAE,KAAK,GAAG,IAAI;IAwBzB,SAAS,CAAC,MAAM,IAAI,IAAI;IAYxB,OAAO,IAAI,IAAI;IAMf,UAAU,CAAC,EAAE,CAAC,EAAE,cAAc,GAAG,cAAc;IAW/C,KAAK,IAAI,cAAc;CAGxB;AACD,+CAA+C;AAC/C,eAAO,MAAM,GAAG,EAAE,MAGZ,CAAC;AACP,oDAAoD;AACpD,eAAO,MAAM,GAAG,EAAE,MAGZ,CAAC;AAEP;;GAEG;AACH,qBAAa,SAAU,SAAQ,MAAM;IACnC,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;gBACX,QAAQ,EAAE,MAAM;IAU5B,MAAM,IAAI,IAAI;IAQd,MAAM,CAAC,IAAI,EAAE,KAAK,GAAG,IAAI;IAKzB,IAAI,CAAC,IAAI,EAAE,KAAK,GAAG,IAAI;IAGvB,SAAS,CAAC,MAAM,IAAI,IAAI;IACxB,UAAU,CAAC,IAAI,EAAE,UAAU,GAAG,UAAU;IAGxC,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU;IAIhC,MAAM,IAAI,IAAI;IAQd,UAAU,CAAC,EAAE,CAAC,EAAE,SAAS,GAAG,SAAS;IAOrC,KAAK,IAAI,SAAS;CAGnB;AAED,gGAAgG;AAChG,eAAO,MAAM,SAAS,GAAI,iBAAc,KAAG,SAAoC,CAAC"}
|
||||
@@ -0,0 +1,96 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createIsolatedProgram = createIsolatedProgram;
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const ts = __importStar(require("typescript"));
|
||||
const getScriptKind_1 = require("./getScriptKind");
|
||||
const shared_1 = require("./shared");
|
||||
const log = (0, debug_1.default)('typescript-eslint:typescript-estree:create-program:createIsolatedProgram');
|
||||
/**
|
||||
* @returns Returns a new source file and program corresponding to the linted code
|
||||
*/
|
||||
function createIsolatedProgram(parseSettings) {
|
||||
log('Getting isolated program in %s mode for: %s', parseSettings.jsx ? 'TSX' : 'TS', parseSettings.filePath);
|
||||
const compilerHost = {
|
||||
fileExists() {
|
||||
return true;
|
||||
},
|
||||
getCanonicalFileName() {
|
||||
return parseSettings.filePath;
|
||||
},
|
||||
getCurrentDirectory() {
|
||||
return '';
|
||||
},
|
||||
getDefaultLibFileName() {
|
||||
return 'lib.d.ts';
|
||||
},
|
||||
getDirectories() {
|
||||
return [];
|
||||
},
|
||||
// TODO: Support Windows CRLF
|
||||
getNewLine() {
|
||||
return '\n';
|
||||
},
|
||||
getSourceFile(filename) {
|
||||
return ts.createSourceFile(filename, parseSettings.codeFullText, ts.ScriptTarget.Latest,
|
||||
/* setParentNodes */ true, (0, getScriptKind_1.getScriptKind)(parseSettings.filePath, parseSettings.jsx));
|
||||
},
|
||||
readFile() {
|
||||
return undefined;
|
||||
},
|
||||
useCaseSensitiveFileNames() {
|
||||
return true;
|
||||
},
|
||||
writeFile() {
|
||||
return null;
|
||||
},
|
||||
};
|
||||
const program = ts.createProgram([parseSettings.filePath], {
|
||||
jsDocParsingMode: parseSettings.jsDocParsingMode,
|
||||
jsx: parseSettings.jsx ? ts.JsxEmit.Preserve : undefined,
|
||||
noResolve: true,
|
||||
target: ts.ScriptTarget.Latest,
|
||||
...(0, shared_1.createDefaultCompilerOptionsFromExtra)(parseSettings),
|
||||
}, compilerHost);
|
||||
const ast = program.getSourceFile(parseSettings.filePath);
|
||||
if (!ast) {
|
||||
throw new Error('Expected an ast to be returned for the single-file isolated program.');
|
||||
}
|
||||
return { ast, program };
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import type * as errors from "./errors.js";
|
||||
import type * as schemas from "./schemas.js";
|
||||
import type { Class } from "./util.js";
|
||||
////////////////////////////// CONSTRUCTORS ///////////////////////////////////////
|
||||
|
||||
type ZodTrait = { _zod: { def: any; [k: string]: any } };
|
||||
export interface $constructor<T extends ZodTrait, D = T["_zod"]["def"]> {
|
||||
new (def: D): T;
|
||||
init(inst: T, def: D): asserts inst is T;
|
||||
}
|
||||
|
||||
/** A special constant with type `never` */
|
||||
export const NEVER: never = /*@__PURE__*/ Object.freeze({
|
||||
status: "aborted",
|
||||
}) as never;
|
||||
|
||||
export /*@__NO_SIDE_EFFECTS__*/ function $constructor<T extends ZodTrait, D = T["_zod"]["def"]>(
|
||||
name: string,
|
||||
initializer: (inst: T, def: D) => void,
|
||||
params?: { Parent?: typeof Class }
|
||||
): $constructor<T, D> {
|
||||
function init(inst: T, def: D) {
|
||||
if (!inst._zod) {
|
||||
Object.defineProperty(inst, "_zod", {
|
||||
value: {
|
||||
def,
|
||||
constr: _,
|
||||
traits: new Set(),
|
||||
},
|
||||
enumerable: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (inst._zod.traits.has(name)) {
|
||||
return;
|
||||
}
|
||||
|
||||
inst._zod.traits.add(name);
|
||||
|
||||
initializer(inst, def);
|
||||
|
||||
// support prototype modifications
|
||||
const proto = _.prototype;
|
||||
const keys = Object.keys(proto);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const k = keys[i]!;
|
||||
if (!(k in inst)) {
|
||||
(inst as any)[k] = proto[k].bind(inst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// doesn't work if Parent has a constructor with arguments
|
||||
const Parent = params?.Parent ?? Object;
|
||||
class Definition extends Parent {}
|
||||
Object.defineProperty(Definition, "name", { value: name });
|
||||
|
||||
function _(this: any, def: D) {
|
||||
const inst = params?.Parent ? new Definition() : this;
|
||||
init(inst, def);
|
||||
inst._zod.deferred ??= [];
|
||||
for (const fn of inst._zod.deferred) {
|
||||
fn();
|
||||
}
|
||||
return inst;
|
||||
}
|
||||
|
||||
Object.defineProperty(_, "init", { value: init });
|
||||
Object.defineProperty(_, Symbol.hasInstance, {
|
||||
value: (inst: any) => {
|
||||
if (params?.Parent && inst instanceof params.Parent) return true;
|
||||
return inst?._zod?.traits?.has(name);
|
||||
},
|
||||
});
|
||||
Object.defineProperty(_, "name", { value: name });
|
||||
return _ as any;
|
||||
}
|
||||
|
||||
////////////////////////////// UTILITIES ///////////////////////////////////////
|
||||
export const $brand: unique symbol = Symbol("zod_brand");
|
||||
export type $brand<T extends string | number | symbol = string | number | symbol> = {
|
||||
[$brand]: { [k in T]: true };
|
||||
};
|
||||
|
||||
export type $ZodBranded<
|
||||
T extends schemas.SomeType,
|
||||
Brand extends string | number | symbol,
|
||||
Dir extends "in" | "out" | "inout" = "out",
|
||||
> = T &
|
||||
(Dir extends "inout"
|
||||
? { _zod: { input: input<T> & $brand<Brand>; output: output<T> & $brand<Brand> } }
|
||||
: Dir extends "in"
|
||||
? { _zod: { input: input<T> & $brand<Brand> } }
|
||||
: { _zod: { output: output<T> & $brand<Brand> } });
|
||||
|
||||
export type $ZodNarrow<T extends schemas.SomeType, Out> = T & { _zod: { output: Out } };
|
||||
|
||||
export class $ZodAsyncError extends Error {
|
||||
constructor() {
|
||||
super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
|
||||
}
|
||||
}
|
||||
|
||||
export class $ZodEncodeError extends Error {
|
||||
constructor(name: string) {
|
||||
super(`Encountered unidirectional transform during encode: ${name}`);
|
||||
this.name = "ZodEncodeError";
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////// TYPE HELPERS ///////////////////////////////////
|
||||
|
||||
// export type input<T extends schemas.$ZodType> = T["_zod"]["input"];
|
||||
// export type output<T extends schemas.$ZodType> = T["_zod"]["output"];
|
||||
// export type input<T extends schemas.$ZodType> = T["_zod"]["input"];
|
||||
// export type output<T extends schemas.$ZodType> = T["_zod"]["output"];
|
||||
export type input<T> = T extends { _zod: { input: any } } ? T["_zod"]["input"] : unknown;
|
||||
export type output<T> = T extends { _zod: { output: any } } ? T["_zod"]["output"] : unknown;
|
||||
|
||||
export type { output as infer };
|
||||
|
||||
////////////////////////////// CONFIG ///////////////////////////////////////
|
||||
|
||||
export interface $ZodConfig {
|
||||
/** Custom error map. Overrides `config().localeError`. */
|
||||
customError?: errors.$ZodErrorMap | undefined;
|
||||
/** Localized error map. Lowest priority. */
|
||||
localeError?: errors.$ZodErrorMap | undefined;
|
||||
/** Disable JIT schema compilation. Useful in environments that disallow `eval`. */
|
||||
jitless?: boolean | undefined;
|
||||
}
|
||||
|
||||
interface GlobalThisWithConfig {
|
||||
/**
|
||||
* The globalConfig instance shared across both CommonJS and ESM builds.
|
||||
* Attached to `globalThis` (mirroring `__zod_globalRegistry`) so that a
|
||||
* single config object is used regardless of how Zod is loaded — CJS,
|
||||
* ESM, multiple bundles in a monorepo, etc. This means `z.config(...)`
|
||||
* applied against any one instance is observed by all of them, and
|
||||
* pre-populating it before Zod loads (e.g. `globalThis.__zod_globalConfig
|
||||
* = { jitless: true }` in an inline script) takes effect immediately on
|
||||
* import.
|
||||
*/
|
||||
__zod_globalConfig?: $ZodConfig;
|
||||
}
|
||||
|
||||
(globalThis as GlobalThisWithConfig).__zod_globalConfig ??= {};
|
||||
export const globalConfig: $ZodConfig = (globalThis as GlobalThisWithConfig).__zod_globalConfig!;
|
||||
|
||||
export function config(newConfig?: Partial<$ZodConfig>): $ZodConfig {
|
||||
if (newConfig) Object.assign(globalConfig, newConfig);
|
||||
return globalConfig;
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.VariableDefinition = void 0;
|
||||
const DefinitionBase_1 = require("./DefinitionBase");
|
||||
const DefinitionType_1 = require("./DefinitionType");
|
||||
class VariableDefinition extends DefinitionBase_1.DefinitionBase {
|
||||
isTypeDefinition = false;
|
||||
isVariableDefinition = true;
|
||||
constructor(name, node, decl) {
|
||||
super(DefinitionType_1.DefinitionType.Variable, name, node, decl);
|
||||
}
|
||||
}
|
||||
exports.VariableDefinition = VariableDefinition;
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,59 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isNotSemicolonToken = exports.isSemicolonToken = exports.isNotOpeningParenToken = exports.isOpeningParenToken = exports.isNotOpeningBracketToken = exports.isOpeningBracketToken = exports.isNotOpeningBraceToken = exports.isOpeningBraceToken = exports.isNotCommentToken = exports.isCommentToken = exports.isNotCommaToken = exports.isCommaToken = exports.isNotColonToken = exports.isColonToken = exports.isNotClosingParenToken = exports.isClosingParenToken = exports.isNotClosingBracketToken = exports.isClosingBracketToken = exports.isNotClosingBraceToken = exports.isClosingBraceToken = exports.isNotArrowToken = exports.isArrowToken = void 0;
|
||||
const eslintUtils = __importStar(require("@eslint-community/eslint-utils"));
|
||||
exports.isArrowToken = eslintUtils.isArrowToken;
|
||||
exports.isNotArrowToken = eslintUtils.isNotArrowToken;
|
||||
exports.isClosingBraceToken = eslintUtils.isClosingBraceToken;
|
||||
exports.isNotClosingBraceToken = eslintUtils.isNotClosingBraceToken;
|
||||
exports.isClosingBracketToken = eslintUtils.isClosingBracketToken;
|
||||
exports.isNotClosingBracketToken = eslintUtils.isNotClosingBracketToken;
|
||||
exports.isClosingParenToken = eslintUtils.isClosingParenToken;
|
||||
exports.isNotClosingParenToken = eslintUtils.isNotClosingParenToken;
|
||||
exports.isColonToken = eslintUtils.isColonToken;
|
||||
exports.isNotColonToken = eslintUtils.isNotColonToken;
|
||||
exports.isCommaToken = eslintUtils.isCommaToken;
|
||||
exports.isNotCommaToken = eslintUtils.isNotCommaToken;
|
||||
exports.isCommentToken = eslintUtils.isCommentToken;
|
||||
exports.isNotCommentToken = eslintUtils.isNotCommentToken;
|
||||
exports.isOpeningBraceToken = eslintUtils.isOpeningBraceToken;
|
||||
exports.isNotOpeningBraceToken = eslintUtils.isNotOpeningBraceToken;
|
||||
exports.isOpeningBracketToken = eslintUtils.isOpeningBracketToken;
|
||||
exports.isNotOpeningBracketToken = eslintUtils.isNotOpeningBracketToken;
|
||||
exports.isOpeningParenToken = eslintUtils.isOpeningParenToken;
|
||||
exports.isNotOpeningParenToken = eslintUtils.isNotOpeningParenToken;
|
||||
exports.isSemicolonToken = eslintUtils.isSemicolonToken;
|
||||
exports.isNotSemicolonToken = eslintUtils.isNotSemicolonToken;
|
||||
@@ -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: "อิโมจิ",
|
||||
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: "ช่วง IP แบบ IPv4",
|
||||
cidrv6: "ช่วง IP แบบ IPv6",
|
||||
base64: "ข้อความแบบ Base64",
|
||||
base64url: "ข้อความแบบ Base64 สำหรับ URL",
|
||||
json_string: "ข้อความแบบ JSON",
|
||||
e164: "เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",
|
||||
jwt: "โทเคน JWT",
|
||||
template_literal: "ข้อมูลที่ป้อน",
|
||||
};
|
||||
const TypeDictionary = {
|
||||
nan: "NaN",
|
||||
number: "ตัวเลข",
|
||||
array: "อาร์เรย์ (Array)",
|
||||
null: "ไม่มีค่า (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 `พบคีย์ที่ไม่รู้จัก: ${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 @@
|
||||
export let nanoid=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce(((t,e)=>t+=(e&=63)<36?e.toString(36):e<62?(e-26).toString(36).toUpperCase():e<63?"_":"-"),"");
|
||||
@@ -0,0 +1,2 @@
|
||||
import type { LibDefinition } from '../variable';
|
||||
export declare const es2017: LibDefinition;
|
||||
@@ -0,0 +1,86 @@
|
||||
import Container, { ContainerProps } from './container.js'
|
||||
import Document from './document.js'
|
||||
import { ProcessOptions } from './postcss.js'
|
||||
import Result from './result.js'
|
||||
|
||||
declare namespace Root {
|
||||
export interface RootRaws extends Record<string, any> {
|
||||
/**
|
||||
* The space symbols after the last child to the end of file.
|
||||
*/
|
||||
after?: string
|
||||
|
||||
/**
|
||||
* Non-CSS code after `Root`, when `Root` is inside `Document`.
|
||||
*
|
||||
* **Experimental:** some aspects of this node could change within minor
|
||||
* or patch version releases.
|
||||
*/
|
||||
codeAfter?: string
|
||||
|
||||
/**
|
||||
* Non-CSS code before `Root`, when `Root` is inside `Document`.
|
||||
*
|
||||
* **Experimental:** some aspects of this node could change within minor
|
||||
* or patch version releases.
|
||||
*/
|
||||
codeBefore?: string
|
||||
|
||||
/**
|
||||
* Is the last child has an (optional) semicolon.
|
||||
*/
|
||||
semicolon?: boolean
|
||||
}
|
||||
|
||||
export interface RootProps extends ContainerProps {
|
||||
/**
|
||||
* Information used to generate byte-to-byte equal node string
|
||||
* as it was in the origin input.
|
||||
* */
|
||||
raws?: RootRaws
|
||||
}
|
||||
|
||||
export { Root_ as default }
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a CSS file and contains all its parsed nodes.
|
||||
*
|
||||
* ```js
|
||||
* const root = postcss.parse('a{color:black} b{z-index:2}')
|
||||
* root.type //=> 'root'
|
||||
* root.nodes.length //=> 2
|
||||
* ```
|
||||
*/
|
||||
declare class Root_ extends Container {
|
||||
nodes: NonNullable<Container['nodes']>
|
||||
parent: Document | undefined
|
||||
raws: Root.RootRaws
|
||||
type: 'root'
|
||||
|
||||
constructor(defaults?: Root.RootProps)
|
||||
|
||||
assign(overrides: object | Root.RootProps): this
|
||||
clone(overrides?: Partial<Root.RootProps>): this
|
||||
cloneAfter(overrides?: Partial<Root.RootProps>): this
|
||||
cloneBefore(overrides?: Partial<Root.RootProps>): this
|
||||
|
||||
/**
|
||||
* Returns a `Result` instance representing the root’s CSS.
|
||||
*
|
||||
* ```js
|
||||
* const root1 = postcss.parse(css1, { from: 'a.css' })
|
||||
* const root2 = postcss.parse(css2, { from: 'b.css' })
|
||||
* root1.append(root2)
|
||||
* const result = root1.toResult({ to: 'all.css', map: true })
|
||||
* ```
|
||||
*
|
||||
* @param options Options.
|
||||
* @return Result with current root’s CSS.
|
||||
*/
|
||||
toResult(options?: ProcessOptions): Result
|
||||
}
|
||||
|
||||
declare class Root extends Root_ {}
|
||||
|
||||
export = Root
|
||||
@@ -0,0 +1,174 @@
|
||||
import { a as namespaces, i as enabled, n as disable, o as humanize, r as enable$1, s as selectColor, t as createDebug$1 } from "./core.js";
|
||||
import { isatty } from "node:tty";
|
||||
import { formatWithOptions, inspect } from "node:util";
|
||||
//#region src/node.ts
|
||||
let env = {};
|
||||
try {
|
||||
process.env.DEBUG;
|
||||
env = process.env;
|
||||
} catch (_unused) {}
|
||||
const colors = process.stderr.getColorDepth && process.stderr.getColorDepth(env) > 2 ? [
|
||||
20,
|
||||
21,
|
||||
26,
|
||||
27,
|
||||
32,
|
||||
33,
|
||||
38,
|
||||
39,
|
||||
40,
|
||||
41,
|
||||
42,
|
||||
43,
|
||||
44,
|
||||
45,
|
||||
56,
|
||||
57,
|
||||
62,
|
||||
63,
|
||||
68,
|
||||
69,
|
||||
74,
|
||||
75,
|
||||
76,
|
||||
77,
|
||||
78,
|
||||
79,
|
||||
80,
|
||||
81,
|
||||
92,
|
||||
93,
|
||||
98,
|
||||
99,
|
||||
112,
|
||||
113,
|
||||
128,
|
||||
129,
|
||||
134,
|
||||
135,
|
||||
148,
|
||||
149,
|
||||
160,
|
||||
161,
|
||||
162,
|
||||
163,
|
||||
164,
|
||||
165,
|
||||
166,
|
||||
167,
|
||||
168,
|
||||
169,
|
||||
170,
|
||||
171,
|
||||
172,
|
||||
173,
|
||||
178,
|
||||
179,
|
||||
184,
|
||||
185,
|
||||
196,
|
||||
197,
|
||||
198,
|
||||
199,
|
||||
200,
|
||||
201,
|
||||
202,
|
||||
203,
|
||||
204,
|
||||
205,
|
||||
206,
|
||||
207,
|
||||
208,
|
||||
209,
|
||||
214,
|
||||
215,
|
||||
220,
|
||||
221
|
||||
] : [
|
||||
6,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
1
|
||||
];
|
||||
const inspectOpts = Object.keys(env).filter((key) => /^debug_/i.test(key)).reduce((obj, key) => {
|
||||
const prop = key.slice(6).toLowerCase().replace(/_([a-z])/g, (_, k) => k.toUpperCase());
|
||||
let value = env[key];
|
||||
const lowerCase = typeof value === "string" && value.toLowerCase();
|
||||
if (value === "null") value = null;
|
||||
else if (lowerCase === "yes" || lowerCase === "on" || lowerCase === "true" || lowerCase === "enabled") value = true;
|
||||
else if (lowerCase === "no" || lowerCase === "off" || lowerCase === "false" || lowerCase === "disabled") value = false;
|
||||
else value = Number(value);
|
||||
obj[prop] = value;
|
||||
return obj;
|
||||
}, Object.create(null));
|
||||
/**
|
||||
* Is stdout a TTY? Colored output is enabled when `true`.
|
||||
*/
|
||||
function useColors() {
|
||||
return "colors" in inspectOpts ? Boolean(inspectOpts.colors) : isatty(process.stderr.fd);
|
||||
}
|
||||
function getDate() {
|
||||
if (inspectOpts.hideDate) return "";
|
||||
return `${(/* @__PURE__ */ new Date()).toISOString()} `;
|
||||
}
|
||||
/**
|
||||
* Adds ANSI color escape codes if enabled.
|
||||
*/
|
||||
function formatArgs(diff, args) {
|
||||
const { namespace: name, useColors } = this;
|
||||
if (useColors) {
|
||||
const c = this.color;
|
||||
const colorCode = `\u001B[3${c < 8 ? c : `8;5;${c}`}`;
|
||||
const prefix = ` ${colorCode};1m${name} \u001B[0m`;
|
||||
args[0] = prefix + args[0].split("\n").join(`\n${prefix}`);
|
||||
args.push(`${colorCode}m+${this.humanize(diff)}\u001B[0m`);
|
||||
} else args[0] = `${getDate()}${name} ${args[0]}`;
|
||||
}
|
||||
function log(...args) {
|
||||
process.stderr.write(`${formatWithOptions(this.inspectOpts, ...args)}\n`);
|
||||
}
|
||||
const defaultOptions = {
|
||||
useColors: useColors(),
|
||||
formatArgs,
|
||||
formatters: {
|
||||
/**
|
||||
* Map %o to `util.inspect()`, all on a single line.
|
||||
*/
|
||||
o(v) {
|
||||
this.inspectOpts.colors = this.useColors;
|
||||
return inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
|
||||
},
|
||||
/**
|
||||
* Map %O to `util.inspect()`, allowing multiple lines if needed.
|
||||
*/
|
||||
O(v) {
|
||||
this.inspectOpts.colors = this.useColors;
|
||||
return inspect(v, this.inspectOpts);
|
||||
}
|
||||
},
|
||||
inspectOpts,
|
||||
log,
|
||||
humanize
|
||||
};
|
||||
function createDebug(namespace, options) {
|
||||
var _ref;
|
||||
const color = (_ref = options && options.color) !== null && _ref !== void 0 ? _ref : selectColor(colors, namespace);
|
||||
return createDebug$1(namespace, Object.assign(defaultOptions, { color }, options));
|
||||
}
|
||||
function save(namespaces) {
|
||||
if (namespaces) env.DEBUG = namespaces;
|
||||
else delete env.DEBUG;
|
||||
}
|
||||
/**
|
||||
* Enables a debug mode by namespaces. This can include modes
|
||||
* separated by a colon and wildcards.
|
||||
*/
|
||||
function enable(namespaces) {
|
||||
save(namespaces);
|
||||
enable$1(namespaces);
|
||||
}
|
||||
enable$1(env.DEBUG || "");
|
||||
//#endregion
|
||||
export { createDebug, disable, enable, enabled, namespaces };
|
||||
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* @fileoverview Disallow Labeled Statements
|
||||
* @author Nicholas C. Zakas
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "suggestion",
|
||||
|
||||
defaultOptions: [
|
||||
{
|
||||
allowLoop: false,
|
||||
allowSwitch: false,
|
||||
},
|
||||
],
|
||||
|
||||
docs: {
|
||||
description: "Disallow labeled statements",
|
||||
recommended: false,
|
||||
frozen: true,
|
||||
url: "https://eslint.org/docs/latest/rules/no-labels",
|
||||
},
|
||||
|
||||
schema: [
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
allowLoop: {
|
||||
type: "boolean",
|
||||
},
|
||||
allowSwitch: {
|
||||
type: "boolean",
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
|
||||
messages: {
|
||||
unexpectedLabel: "Unexpected labeled statement.",
|
||||
unexpectedLabelInBreak: "Unexpected label in break statement.",
|
||||
unexpectedLabelInContinue:
|
||||
"Unexpected label in continue statement.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const [{ allowLoop, allowSwitch }] = context.options;
|
||||
let scopeInfo = null;
|
||||
|
||||
/**
|
||||
* Gets the kind of a given node.
|
||||
* @param {ASTNode} node A node to get.
|
||||
* @returns {string} The kind of the node.
|
||||
*/
|
||||
function getBodyKind(node) {
|
||||
if (astUtils.isLoop(node)) {
|
||||
return "loop";
|
||||
}
|
||||
if (node.type === "SwitchStatement") {
|
||||
return "switch";
|
||||
}
|
||||
return "other";
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the label of a given kind is allowed or not.
|
||||
* @param {string} kind A kind to check.
|
||||
* @returns {boolean} `true` if the kind is allowed.
|
||||
*/
|
||||
function isAllowed(kind) {
|
||||
switch (kind) {
|
||||
case "loop":
|
||||
return allowLoop;
|
||||
case "switch":
|
||||
return allowSwitch;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a given name is a label of a loop or not.
|
||||
* @param {string} label A name of a label to check.
|
||||
* @returns {boolean} `true` if the name is a label of a loop.
|
||||
*/
|
||||
function getKind(label) {
|
||||
let info = scopeInfo;
|
||||
|
||||
while (info) {
|
||||
if (info.label === label) {
|
||||
return info.kind;
|
||||
}
|
||||
info = info.upper;
|
||||
}
|
||||
|
||||
/* c8 ignore next */
|
||||
return "other";
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Public
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
return {
|
||||
LabeledStatement(node) {
|
||||
scopeInfo = {
|
||||
label: node.label.name,
|
||||
kind: getBodyKind(node.body),
|
||||
upper: scopeInfo,
|
||||
};
|
||||
},
|
||||
|
||||
"LabeledStatement:exit"(node) {
|
||||
if (!isAllowed(scopeInfo.kind)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "unexpectedLabel",
|
||||
});
|
||||
}
|
||||
|
||||
scopeInfo = scopeInfo.upper;
|
||||
},
|
||||
|
||||
BreakStatement(node) {
|
||||
if (node.label && !isAllowed(getKind(node.label.name))) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "unexpectedLabelInBreak",
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
ContinueStatement(node) {
|
||||
if (node.label && !isAllowed(getKind(node.label.name))) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "unexpectedLabelInContinue",
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,85 @@
|
||||
'use strict';
|
||||
|
||||
const {none, final, isFinal, getFinalValue, many, isMany, getManyValues} = require('../defs');
|
||||
|
||||
const next = async (value, fns, index, push) => {
|
||||
for (let i = index; i <= fns.length; ++i) {
|
||||
if (value && typeof value.then == 'function') {
|
||||
// thenable
|
||||
value = await value;
|
||||
}
|
||||
if (value === none) break;
|
||||
if (isFinal(value)) {
|
||||
const val = getFinalValue(value);
|
||||
val !== none && push(val);
|
||||
break;
|
||||
}
|
||||
if (isMany(value)) {
|
||||
const values = getManyValues(value);
|
||||
if (i == fns.length) {
|
||||
values.forEach(val => push(val));
|
||||
} else {
|
||||
for (let j = 0; j < values.length; ++j) {
|
||||
await next(values[j], fns, i, push);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (value && typeof value.next == 'function') {
|
||||
// generator
|
||||
for (;;) {
|
||||
let data = value.next();
|
||||
if (data && typeof data.then == 'function') {
|
||||
data = await data;
|
||||
}
|
||||
if (data.done) break;
|
||||
if (i == fns.length) {
|
||||
push(data.value);
|
||||
} else {
|
||||
await next(data.value, fns, i, push);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (i == fns.length) {
|
||||
push(value);
|
||||
break;
|
||||
}
|
||||
value = fns[i](value);
|
||||
}
|
||||
};
|
||||
|
||||
const nop = () => {};
|
||||
|
||||
const asFun = (...fns) => {
|
||||
fns = fns.filter(fn => fn);
|
||||
if (!fns.length) return nop;
|
||||
if (Symbol.asyncIterator && fns[0][Symbol.asyncIterator]) {
|
||||
fns[0] = fns[0][Symbol.asyncIterator];
|
||||
} else if (Symbol.iterator && fns[0][Symbol.iterator]) {
|
||||
fns[0] = fns[0][Symbol.iterator];
|
||||
}
|
||||
return async value => {
|
||||
const results = [];
|
||||
await next(value, fns, 0, value => results.push(value));
|
||||
switch (results.length) {
|
||||
case 0:
|
||||
return none;
|
||||
case 1:
|
||||
return results[0];
|
||||
}
|
||||
return many(results);
|
||||
};
|
||||
};
|
||||
|
||||
asFun.next = next;
|
||||
|
||||
asFun.none = none;
|
||||
asFun.final = final;
|
||||
asFun.isFinal = isFinal;
|
||||
asFun.getFinalValue = getFinalValue;
|
||||
asFun.many = many;
|
||||
asFun.isMany = isMany;
|
||||
asFun.getManyValues = getManyValues;
|
||||
|
||||
module.exports = asFun;
|
||||
@@ -0,0 +1,4 @@
|
||||
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"preferNonNullAssertion", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
|
||||
name: string;
|
||||
};
|
||||
export default _default;
|
||||
@@ -0,0 +1,61 @@
|
||||
'use strict';
|
||||
|
||||
var fs = require('fs')
|
||||
, path = require('path')
|
||||
, browserify = require('browserify')
|
||||
, uglify = require('uglify-js');
|
||||
|
||||
var pkg = process.argv[2]
|
||||
, standalone = process.argv[3]
|
||||
, compress = process.argv[4];
|
||||
|
||||
var packageDir = path.join(__dirname, '..');
|
||||
if (pkg != '.') packageDir = path.join(packageDir, 'node_modules', pkg);
|
||||
|
||||
var json = require(path.join(packageDir, 'package.json'));
|
||||
|
||||
var distDir = path.join(__dirname, '..', 'dist');
|
||||
if (!fs.existsSync(distDir)) fs.mkdirSync(distDir);
|
||||
|
||||
var bOpts = {};
|
||||
if (standalone) bOpts.standalone = standalone;
|
||||
|
||||
browserify(bOpts)
|
||||
.require(path.join(packageDir, json.main), {expose: json.name})
|
||||
.bundle(function (err, buf) {
|
||||
if (err) {
|
||||
console.error('browserify error:', err);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
var outputFile = path.join(distDir, json.name);
|
||||
var uglifyOpts = {
|
||||
warnings: true,
|
||||
compress: {},
|
||||
output: {
|
||||
preamble: '/* ' + json.name + ' ' + json.version + ': ' + json.description + ' */'
|
||||
}
|
||||
};
|
||||
if (compress) {
|
||||
var compressOpts = compress.split(',');
|
||||
for (var i=0, il = compressOpts.length; i<il; ++i) {
|
||||
var pair = compressOpts[i].split('=');
|
||||
uglifyOpts.compress[pair[0]] = pair.length < 1 || pair[1] != 'false';
|
||||
}
|
||||
}
|
||||
if (standalone) {
|
||||
uglifyOpts.sourceMap = {
|
||||
filename: json.name + '.min.js',
|
||||
url: json.name + '.min.js.map'
|
||||
};
|
||||
}
|
||||
|
||||
var result = uglify.minify(buf.toString(), uglifyOpts);
|
||||
fs.writeFileSync(outputFile + '.min.js', result.code);
|
||||
if (result.map) fs.writeFileSync(outputFile + '.min.js.map', result.map);
|
||||
if (standalone) fs.writeFileSync(outputFile + '.bundle.js', buf);
|
||||
if (result.warnings) {
|
||||
for (var j=0, jl = result.warnings.length; j<jl; ++j)
|
||||
console.warn('UglifyJS warning:', result.warnings[j]);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
|
||||
function normalizeWindowsPath(input = "") {
|
||||
if (!input) {
|
||||
return input;
|
||||
}
|
||||
return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
|
||||
}
|
||||
|
||||
const _UNC_REGEX = /^[/\\]{2}/;
|
||||
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
|
||||
const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
|
||||
const normalize = function(path) {
|
||||
if (path.length === 0) {
|
||||
return ".";
|
||||
}
|
||||
path = normalizeWindowsPath(path);
|
||||
const isUNCPath = path.match(_UNC_REGEX);
|
||||
const isPathAbsolute = isAbsolute(path);
|
||||
const trailingSeparator = path[path.length - 1] === "/";
|
||||
path = normalizeString(path, !isPathAbsolute);
|
||||
if (path.length === 0) {
|
||||
if (isPathAbsolute) {
|
||||
return "/";
|
||||
}
|
||||
return trailingSeparator ? "./" : ".";
|
||||
}
|
||||
if (trailingSeparator) {
|
||||
path += "/";
|
||||
}
|
||||
if (_DRIVE_LETTER_RE.test(path)) {
|
||||
path += "/";
|
||||
}
|
||||
if (isUNCPath) {
|
||||
if (!isPathAbsolute) {
|
||||
return `//./${path}`;
|
||||
}
|
||||
return `//${path}`;
|
||||
}
|
||||
return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
|
||||
};
|
||||
const join = function(...segments) {
|
||||
let path = "";
|
||||
for (const seg of segments) {
|
||||
if (!seg) {
|
||||
continue;
|
||||
}
|
||||
if (path.length > 0) {
|
||||
const pathTrailing = path[path.length - 1] === "/";
|
||||
const segLeading = seg[0] === "/";
|
||||
const both = pathTrailing && segLeading;
|
||||
if (both) {
|
||||
path += seg.slice(1);
|
||||
} else {
|
||||
path += pathTrailing || segLeading ? seg : `/${seg}`;
|
||||
}
|
||||
} else {
|
||||
path += seg;
|
||||
}
|
||||
}
|
||||
return normalize(path);
|
||||
};
|
||||
function cwd() {
|
||||
if (typeof process !== "undefined" && typeof process.cwd === "function") {
|
||||
return process.cwd().replace(/\\/g, "/");
|
||||
}
|
||||
return "/";
|
||||
}
|
||||
const resolve = function(...arguments_) {
|
||||
arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
|
||||
let resolvedPath = "";
|
||||
let resolvedAbsolute = false;
|
||||
for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
|
||||
const path = index >= 0 ? arguments_[index] : cwd();
|
||||
if (!path || path.length === 0) {
|
||||
continue;
|
||||
}
|
||||
resolvedPath = `${path}/${resolvedPath}`;
|
||||
resolvedAbsolute = isAbsolute(path);
|
||||
}
|
||||
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
|
||||
if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
|
||||
return `/${resolvedPath}`;
|
||||
}
|
||||
return resolvedPath.length > 0 ? resolvedPath : ".";
|
||||
};
|
||||
function normalizeString(path, allowAboveRoot) {
|
||||
let res = "";
|
||||
let lastSegmentLength = 0;
|
||||
let lastSlash = -1;
|
||||
let dots = 0;
|
||||
let char = null;
|
||||
for (let index = 0; index <= path.length; ++index) {
|
||||
if (index < path.length) {
|
||||
char = path[index];
|
||||
} else if (char === "/") {
|
||||
break;
|
||||
} else {
|
||||
char = "/";
|
||||
}
|
||||
if (char === "/") {
|
||||
if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) {
|
||||
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
|
||||
if (res.length > 2) {
|
||||
const lastSlashIndex = res.lastIndexOf("/");
|
||||
if (lastSlashIndex === -1) {
|
||||
res = "";
|
||||
lastSegmentLength = 0;
|
||||
} else {
|
||||
res = res.slice(0, lastSlashIndex);
|
||||
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
|
||||
}
|
||||
lastSlash = index;
|
||||
dots = 0;
|
||||
continue;
|
||||
} else if (res.length > 0) {
|
||||
res = "";
|
||||
lastSegmentLength = 0;
|
||||
lastSlash = index;
|
||||
dots = 0;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (allowAboveRoot) {
|
||||
res += res.length > 0 ? "/.." : "..";
|
||||
lastSegmentLength = 2;
|
||||
}
|
||||
} else {
|
||||
if (res.length > 0) {
|
||||
res += `/${path.slice(lastSlash + 1, index)}`;
|
||||
} else {
|
||||
res = path.slice(lastSlash + 1, index);
|
||||
}
|
||||
lastSegmentLength = index - lastSlash - 1;
|
||||
}
|
||||
lastSlash = index;
|
||||
dots = 0;
|
||||
} else if (char === "." && dots !== -1) {
|
||||
++dots;
|
||||
} else {
|
||||
dots = -1;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
const isAbsolute = function(p) {
|
||||
return _IS_ABSOLUTE_RE.test(p);
|
||||
};
|
||||
const dirname = function(p) {
|
||||
const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
|
||||
if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) {
|
||||
segments[0] += "/";
|
||||
}
|
||||
return segments.join("/") || (isAbsolute(p) ? "/" : ".");
|
||||
};
|
||||
|
||||
export { dirname as d, join as j, resolve as r };
|
||||
@@ -0,0 +1,204 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
const ts = __importStar(require("typescript"));
|
||||
const util_1 = require("../util");
|
||||
exports.default = (0, util_1.createRule)({
|
||||
name: 'promise-function-async',
|
||||
meta: {
|
||||
type: 'suggestion',
|
||||
docs: {
|
||||
description: 'Require any function or method that returns a Promise to be marked async',
|
||||
requiresTypeChecking: true,
|
||||
},
|
||||
fixable: 'code',
|
||||
messages: {
|
||||
missingAsync: 'Functions that return promises must be async.',
|
||||
missingAsyncHybridReturn: 'Functions that return promises must be async. Consider adding an explicit return type annotation if the function is intended to return a union of promise and non-promise types.',
|
||||
},
|
||||
schema: [
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
allowAny: {
|
||||
type: 'boolean',
|
||||
description: 'Whether to consider `any` and `unknown` to be Promises.',
|
||||
},
|
||||
allowedPromiseNames: {
|
||||
type: 'array',
|
||||
description: 'Any extra names of classes or interfaces to be considered Promises.',
|
||||
items: {
|
||||
type: 'string',
|
||||
},
|
||||
},
|
||||
checkArrowFunctions: {
|
||||
type: 'boolean',
|
||||
description: 'Whether to check arrow functions.',
|
||||
},
|
||||
checkFunctionDeclarations: {
|
||||
type: 'boolean',
|
||||
description: 'Whether to check standalone function declarations.',
|
||||
},
|
||||
checkFunctionExpressions: {
|
||||
type: 'boolean',
|
||||
description: 'Whether to check inline function expressions',
|
||||
},
|
||||
checkMethodDeclarations: {
|
||||
type: 'boolean',
|
||||
description: 'Whether to check methods on classes and object literals.',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
defaultOptions: [
|
||||
{
|
||||
allowAny: true,
|
||||
allowedPromiseNames: [],
|
||||
checkArrowFunctions: true,
|
||||
checkFunctionDeclarations: true,
|
||||
checkFunctionExpressions: true,
|
||||
checkMethodDeclarations: true,
|
||||
},
|
||||
],
|
||||
create(context, [{ allowAny, allowedPromiseNames, checkArrowFunctions, checkFunctionDeclarations, checkFunctionExpressions, checkMethodDeclarations, },]) {
|
||||
const allAllowedPromiseNames = new Set([
|
||||
'Promise',
|
||||
// https://github.com/typescript-eslint/typescript-eslint/issues/5439
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
...allowedPromiseNames,
|
||||
]);
|
||||
const services = (0, util_1.getParserServices)(context);
|
||||
const checker = services.program.getTypeChecker();
|
||||
function validateNode(node) {
|
||||
if (node.parent.type === utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition) {
|
||||
// Abstract method can't be async
|
||||
return;
|
||||
}
|
||||
if ((node.parent.type === utils_1.AST_NODE_TYPES.Property ||
|
||||
node.parent.type === utils_1.AST_NODE_TYPES.MethodDefinition) &&
|
||||
(node.parent.kind === 'get' || node.parent.kind === 'set')) {
|
||||
// Getters and setters can't be async
|
||||
return;
|
||||
}
|
||||
const signatures = services.getTypeAtLocation(node).getCallSignatures();
|
||||
if (!signatures.length) {
|
||||
return;
|
||||
}
|
||||
const returnTypes = signatures.map(signature => checker.getReturnTypeOfSignature(signature));
|
||||
if (!allowAny &&
|
||||
returnTypes.some(type => (0, util_1.isTypeFlagSet)(type, ts.TypeFlags.Any | ts.TypeFlags.Unknown))) {
|
||||
// Report without auto fixer because the return type is unknown
|
||||
return context.report({
|
||||
loc: (0, util_1.getFunctionHeadLoc)(node, context.sourceCode),
|
||||
node,
|
||||
messageId: 'missingAsync',
|
||||
});
|
||||
}
|
||||
if (
|
||||
// require all potential return types to be promise/any/unknown
|
||||
returnTypes.every(type => (0, util_1.containsAllTypesByName)(type, true, allAllowedPromiseNames,
|
||||
// If no return type is explicitly set, we check if any parts of the return type match a Promise (instead of requiring all to match).
|
||||
node.returnType == null))) {
|
||||
const isHybridReturnType = returnTypes.some(type => type.isUnion() &&
|
||||
!type.types.every(part => (0, util_1.containsAllTypesByName)(part, true, allAllowedPromiseNames)));
|
||||
context.report({
|
||||
loc: (0, util_1.getFunctionHeadLoc)(node, context.sourceCode),
|
||||
node,
|
||||
messageId: isHybridReturnType
|
||||
? 'missingAsyncHybridReturn'
|
||||
: 'missingAsync',
|
||||
fix: fixer => {
|
||||
if (node.parent.type === utils_1.AST_NODE_TYPES.MethodDefinition ||
|
||||
(node.parent.type === utils_1.AST_NODE_TYPES.Property &&
|
||||
node.parent.method)) {
|
||||
// this function is a class method or object function property shorthand
|
||||
const method = node.parent;
|
||||
// the token to put `async` before
|
||||
let keyToken = (0, util_1.nullThrows)(context.sourceCode.getFirstToken(method), util_1.NullThrowsReasons.MissingToken('key token', 'method'));
|
||||
// if there are decorators then skip past them
|
||||
if (method.type === utils_1.AST_NODE_TYPES.MethodDefinition &&
|
||||
method.decorators.length) {
|
||||
const lastDecorator = method.decorators[method.decorators.length - 1];
|
||||
keyToken = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(lastDecorator), util_1.NullThrowsReasons.MissingToken('key token', 'last decorator'));
|
||||
}
|
||||
// if current token is a keyword like `static` or `public`, or the `override` modifier, then skip it
|
||||
while ((keyToken.type === utils_1.AST_TOKEN_TYPES.Keyword ||
|
||||
(keyToken.type === utils_1.AST_TOKEN_TYPES.Identifier &&
|
||||
keyToken.value === 'override')) &&
|
||||
keyToken.range[0] < method.key.range[0]) {
|
||||
keyToken = (0, util_1.nullThrows)(context.sourceCode.getTokenAfter(keyToken), util_1.NullThrowsReasons.MissingToken('token', 'modifier keyword'));
|
||||
}
|
||||
// check if there is a space between key and previous token
|
||||
const insertSpace = !context.sourceCode.isSpaceBetween((0, util_1.nullThrows)(context.sourceCode.getTokenBefore(keyToken), util_1.NullThrowsReasons.MissingToken('token', 'keyword')), keyToken);
|
||||
let code = 'async ';
|
||||
if (insertSpace) {
|
||||
code = ` ${code}`;
|
||||
}
|
||||
return fixer.insertTextBefore(keyToken, code);
|
||||
}
|
||||
return fixer.insertTextBefore(node, 'async ');
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
return {
|
||||
...(checkArrowFunctions && {
|
||||
'ArrowFunctionExpression[async = false]'(node) {
|
||||
validateNode(node);
|
||||
},
|
||||
}),
|
||||
...(checkFunctionDeclarations && {
|
||||
'FunctionDeclaration[async = false]'(node) {
|
||||
validateNode(node);
|
||||
},
|
||||
}),
|
||||
'FunctionExpression[async = false]'(node) {
|
||||
if (node.parent.type === utils_1.AST_NODE_TYPES.MethodDefinition &&
|
||||
node.parent.kind === 'method') {
|
||||
if (checkMethodDeclarations) {
|
||||
validateNode(node);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (checkFunctionExpressions) {
|
||||
validateNode(node);
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.specifierNameMatches = specifierNameMatches;
|
||||
function specifierNameMatches(type, names) {
|
||||
if (typeof names === 'string') {
|
||||
names = [names];
|
||||
}
|
||||
const symbol = type.aliasSymbol ?? type.getSymbol();
|
||||
const candidateNames = symbol
|
||||
? [symbol.escapedName, type.intrinsicName]
|
||||
: [type.intrinsicName];
|
||||
if (names.some(item => candidateNames.includes(item))) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* @fileoverview Rule to flag duplicate arguments
|
||||
* @author Jamund Ferguson
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Types
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @typedef {import("eslint-scope").Definition} Definition */
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: "problem",
|
||||
|
||||
docs: {
|
||||
description:
|
||||
"Disallow duplicate arguments in `function` definitions",
|
||||
recommended: true,
|
||||
url: "https://eslint.org/docs/latest/rules/no-dupe-args",
|
||||
},
|
||||
|
||||
schema: [],
|
||||
|
||||
messages: {
|
||||
unexpected: "Duplicate param '{{name}}'.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const sourceCode = context.sourceCode;
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Checks whether or not a given definition is a parameter's.
|
||||
* @param {Definition} def A definition to check.
|
||||
* @returns {boolean} `true` if the definition is a parameter's.
|
||||
*/
|
||||
function isParameter(def) {
|
||||
return def.type === "Parameter";
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a given node has duplicate parameters.
|
||||
* @param {ASTNode} node The node to check.
|
||||
* @returns {void}
|
||||
* @private
|
||||
*/
|
||||
function checkParams(node) {
|
||||
const variables = sourceCode.getDeclaredVariables(node);
|
||||
|
||||
for (let i = 0; i < variables.length; ++i) {
|
||||
const variable = variables[i];
|
||||
|
||||
// Checks and reports duplications.
|
||||
const defs = variable.defs.filter(isParameter);
|
||||
const loc = {
|
||||
start: astUtils.getOpeningParenOfParams(node, sourceCode)
|
||||
.loc.start,
|
||||
end: sourceCode.getTokenBefore(node.body).loc.end,
|
||||
};
|
||||
|
||||
if (defs.length >= 2) {
|
||||
context.report({
|
||||
loc,
|
||||
messageId: "unexpected",
|
||||
data: { name: variable.name },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Public API
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
return {
|
||||
FunctionDeclaration: checkParams,
|
||||
FunctionExpression: checkParams,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;GAaG;AACH,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC"}
|
||||
@@ -0,0 +1,18 @@
|
||||
"use strict";
|
||||
|
||||
var _type_of = require("./_type_of.cjs");
|
||||
|
||||
function _to_primitive(input, hint) {
|
||||
if (_type_of._(input) !== "object" || input === null) return input;
|
||||
|
||||
var prim = input[Symbol.toPrimitive];
|
||||
|
||||
if (prim !== undefined) {
|
||||
var res = prim.call(input, hint || "default");
|
||||
if (_type_of._(res) !== "object") return res;
|
||||
throw new TypeError("@@toPrimitive must return a primitive value.");
|
||||
}
|
||||
|
||||
return (hint === "string" ? String : Number)(input);
|
||||
}
|
||||
exports._ = _to_primitive;
|
||||
@@ -0,0 +1,2 @@
|
||||
export type VisitorKeys = Record<string, readonly string[] | undefined>;
|
||||
export declare const visitorKeys: VisitorKeys;
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,6 @@
|
||||
'use strict'
|
||||
|
||||
module.exports = require('neostandard')({
|
||||
ignores: require('neostandard').resolveIgnoresFromGitignore(),
|
||||
ts: true
|
||||
})
|
||||
@@ -0,0 +1,110 @@
|
||||
import * as util from "../core/util.js";
|
||||
const error = () => {
|
||||
const Sizable = {
|
||||
string: { unit: "belgi", verb: "bo‘lishi kerak" },
|
||||
file: { unit: "bayt", verb: "bo‘lishi kerak" },
|
||||
array: { unit: "element", verb: "bo‘lishi kerak" },
|
||||
set: { unit: "element", verb: "bo‘lishi kerak" },
|
||||
map: { unit: "yozuv", verb: "bo‘lishi kerak" },
|
||||
};
|
||||
function getSizing(origin) {
|
||||
return Sizable[origin] ?? null;
|
||||
}
|
||||
const FormatDictionary = {
|
||||
regex: "kirish",
|
||||
email: "elektron pochta manzili",
|
||||
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 sana va vaqti",
|
||||
date: "ISO sana",
|
||||
time: "ISO vaqt",
|
||||
duration: "ISO davomiylik",
|
||||
ipv4: "IPv4 manzil",
|
||||
ipv6: "IPv6 manzil",
|
||||
mac: "MAC manzil",
|
||||
cidrv4: "IPv4 diapazon",
|
||||
cidrv6: "IPv6 diapazon",
|
||||
base64: "base64 kodlangan satr",
|
||||
base64url: "base64url kodlangan satr",
|
||||
json_string: "JSON satr",
|
||||
e164: "E.164 raqam",
|
||||
jwt: "JWT",
|
||||
template_literal: "kirish",
|
||||
};
|
||||
const TypeDictionary = {
|
||||
nan: "NaN",
|
||||
number: "raqam",
|
||||
array: "massiv",
|
||||
};
|
||||
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 `Noto‘g‘ri kirish: kutilgan instanceof ${issue.expected}, qabul qilingan ${received}`;
|
||||
}
|
||||
return `Noto‘g‘ri kirish: kutilgan ${expected}, qabul qilingan ${received}`;
|
||||
}
|
||||
case "invalid_value":
|
||||
if (issue.values.length === 1)
|
||||
return `Noto‘g‘ri kirish: kutilgan ${util.stringifyPrimitive(issue.values[0])}`;
|
||||
return `Noto‘g‘ri variant: quyidagilardan biri kutilgan ${util.joinValues(issue.values, "|")}`;
|
||||
case "too_big": {
|
||||
const adj = issue.inclusive ? "<=" : "<";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing)
|
||||
return `Juda katta: kutilgan ${issue.origin ?? "qiymat"} ${adj}${issue.maximum.toString()} ${sizing.unit} ${sizing.verb}`;
|
||||
return `Juda katta: kutilgan ${issue.origin ?? "qiymat"} ${adj}${issue.maximum.toString()}`;
|
||||
}
|
||||
case "too_small": {
|
||||
const adj = issue.inclusive ? ">=" : ">";
|
||||
const sizing = getSizing(issue.origin);
|
||||
if (sizing) {
|
||||
return `Juda kichik: kutilgan ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
|
||||
}
|
||||
return `Juda kichik: kutilgan ${issue.origin} ${adj}${issue.minimum.toString()}`;
|
||||
}
|
||||
case "invalid_format": {
|
||||
const _issue = issue;
|
||||
if (_issue.format === "starts_with")
|
||||
return `Noto‘g‘ri satr: "${_issue.prefix}" bilan boshlanishi kerak`;
|
||||
if (_issue.format === "ends_with")
|
||||
return `Noto‘g‘ri satr: "${_issue.suffix}" bilan tugashi kerak`;
|
||||
if (_issue.format === "includes")
|
||||
return `Noto‘g‘ri satr: "${_issue.includes}" ni o‘z ichiga olishi kerak`;
|
||||
if (_issue.format === "regex")
|
||||
return `Noto‘g‘ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`;
|
||||
return `Noto‘g‘ri ${FormatDictionary[_issue.format] ?? issue.format}`;
|
||||
}
|
||||
case "not_multiple_of":
|
||||
return `Noto‘g‘ri raqam: ${issue.divisor} ning karralisi bo‘lishi kerak`;
|
||||
case "unrecognized_keys":
|
||||
return `Noma’lum kalit${issue.keys.length > 1 ? "lar" : ""}: ${util.joinValues(issue.keys, ", ")}`;
|
||||
case "invalid_key":
|
||||
return `${issue.origin} dagi kalit noto‘g‘ri`;
|
||||
case "invalid_union":
|
||||
return "Noto‘g‘ri kirish";
|
||||
case "invalid_element":
|
||||
return `${issue.origin} da noto‘g‘ri qiymat`;
|
||||
default:
|
||||
return `Noto‘g‘ri kirish`;
|
||||
}
|
||||
};
|
||||
};
|
||||
export default function () {
|
||||
return {
|
||||
localeError: error(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# @vitest/spy
|
||||
|
||||
[](https://npmx.dev/package/@vitest/spy)
|
||||
|
||||
Lightweight Jest-compatible mocking implementation.
|
||||
|
||||
[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/spy) | [Documentation](https://vitest.dev/api/mock)
|
||||
@@ -0,0 +1 @@
|
||||
"use strict";var i=Object.defineProperty;var a=(r,t)=>i(r,"name",{value:t,configurable:!0});var n=require("node:repl"),u=require("esbuild");const f=a(r=>{const{eval:t}=r,c=a(async function(e,l,s,o){try{e=(await u.transform(e,{sourcefile:s,loader:"ts",tsconfigRaw:{compilerOptions:{preserveValueImports:!0}},define:{require:"global.require"}})).code}catch{}return t.call(this,e,l,s,o)},"preEval");r.eval=c},"patchEval"),{start:p}=n;n.start=function(){const r=Reflect.apply(p,this,arguments);return f(r),r};
|
||||
@@ -0,0 +1,52 @@
|
||||
var _typeof = require("./typeof.js")["default"];
|
||||
var setPrototypeOf = require("./setPrototypeOf.js");
|
||||
var inherits = require("./inherits.js");
|
||||
function _wrapRegExp() {
|
||||
module.exports = _wrapRegExp = function _wrapRegExp(e, r) {
|
||||
return new BabelRegExp(e, void 0, r);
|
||||
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
|
||||
var e = RegExp.prototype,
|
||||
r = new WeakMap();
|
||||
function BabelRegExp(e, t, p) {
|
||||
var o = RegExp(e, t);
|
||||
return r.set(o, p || r.get(e)), setPrototypeOf(o, BabelRegExp.prototype);
|
||||
}
|
||||
function buildGroups(e, t) {
|
||||
var p = r.get(t);
|
||||
return Object.keys(p).reduce(function (r, t) {
|
||||
var o = p[t];
|
||||
if ("number" == typeof o) r[t] = e[o];else {
|
||||
for (var i = 0; void 0 === e[o[i]] && i + 1 < o.length;) i++;
|
||||
r[t] = e[o[i]];
|
||||
}
|
||||
return r;
|
||||
}, Object.create(null));
|
||||
}
|
||||
return inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (r) {
|
||||
var t = e.exec.call(this, r);
|
||||
if (t) {
|
||||
t.groups = buildGroups(t, this);
|
||||
var p = t.indices;
|
||||
p && (p.groups = buildGroups(p, this));
|
||||
}
|
||||
return t;
|
||||
}, BabelRegExp.prototype[Symbol.replace] = function (t, p) {
|
||||
if ("string" == typeof p) {
|
||||
var o = r.get(this);
|
||||
return e[Symbol.replace].call(this, t, p.replace(/\$<([^>]+)(>|$)/g, function (e, r, t) {
|
||||
if ("" === t) return e;
|
||||
var p = o[r];
|
||||
return Array.isArray(p) ? "$" + p.join("$") : "number" == typeof p ? "$" + p : "";
|
||||
}));
|
||||
}
|
||||
if ("function" == typeof p) {
|
||||
var i = this;
|
||||
return e[Symbol.replace].call(this, t, function () {
|
||||
var e = arguments;
|
||||
return "object" != _typeof(e[e.length - 1]) && (e = [].slice.call(e)).push(buildGroups(e, i)), p.apply(this, e);
|
||||
});
|
||||
}
|
||||
return e[Symbol.replace].call(this, t, p);
|
||||
}, _wrapRegExp.apply(this, arguments);
|
||||
}
|
||||
module.exports = _wrapRegExp, module.exports.__esModule = true, module.exports["default"] = module.exports;
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors
|
||||
|
||||
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,23 @@
|
||||
var test = require('tape');
|
||||
var equal = require('../');
|
||||
|
||||
test('equal', function (t) {
|
||||
t.ok(equal(
|
||||
{ a : [ 2, 3 ], b : [ 4 ] },
|
||||
{ a : [ 2, 3 ], b : [ 4 ] }
|
||||
));
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('not equal', function (t) {
|
||||
t.notOk(equal(
|
||||
{ x : 5, y : [6] },
|
||||
{ x : 5, y : 6 }
|
||||
));
|
||||
t.end();
|
||||
});
|
||||
|
||||
test('nested nulls', function (t) {
|
||||
t.ok(equal([ null, null, null ], [ null, null, null ]));
|
||||
t.end();
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
export { _ as default } from "../esm/_iterable_to_array.js";
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { FlatConfig } from '@typescript-eslint/utils/ts-eslint';
|
||||
|
||||
import type plugin from './index';
|
||||
|
||||
declare const cjsExport: {
|
||||
flatConfigs: {
|
||||
'flat/all': FlatConfig.ConfigArray;
|
||||
'flat/base': FlatConfig.Config;
|
||||
'flat/disable-type-checked': FlatConfig.Config;
|
||||
'flat/eslint-recommended': FlatConfig.Config;
|
||||
'flat/recommended': FlatConfig.ConfigArray;
|
||||
'flat/recommended-type-checked': FlatConfig.ConfigArray;
|
||||
'flat/recommended-type-checked-only': FlatConfig.ConfigArray;
|
||||
'flat/strict': FlatConfig.ConfigArray;
|
||||
'flat/strict-type-checked': FlatConfig.ConfigArray;
|
||||
'flat/strict-type-checked-only': FlatConfig.ConfigArray;
|
||||
'flat/stylistic': FlatConfig.ConfigArray;
|
||||
'flat/stylistic-type-checked': FlatConfig.ConfigArray;
|
||||
'flat/stylistic-type-checked-only': FlatConfig.ConfigArray;
|
||||
};
|
||||
parser: FlatConfig.Parser;
|
||||
plugin: typeof plugin;
|
||||
};
|
||||
|
||||
export = cjsExport;
|
||||
@@ -0,0 +1,143 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const utils_1 = require("@typescript-eslint/utils");
|
||||
const util_1 = require("../util");
|
||||
const noEmptyMessage = (emptyType) => [
|
||||
`${emptyType} allows any non-nullish value, including literals like \`0\` and \`""\`.`,
|
||||
"- If that's what you want, disable this lint rule with an inline comment or configure the '{{ option }}' rule option.",
|
||||
'- If you want a type meaning "any object", you probably want `object` instead.',
|
||||
'- If you want a type meaning "any value", you probably want `unknown` instead.',
|
||||
].join('\n');
|
||||
exports.default = (0, util_1.createRule)({
|
||||
name: 'no-empty-object-type',
|
||||
meta: {
|
||||
type: 'suggestion',
|
||||
docs: {
|
||||
description: 'Disallow accidentally using the "empty object" type',
|
||||
recommended: 'recommended',
|
||||
},
|
||||
hasSuggestions: true,
|
||||
messages: {
|
||||
noEmptyInterface: noEmptyMessage('An empty interface declaration'),
|
||||
noEmptyInterfaceWithSuper: 'An interface declaring no members is equivalent to its supertype.',
|
||||
noEmptyObject: noEmptyMessage('The `{}` ("empty object") type'),
|
||||
replaceEmptyInterface: 'Replace empty interface with `{{replacement}}`.',
|
||||
replaceEmptyInterfaceWithSuper: 'Replace empty interface with a type alias.',
|
||||
replaceEmptyObjectType: 'Replace `{}` with `{{replacement}}`.',
|
||||
},
|
||||
schema: [
|
||||
{
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
allowInterfaces: {
|
||||
type: 'string',
|
||||
description: 'Whether to allow empty interfaces.',
|
||||
enum: ['always', 'never', 'with-single-extends'],
|
||||
},
|
||||
allowObjectTypes: {
|
||||
type: 'string',
|
||||
description: 'Whether to allow empty object type literals.',
|
||||
enum: ['always', 'never'],
|
||||
},
|
||||
allowWithName: {
|
||||
type: 'string',
|
||||
description: 'A stringified regular expression to allow interfaces and object type aliases with the configured name.',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
defaultOptions: [
|
||||
{
|
||||
allowInterfaces: 'never',
|
||||
allowObjectTypes: 'never',
|
||||
},
|
||||
],
|
||||
create(context, [{ allowInterfaces, allowObjectTypes, allowWithName }]) {
|
||||
const allowWithNameTester = allowWithName
|
||||
? new RegExp(allowWithName, 'u')
|
||||
: undefined;
|
||||
return {
|
||||
...(allowInterfaces !== 'always' && {
|
||||
TSInterfaceDeclaration(node) {
|
||||
if (allowWithNameTester?.test(node.id.name)) {
|
||||
return;
|
||||
}
|
||||
const extend = node.extends;
|
||||
if (node.body.body.length !== 0 ||
|
||||
(extend.length === 1 &&
|
||||
allowInterfaces === 'with-single-extends') ||
|
||||
extend.length > 1) {
|
||||
return;
|
||||
}
|
||||
const scope = context.sourceCode.getScope(node);
|
||||
const mergedWithClassDeclaration = scope.set
|
||||
.get(node.id.name)
|
||||
?.defs.some(def => def.node.type === utils_1.AST_NODE_TYPES.ClassDeclaration);
|
||||
if (extend.length === 0) {
|
||||
context.report({
|
||||
node: node.id,
|
||||
messageId: 'noEmptyInterface',
|
||||
data: { option: 'allowInterfaces' },
|
||||
...(!mergedWithClassDeclaration && {
|
||||
suggest: ['object', 'unknown'].map(replacement => ({
|
||||
messageId: 'replaceEmptyInterface',
|
||||
data: { replacement },
|
||||
fix(fixer) {
|
||||
const id = context.sourceCode.getText(node.id);
|
||||
const typeParam = node.typeParameters
|
||||
? context.sourceCode.getText(node.typeParameters)
|
||||
: '';
|
||||
return fixer.replaceText(node, `type ${id}${typeParam} = ${replacement}`);
|
||||
},
|
||||
})),
|
||||
}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
context.report({
|
||||
node: node.id,
|
||||
messageId: 'noEmptyInterfaceWithSuper',
|
||||
...(!mergedWithClassDeclaration && {
|
||||
suggest: [
|
||||
{
|
||||
messageId: 'replaceEmptyInterfaceWithSuper',
|
||||
fix(fixer) {
|
||||
const extended = context.sourceCode.getText(extend[0]);
|
||||
const id = context.sourceCode.getText(node.id);
|
||||
const typeParam = node.typeParameters
|
||||
? context.sourceCode.getText(node.typeParameters)
|
||||
: '';
|
||||
return fixer.replaceText(node, `type ${id}${typeParam} = ${extended}`);
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
},
|
||||
}),
|
||||
...(allowObjectTypes !== 'always' && {
|
||||
TSTypeLiteral(node) {
|
||||
if (node.members.length ||
|
||||
node.parent.type === utils_1.AST_NODE_TYPES.TSIntersectionType ||
|
||||
(allowWithNameTester &&
|
||||
node.parent.type === utils_1.AST_NODE_TYPES.TSTypeAliasDeclaration &&
|
||||
allowWithNameTester.test(node.parent.id.name))) {
|
||||
return;
|
||||
}
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'noEmptyObject',
|
||||
data: { option: 'allowObjectTypes' },
|
||||
suggest: ['object', 'unknown'].map(replacement => ({
|
||||
messageId: 'replaceEmptyObjectType',
|
||||
data: { replacement },
|
||||
fix: (fixer) => fixer.replaceText(node, replacement),
|
||||
})),
|
||||
});
|
||||
},
|
||||
}),
|
||||
};
|
||||
},
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user