[backend] fix: 修复异常处理和类型转换问题

This commit is contained in:
xsl
2026-01-26 11:53:40 +08:00
parent 7ccc2a6ac6
commit 83e05bf85f
28639 changed files with 2506458 additions and 93 deletions
+37
View File
@@ -0,0 +1,37 @@
# @eslint-community/eslint-utils
[![npm version](https://img.shields.io/npm/v/@eslint-community/eslint-utils.svg)](https://www.npmjs.com/package/@eslint-community/eslint-utils)
[![Downloads/month](https://img.shields.io/npm/dm/@eslint-community/eslint-utils.svg)](http://www.npmtrends.com/@eslint-community/eslint-utils)
[![Build Status](https://github.com/eslint-community/eslint-utils/workflows/CI/badge.svg)](https://github.com/eslint-community/eslint-utils/actions)
[![Coverage Status](https://codecov.io/gh/eslint-community/eslint-utils/branch/main/graph/badge.svg)](https://codecov.io/gh/eslint-community/eslint-utils)
## 🏁 Goal
This package provides utility functions and classes for make ESLint custom rules.
For examples:
- [`getStaticValue`](https://eslint-community.github.io/eslint-utils/api/ast-utils.html#getstaticvalue) evaluates static value on AST.
- [`ReferenceTracker`](https://eslint-community.github.io/eslint-utils/api/scope-utils.html#referencetracker-class) checks the members of modules/globals as handling assignments and destructuring.
## 📖 Usage
See [documentation](https://eslint-community.github.io/eslint-utils).
## 📰 Changelog
See [releases](https://github.com/eslint-community/eslint-utils/releases).
## ❤️ Contributing
Welcome contributing!
Please use GitHub's Issues/PRs.
### Development Tools
- `npm run test-coverage` runs tests and measures coverage.
- `npm run clean` removes the coverage result of `npm run test-coverage` command.
- `npm run coverage` shows the coverage result of the last `npm run test-coverage` command.
- `npm run lint` runs ESLint.
- `npm run watch` runs tests on each file change.
+217
View File
@@ -0,0 +1,217 @@
import * as eslint from 'eslint';
import { Rule, AST } from 'eslint';
import * as estree from 'estree';
declare const READ: unique symbol;
declare const CALL: unique symbol;
declare const CONSTRUCT: unique symbol;
declare const ESM: unique symbol;
declare class ReferenceTracker {
constructor(globalScope: Scope$2, options?: {
mode?: "legacy" | "strict" | undefined;
globalObjectNames?: string[] | undefined;
} | undefined);
private variableStack;
private globalScope;
private mode;
private globalObjectNames;
iterateGlobalReferences<T>(traceMap: TraceMap$2<T>): IterableIterator<TrackedReferences$2<T>>;
iterateCjsReferences<T_1>(traceMap: TraceMap$2<T_1>): IterableIterator<TrackedReferences$2<T_1>>;
iterateEsmReferences<T_2>(traceMap: TraceMap$2<T_2>): IterableIterator<TrackedReferences$2<T_2>>;
iteratePropertyReferences<T_3>(node: Expression, traceMap: TraceMap$2<T_3>): IterableIterator<TrackedReferences$2<T_3>>;
private _iterateVariableReferences;
private _iteratePropertyReferences;
private _iterateLhsReferences;
private _iterateImportReferences;
}
declare namespace ReferenceTracker {
export { READ };
export { CALL };
export { CONSTRUCT };
export { ESM };
}
type Scope$2 = eslint.Scope.Scope;
type Expression = estree.Expression;
type TraceMap$2<T> = TraceMap$1<T>;
type TrackedReferences$2<T> = TrackedReferences$1<T>;
type StaticValue$2 = StaticValueProvided$1 | StaticValueOptional$1;
type StaticValueProvided$1 = {
optional?: undefined;
value: unknown;
};
type StaticValueOptional$1 = {
optional?: true;
value: undefined;
};
type ReferenceTrackerOptions$1 = {
globalObjectNames?: string[];
mode?: "legacy" | "strict";
};
type TraceMap$1<T = unknown> = {
[i: string]: TraceMapObject<T>;
};
type TraceMapObject<T> = {
[i: string]: TraceMapObject<T>;
[CALL]?: T;
[CONSTRUCT]?: T;
[READ]?: T;
[ESM]?: boolean;
};
type TrackedReferences$1<T> = {
info: T;
node: Rule.Node;
path: string[];
type: typeof CALL | typeof CONSTRUCT | typeof READ;
};
type HasSideEffectOptions$1 = {
considerGetters?: boolean;
considerImplicitTypeConversion?: boolean;
};
type PunctuatorToken<Value extends string> = AST.Token & {
type: "Punctuator";
value: Value;
};
type ArrowToken$1 = PunctuatorToken<"=>">;
type CommaToken$1 = PunctuatorToken<",">;
type SemicolonToken$1 = PunctuatorToken<";">;
type ColonToken$1 = PunctuatorToken<":">;
type OpeningParenToken$1 = PunctuatorToken<"(">;
type ClosingParenToken$1 = PunctuatorToken<")">;
type OpeningBracketToken$1 = PunctuatorToken<"[">;
type ClosingBracketToken$1 = PunctuatorToken<"]">;
type OpeningBraceToken$1 = PunctuatorToken<"{">;
type ClosingBraceToken$1 = PunctuatorToken<"}">;
declare function findVariable(initialScope: Scope$1, nameOrNode: string | Identifier): Variable | null;
type Scope$1 = eslint.Scope.Scope;
type Variable = eslint.Scope.Variable;
type Identifier = estree.Identifier;
declare function getFunctionHeadLocation(node: FunctionNode$1, sourceCode: SourceCode$2): SourceLocation | null;
type SourceCode$2 = eslint.SourceCode;
type FunctionNode$1 = estree.Function;
type SourceLocation = estree.SourceLocation;
declare function getFunctionNameWithKind(node: FunctionNode, sourceCode?: eslint.SourceCode | undefined): string;
type FunctionNode = estree.Function;
declare function getInnermostScope(initialScope: Scope, node: Node$4): Scope;
type Scope = eslint.Scope.Scope;
type Node$4 = estree.Node;
declare function getPropertyName(node: MemberExpression | MethodDefinition | Property | PropertyDefinition, initialScope?: eslint.Scope.Scope | undefined): string | null | undefined;
type MemberExpression = estree.MemberExpression;
type MethodDefinition = estree.MethodDefinition;
type Property = estree.Property;
type PropertyDefinition = estree.PropertyDefinition;
declare function getStaticValue(node: Node$3, initialScope?: eslint.Scope.Scope | null | undefined): StaticValue$1 | null;
type StaticValue$1 = StaticValue$2;
type Node$3 = estree.Node;
declare function getStringIfConstant(node: Node$2, initialScope?: eslint.Scope.Scope | null | undefined): string | null;
type Node$2 = estree.Node;
declare function hasSideEffect(node: Node$1, sourceCode: SourceCode$1, options?: HasSideEffectOptions$1 | undefined): boolean;
type Node$1 = estree.Node;
type SourceCode$1 = eslint.SourceCode;
declare function isArrowToken(token: CommentOrToken): token is ArrowToken$1;
declare function isCommaToken(token: CommentOrToken): token is CommaToken$1;
declare function isSemicolonToken(token: CommentOrToken): token is SemicolonToken$1;
declare function isColonToken(token: CommentOrToken): token is ColonToken$1;
declare function isOpeningParenToken(token: CommentOrToken): token is OpeningParenToken$1;
declare function isClosingParenToken(token: CommentOrToken): token is ClosingParenToken$1;
declare function isOpeningBracketToken(token: CommentOrToken): token is OpeningBracketToken$1;
declare function isClosingBracketToken(token: CommentOrToken): token is ClosingBracketToken$1;
declare function isOpeningBraceToken(token: CommentOrToken): token is OpeningBraceToken$1;
declare function isClosingBraceToken(token: CommentOrToken): token is ClosingBraceToken$1;
declare function isCommentToken(token: CommentOrToken): token is estree.Comment;
declare function isNotArrowToken(arg0: CommentOrToken): boolean;
declare function isNotCommaToken(arg0: CommentOrToken): boolean;
declare function isNotSemicolonToken(arg0: CommentOrToken): boolean;
declare function isNotColonToken(arg0: CommentOrToken): boolean;
declare function isNotOpeningParenToken(arg0: CommentOrToken): boolean;
declare function isNotClosingParenToken(arg0: CommentOrToken): boolean;
declare function isNotOpeningBracketToken(arg0: CommentOrToken): boolean;
declare function isNotClosingBracketToken(arg0: CommentOrToken): boolean;
declare function isNotOpeningBraceToken(arg0: CommentOrToken): boolean;
declare function isNotClosingBraceToken(arg0: CommentOrToken): boolean;
declare function isNotCommentToken(arg0: CommentOrToken): boolean;
type Token = eslint.AST.Token;
type Comment = estree.Comment;
type CommentOrToken = Comment | Token;
declare function isParenthesized(timesOrNode: Node | number, nodeOrSourceCode: Node | SourceCode, optionalSourceCode?: eslint.SourceCode | undefined): boolean;
type Node = estree.Node;
type SourceCode = eslint.SourceCode;
declare class PatternMatcher {
constructor(pattern: RegExp, options?: {
escaped?: boolean | undefined;
} | undefined);
execAll(str: string): IterableIterator<RegExpExecArray>;
test(str: string): boolean;
[Symbol.replace](str: string, replacer: string | ((...strs: string[]) => string)): string;
}
declare namespace _default {
export { CALL };
export { CONSTRUCT };
export { ESM };
export { findVariable };
export { getFunctionHeadLocation };
export { getFunctionNameWithKind };
export { getInnermostScope };
export { getPropertyName };
export { getStaticValue };
export { getStringIfConstant };
export { hasSideEffect };
export { isArrowToken };
export { isClosingBraceToken };
export { isClosingBracketToken };
export { isClosingParenToken };
export { isColonToken };
export { isCommaToken };
export { isCommentToken };
export { isNotArrowToken };
export { isNotClosingBraceToken };
export { isNotClosingBracketToken };
export { isNotClosingParenToken };
export { isNotColonToken };
export { isNotCommaToken };
export { isNotCommentToken };
export { isNotOpeningBraceToken };
export { isNotOpeningBracketToken };
export { isNotOpeningParenToken };
export { isNotSemicolonToken };
export { isOpeningBraceToken };
export { isOpeningBracketToken };
export { isOpeningParenToken };
export { isParenthesized };
export { isSemicolonToken };
export { PatternMatcher };
export { READ };
export { ReferenceTracker };
}
type StaticValue = StaticValue$2;
type StaticValueOptional = StaticValueOptional$1;
type StaticValueProvided = StaticValueProvided$1;
type ReferenceTrackerOptions = ReferenceTrackerOptions$1;
type TraceMap<T> = TraceMap$1<T>;
type TrackedReferences<T> = TrackedReferences$1<T>;
type HasSideEffectOptions = HasSideEffectOptions$1;
type ArrowToken = ArrowToken$1;
type CommaToken = CommaToken$1;
type SemicolonToken = SemicolonToken$1;
type ColonToken = ColonToken$1;
type OpeningParenToken = OpeningParenToken$1;
type ClosingParenToken = ClosingParenToken$1;
type OpeningBracketToken = OpeningBracketToken$1;
type ClosingBracketToken = ClosingBracketToken$1;
type OpeningBraceToken = OpeningBraceToken$1;
type ClosingBraceToken = ClosingBraceToken$1;
export { ArrowToken, CALL, CONSTRUCT, ClosingBraceToken, ClosingBracketToken, ClosingParenToken, ColonToken, CommaToken, ESM, HasSideEffectOptions, OpeningBraceToken, OpeningBracketToken, OpeningParenToken, PatternMatcher, READ, ReferenceTracker, ReferenceTrackerOptions, SemicolonToken, StaticValue, StaticValueOptional, StaticValueProvided, TraceMap, TrackedReferences, _default as default, findVariable, getFunctionHeadLocation, getFunctionNameWithKind, getInnermostScope, getPropertyName, getStaticValue, getStringIfConstant, hasSideEffect, isArrowToken, isClosingBraceToken, isClosingBracketToken, isClosingParenToken, isColonToken, isCommaToken, isCommentToken, isNotArrowToken, isNotClosingBraceToken, isNotClosingBracketToken, isNotClosingParenToken, isNotColonToken, isNotCommaToken, isNotCommentToken, isNotOpeningBraceToken, isNotOpeningBracketToken, isNotOpeningParenToken, isNotSemicolonToken, isOpeningBraceToken, isOpeningBracketToken, isOpeningParenToken, isParenthesized, isSemicolonToken };
+217
View File
@@ -0,0 +1,217 @@
import * as eslint from 'eslint';
import { Rule, AST } from 'eslint';
import * as estree from 'estree';
declare const READ: unique symbol;
declare const CALL: unique symbol;
declare const CONSTRUCT: unique symbol;
declare const ESM: unique symbol;
declare class ReferenceTracker {
constructor(globalScope: Scope$2, options?: {
mode?: "legacy" | "strict" | undefined;
globalObjectNames?: string[] | undefined;
} | undefined);
private variableStack;
private globalScope;
private mode;
private globalObjectNames;
iterateGlobalReferences<T>(traceMap: TraceMap$2<T>): IterableIterator<TrackedReferences$2<T>>;
iterateCjsReferences<T_1>(traceMap: TraceMap$2<T_1>): IterableIterator<TrackedReferences$2<T_1>>;
iterateEsmReferences<T_2>(traceMap: TraceMap$2<T_2>): IterableIterator<TrackedReferences$2<T_2>>;
iteratePropertyReferences<T_3>(node: Expression, traceMap: TraceMap$2<T_3>): IterableIterator<TrackedReferences$2<T_3>>;
private _iterateVariableReferences;
private _iteratePropertyReferences;
private _iterateLhsReferences;
private _iterateImportReferences;
}
declare namespace ReferenceTracker {
export { READ };
export { CALL };
export { CONSTRUCT };
export { ESM };
}
type Scope$2 = eslint.Scope.Scope;
type Expression = estree.Expression;
type TraceMap$2<T> = TraceMap$1<T>;
type TrackedReferences$2<T> = TrackedReferences$1<T>;
type StaticValue$2 = StaticValueProvided$1 | StaticValueOptional$1;
type StaticValueProvided$1 = {
optional?: undefined;
value: unknown;
};
type StaticValueOptional$1 = {
optional?: true;
value: undefined;
};
type ReferenceTrackerOptions$1 = {
globalObjectNames?: string[];
mode?: "legacy" | "strict";
};
type TraceMap$1<T = unknown> = {
[i: string]: TraceMapObject<T>;
};
type TraceMapObject<T> = {
[i: string]: TraceMapObject<T>;
[CALL]?: T;
[CONSTRUCT]?: T;
[READ]?: T;
[ESM]?: boolean;
};
type TrackedReferences$1<T> = {
info: T;
node: Rule.Node;
path: string[];
type: typeof CALL | typeof CONSTRUCT | typeof READ;
};
type HasSideEffectOptions$1 = {
considerGetters?: boolean;
considerImplicitTypeConversion?: boolean;
};
type PunctuatorToken<Value extends string> = AST.Token & {
type: "Punctuator";
value: Value;
};
type ArrowToken$1 = PunctuatorToken<"=>">;
type CommaToken$1 = PunctuatorToken<",">;
type SemicolonToken$1 = PunctuatorToken<";">;
type ColonToken$1 = PunctuatorToken<":">;
type OpeningParenToken$1 = PunctuatorToken<"(">;
type ClosingParenToken$1 = PunctuatorToken<")">;
type OpeningBracketToken$1 = PunctuatorToken<"[">;
type ClosingBracketToken$1 = PunctuatorToken<"]">;
type OpeningBraceToken$1 = PunctuatorToken<"{">;
type ClosingBraceToken$1 = PunctuatorToken<"}">;
declare function findVariable(initialScope: Scope$1, nameOrNode: string | Identifier): Variable | null;
type Scope$1 = eslint.Scope.Scope;
type Variable = eslint.Scope.Variable;
type Identifier = estree.Identifier;
declare function getFunctionHeadLocation(node: FunctionNode$1, sourceCode: SourceCode$2): SourceLocation | null;
type SourceCode$2 = eslint.SourceCode;
type FunctionNode$1 = estree.Function;
type SourceLocation = estree.SourceLocation;
declare function getFunctionNameWithKind(node: FunctionNode, sourceCode?: eslint.SourceCode | undefined): string;
type FunctionNode = estree.Function;
declare function getInnermostScope(initialScope: Scope, node: Node$4): Scope;
type Scope = eslint.Scope.Scope;
type Node$4 = estree.Node;
declare function getPropertyName(node: MemberExpression | MethodDefinition | Property | PropertyDefinition, initialScope?: eslint.Scope.Scope | undefined): string | null | undefined;
type MemberExpression = estree.MemberExpression;
type MethodDefinition = estree.MethodDefinition;
type Property = estree.Property;
type PropertyDefinition = estree.PropertyDefinition;
declare function getStaticValue(node: Node$3, initialScope?: eslint.Scope.Scope | null | undefined): StaticValue$1 | null;
type StaticValue$1 = StaticValue$2;
type Node$3 = estree.Node;
declare function getStringIfConstant(node: Node$2, initialScope?: eslint.Scope.Scope | null | undefined): string | null;
type Node$2 = estree.Node;
declare function hasSideEffect(node: Node$1, sourceCode: SourceCode$1, options?: HasSideEffectOptions$1 | undefined): boolean;
type Node$1 = estree.Node;
type SourceCode$1 = eslint.SourceCode;
declare function isArrowToken(token: CommentOrToken): token is ArrowToken$1;
declare function isCommaToken(token: CommentOrToken): token is CommaToken$1;
declare function isSemicolonToken(token: CommentOrToken): token is SemicolonToken$1;
declare function isColonToken(token: CommentOrToken): token is ColonToken$1;
declare function isOpeningParenToken(token: CommentOrToken): token is OpeningParenToken$1;
declare function isClosingParenToken(token: CommentOrToken): token is ClosingParenToken$1;
declare function isOpeningBracketToken(token: CommentOrToken): token is OpeningBracketToken$1;
declare function isClosingBracketToken(token: CommentOrToken): token is ClosingBracketToken$1;
declare function isOpeningBraceToken(token: CommentOrToken): token is OpeningBraceToken$1;
declare function isClosingBraceToken(token: CommentOrToken): token is ClosingBraceToken$1;
declare function isCommentToken(token: CommentOrToken): token is estree.Comment;
declare function isNotArrowToken(arg0: CommentOrToken): boolean;
declare function isNotCommaToken(arg0: CommentOrToken): boolean;
declare function isNotSemicolonToken(arg0: CommentOrToken): boolean;
declare function isNotColonToken(arg0: CommentOrToken): boolean;
declare function isNotOpeningParenToken(arg0: CommentOrToken): boolean;
declare function isNotClosingParenToken(arg0: CommentOrToken): boolean;
declare function isNotOpeningBracketToken(arg0: CommentOrToken): boolean;
declare function isNotClosingBracketToken(arg0: CommentOrToken): boolean;
declare function isNotOpeningBraceToken(arg0: CommentOrToken): boolean;
declare function isNotClosingBraceToken(arg0: CommentOrToken): boolean;
declare function isNotCommentToken(arg0: CommentOrToken): boolean;
type Token = eslint.AST.Token;
type Comment = estree.Comment;
type CommentOrToken = Comment | Token;
declare function isParenthesized(timesOrNode: Node | number, nodeOrSourceCode: Node | SourceCode, optionalSourceCode?: eslint.SourceCode | undefined): boolean;
type Node = estree.Node;
type SourceCode = eslint.SourceCode;
declare class PatternMatcher {
constructor(pattern: RegExp, options?: {
escaped?: boolean | undefined;
} | undefined);
execAll(str: string): IterableIterator<RegExpExecArray>;
test(str: string): boolean;
[Symbol.replace](str: string, replacer: string | ((...strs: string[]) => string)): string;
}
declare namespace _default {
export { CALL };
export { CONSTRUCT };
export { ESM };
export { findVariable };
export { getFunctionHeadLocation };
export { getFunctionNameWithKind };
export { getInnermostScope };
export { getPropertyName };
export { getStaticValue };
export { getStringIfConstant };
export { hasSideEffect };
export { isArrowToken };
export { isClosingBraceToken };
export { isClosingBracketToken };
export { isClosingParenToken };
export { isColonToken };
export { isCommaToken };
export { isCommentToken };
export { isNotArrowToken };
export { isNotClosingBraceToken };
export { isNotClosingBracketToken };
export { isNotClosingParenToken };
export { isNotColonToken };
export { isNotCommaToken };
export { isNotCommentToken };
export { isNotOpeningBraceToken };
export { isNotOpeningBracketToken };
export { isNotOpeningParenToken };
export { isNotSemicolonToken };
export { isOpeningBraceToken };
export { isOpeningBracketToken };
export { isOpeningParenToken };
export { isParenthesized };
export { isSemicolonToken };
export { PatternMatcher };
export { READ };
export { ReferenceTracker };
}
type StaticValue = StaticValue$2;
type StaticValueOptional = StaticValueOptional$1;
type StaticValueProvided = StaticValueProvided$1;
type ReferenceTrackerOptions = ReferenceTrackerOptions$1;
type TraceMap<T> = TraceMap$1<T>;
type TrackedReferences<T> = TrackedReferences$1<T>;
type HasSideEffectOptions = HasSideEffectOptions$1;
type ArrowToken = ArrowToken$1;
type CommaToken = CommaToken$1;
type SemicolonToken = SemicolonToken$1;
type ColonToken = ColonToken$1;
type OpeningParenToken = OpeningParenToken$1;
type ClosingParenToken = ClosingParenToken$1;
type OpeningBracketToken = OpeningBracketToken$1;
type ClosingBracketToken = ClosingBracketToken$1;
type OpeningBraceToken = OpeningBraceToken$1;
type ClosingBraceToken = ClosingBraceToken$1;
export { ArrowToken, CALL, CONSTRUCT, ClosingBraceToken, ClosingBracketToken, ClosingParenToken, ColonToken, CommaToken, ESM, HasSideEffectOptions, OpeningBraceToken, OpeningBracketToken, OpeningParenToken, PatternMatcher, READ, ReferenceTracker, ReferenceTrackerOptions, SemicolonToken, StaticValue, StaticValueOptional, StaticValueProvided, TraceMap, TrackedReferences, _default as default, findVariable, getFunctionHeadLocation, getFunctionNameWithKind, getInnermostScope, getPropertyName, getStaticValue, getStringIfConstant, hasSideEffect, isArrowToken, isClosingBraceToken, isClosingBracketToken, isClosingParenToken, isColonToken, isCommaToken, isCommentToken, isNotArrowToken, isNotClosingBraceToken, isNotClosingBracketToken, isNotClosingParenToken, isNotColonToken, isNotCommaToken, isNotCommentToken, isNotOpeningBraceToken, isNotOpeningBracketToken, isNotOpeningParenToken, isNotSemicolonToken, isOpeningBraceToken, isOpeningBracketToken, isOpeningParenToken, isParenthesized, isSemicolonToken };
+737
View File
@@ -1881,3 +1881,740 @@ function replaceS(matcher, str, replacement) {
* @returns {string} The replaced string.
*/
function replaceF(matcher, str, replace) {
const chunks = [];
let index = 0;
for (const match of matcher.execAll(str)) {
chunks.push(str.slice(index, match.index));
chunks.push(
String(
replace(
.../** @type {[string, ...string[]]} */ (
/** @type {string[]} */ (match)
),
match.index,
match.input,
),
),
);
index = match.index + match[0].length;
}
chunks.push(str.slice(index));
return chunks.join("")
}
/**
* The class to find patterns as considering escape sequences.
*/
class PatternMatcher {
/**
* Initialize this matcher.
* @param {RegExp} pattern The pattern to match.
* @param {{escaped?:boolean}} [options] The options.
*/
constructor(pattern, options = {}) {
const { escaped = false } = options;
if (!(pattern instanceof RegExp)) {
throw new TypeError("'pattern' should be a RegExp instance.")
}
if (!pattern.flags.includes("g")) {
throw new Error("'pattern' should contains 'g' flag.")
}
internal.set(this, {
pattern: new RegExp(pattern.source, pattern.flags),
escaped: Boolean(escaped),
});
}
/**
* Find the pattern in a given string.
* @param {string} str The string to find.
* @returns {IterableIterator<RegExpExecArray>} The iterator which iterate the matched information.
*/
*execAll(str) {
const { pattern, escaped } =
/** @type {{pattern:RegExp,escaped:boolean}} */ (internal.get(this));
let match = null;
let lastIndex = 0;
pattern.lastIndex = 0;
while ((match = pattern.exec(str)) != null) {
if (escaped || !isEscaped(str, match.index)) {
lastIndex = pattern.lastIndex;
yield match;
pattern.lastIndex = lastIndex;
}
}
}
/**
* Check whether the pattern is found in a given string.
* @param {string} str The string to check.
* @returns {boolean} `true` if the pattern was found in the string.
*/
test(str) {
const it = this.execAll(str);
const ret = it.next();
return !ret.done
}
/**
* Replace a given string.
* @param {string} str The string to be replaced.
* @param {(string|((...strs:string[])=>string))} replacer The string or function to replace. This is the same as the 2nd argument of `String.prototype.replace`.
* @returns {string} The replaced string.
*/
[Symbol.replace](str, replacer) {
return typeof replacer === "function"
? replaceF(this, String(str), replacer)
: replaceS(this, String(str), String(replacer))
}
}
/** @typedef {import("eslint").Scope.Scope} Scope */
/** @typedef {import("eslint").Scope.Variable} Variable */
/** @typedef {import("eslint").Rule.Node} RuleNode */
/** @typedef {import("estree").Node} Node */
/** @typedef {import("estree").Expression} Expression */
/** @typedef {import("estree").Pattern} Pattern */
/** @typedef {import("estree").Identifier} Identifier */
/** @typedef {import("estree").SimpleCallExpression} CallExpression */
/** @typedef {import("estree").Program} Program */
/** @typedef {import("estree").ImportDeclaration} ImportDeclaration */
/** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclaration */
/** @typedef {import("estree").ExportDefaultDeclaration} ExportDefaultDeclaration */
/** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclaration */
/** @typedef {import("estree").ImportSpecifier} ImportSpecifier */
/** @typedef {import("estree").ImportDefaultSpecifier} ImportDefaultSpecifier */
/** @typedef {import("estree").ImportNamespaceSpecifier} ImportNamespaceSpecifier */
/** @typedef {import("estree").ExportSpecifier} ExportSpecifier */
/** @typedef {import("estree").Property} Property */
/** @typedef {import("estree").AssignmentProperty} AssignmentProperty */
/** @typedef {import("estree").Literal} Literal */
/** @typedef {import("@typescript-eslint/types").TSESTree.Node} TSESTreeNode */
/** @typedef {import("./types.mjs").ReferenceTrackerOptions} ReferenceTrackerOptions */
/**
* @template T
* @typedef {import("./types.mjs").TraceMap<T>} TraceMap
*/
/**
* @template T
* @typedef {import("./types.mjs").TraceMapObject<T>} TraceMapObject
*/
/**
* @template T
* @typedef {import("./types.mjs").TrackedReferences<T>} TrackedReferences
*/
const IMPORT_TYPE = /^(?:Import|Export(?:All|Default|Named))Declaration$/u;
/**
* Check whether a given node is an import node or not.
* @param {Node} node
* @returns {node is ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration&{source: Literal}} `true` if the node is an import node.
*/
function isHasSource(node) {
return (
IMPORT_TYPE.test(node.type) &&
/** @type {ImportDeclaration|ExportAllDeclaration|ExportNamedDeclaration} */ (
node
).source != null
)
}
const has =
/** @type {<T>(traceMap: TraceMap<unknown>, v: T) => v is (string extends T ? string : T)} */ (
Function.call.bind(Object.hasOwnProperty)
);
const READ = Symbol("read");
const CALL = Symbol("call");
const CONSTRUCT = Symbol("construct");
const ESM = Symbol("esm");
const requireCall = { require: { [CALL]: true } };
/**
* Check whether a given variable is modified or not.
* @param {Variable|undefined} variable The variable to check.
* @returns {boolean} `true` if the variable is modified.
*/
function isModifiedGlobal(variable) {
return (
variable == null ||
variable.defs.length !== 0 ||
variable.references.some((r) => r.isWrite())
)
}
/**
* Check if the value of a given node is passed through to the parent syntax as-is.
* For example, `a` and `b` in (`a || b` and `c ? a : b`) are passed through.
* @param {Node} node A node to check.
* @returns {node is RuleNode & {parent: Expression}} `true` if the node is passed through.
*/
function isPassThrough(node) {
const parent = /** @type {TSESTreeNode} */ (node).parent;
if (parent) {
switch (parent.type) {
case "ConditionalExpression":
return parent.consequent === node || parent.alternate === node
case "LogicalExpression":
return true
case "SequenceExpression":
return (
parent.expressions[parent.expressions.length - 1] === node
)
case "ChainExpression":
return true
case "TSAsExpression":
case "TSSatisfiesExpression":
case "TSTypeAssertion":
case "TSNonNullExpression":
case "TSInstantiationExpression":
return true
default:
return false
}
}
return false
}
/**
* The reference tracker.
*/
class ReferenceTracker {
/**
* Initialize this tracker.
* @param {Scope} globalScope The global scope.
* @param {object} [options] The options.
* @param {"legacy"|"strict"} [options.mode="strict"] The mode to determine the ImportDeclaration's behavior for CJS modules.
* @param {string[]} [options.globalObjectNames=["global","globalThis","self","window"]] The variable names for Global Object.
*/
constructor(globalScope, options = {}) {
const {
mode = "strict",
globalObjectNames = ["global", "globalThis", "self", "window"],
} = options;
/** @private @type {Variable[]} */
this.variableStack = [];
/** @private */
this.globalScope = globalScope;
/** @private */
this.mode = mode;
/** @private */
this.globalObjectNames = globalObjectNames.slice(0);
}
/**
* Iterate the references of global variables.
* @template T
* @param {TraceMap<T>} traceMap The trace map.
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
*/
*iterateGlobalReferences(traceMap) {
for (const key of Object.keys(traceMap)) {
const nextTraceMap = traceMap[key];
const path = [key];
const variable = this.globalScope.set.get(key);
if (isModifiedGlobal(variable)) {
continue
}
yield* this._iterateVariableReferences(
/** @type {Variable} */ (variable),
path,
nextTraceMap,
true,
);
}
for (const key of this.globalObjectNames) {
/** @type {string[]} */
const path = [];
const variable = this.globalScope.set.get(key);
if (isModifiedGlobal(variable)) {
continue
}
yield* this._iterateVariableReferences(
/** @type {Variable} */ (variable),
path,
traceMap,
false,
);
}
}
/**
* Iterate the references of CommonJS modules.
* @template T
* @param {TraceMap<T>} traceMap The trace map.
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
*/
*iterateCjsReferences(traceMap) {
for (const { node } of this.iterateGlobalReferences(requireCall)) {
const key = getStringIfConstant(
/** @type {CallExpression} */ (node).arguments[0],
);
if (key == null || !has(traceMap, key)) {
continue
}
const nextTraceMap = traceMap[key];
const path = [key];
if (nextTraceMap[READ]) {
yield {
node,
path,
type: READ,
info: nextTraceMap[READ],
};
}
yield* this._iteratePropertyReferences(
/** @type {CallExpression} */ (node),
path,
nextTraceMap,
);
}
}
/**
* Iterate the references of ES modules.
* @template T
* @param {TraceMap<T>} traceMap The trace map.
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
*/
*iterateEsmReferences(traceMap) {
const programNode = /** @type {Program} */ (this.globalScope.block);
for (const node of programNode.body) {
if (!isHasSource(node)) {
continue
}
const moduleId = /** @type {string} */ (node.source.value);
if (!has(traceMap, moduleId)) {
continue
}
const nextTraceMap = traceMap[moduleId];
const path = [moduleId];
if (nextTraceMap[READ]) {
yield {
// eslint-disable-next-line object-shorthand -- apply type
node: /** @type {RuleNode} */ (node),
path,
type: READ,
info: nextTraceMap[READ],
};
}
if (node.type === "ExportAllDeclaration") {
for (const key of Object.keys(nextTraceMap)) {
const exportTraceMap = nextTraceMap[key];
if (exportTraceMap[READ]) {
yield {
// eslint-disable-next-line object-shorthand -- apply type
node: /** @type {RuleNode} */ (node),
path: path.concat(key),
type: READ,
info: exportTraceMap[READ],
};
}
}
} else {
for (const specifier of node.specifiers) {
const esm = has(nextTraceMap, ESM);
const it = this._iterateImportReferences(
specifier,
path,
esm
? nextTraceMap
: this.mode === "legacy"
? { default: nextTraceMap, ...nextTraceMap }
: { default: nextTraceMap },
);
if (esm) {
yield* it;
} else {
for (const report of it) {
report.path = report.path.filter(exceptDefault);
if (
report.path.length >= 2 ||
report.type !== READ
) {
yield report;
}
}
}
}
}
}
}
/**
* Iterate the property references for a given expression AST node.
* @template T
* @param {Expression} node The expression AST node to iterate property references.
* @param {TraceMap<T>} traceMap The trace map.
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate property references.
*/
*iteratePropertyReferences(node, traceMap) {
yield* this._iteratePropertyReferences(node, [], traceMap);
}
/**
* Iterate the references for a given variable.
* @private
* @template T
* @param {Variable} variable The variable to iterate that references.
* @param {string[]} path The current path.
* @param {TraceMapObject<T>} traceMap The trace map.
* @param {boolean} shouldReport = The flag to report those references.
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
*/
*_iterateVariableReferences(variable, path, traceMap, shouldReport) {
if (this.variableStack.includes(variable)) {
return
}
this.variableStack.push(variable);
try {
for (const reference of variable.references) {
if (!reference.isRead()) {
continue
}
const node = /** @type {RuleNode & Identifier} */ (
reference.identifier
);
if (shouldReport && traceMap[READ]) {
yield { node, path, type: READ, info: traceMap[READ] };
}
yield* this._iteratePropertyReferences(node, path, traceMap);
}
} finally {
this.variableStack.pop();
}
}
/**
* Iterate the references for a given AST node.
* @private
* @template T
* @param {Expression} rootNode The AST node to iterate references.
* @param {string[]} path The current path.
* @param {TraceMapObject<T>} traceMap The trace map.
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
*/
//eslint-disable-next-line complexity
*_iteratePropertyReferences(rootNode, path, traceMap) {
let node = rootNode;
while (isPassThrough(node)) {
node = node.parent;
}
const parent = /** @type {RuleNode} */ (node).parent;
if (!parent) {
return
}
if (parent.type === "MemberExpression") {
if (parent.object === node) {
const key = getPropertyName(parent);
if (key == null || !has(traceMap, key)) {
return
}
path = path.concat(key); //eslint-disable-line no-param-reassign
const nextTraceMap = traceMap[key];
if (nextTraceMap[READ]) {
yield {
node: parent,
path,
type: READ,
info: nextTraceMap[READ],
};
}
yield* this._iteratePropertyReferences(
parent,
path,
nextTraceMap,
);
}
return
}
if (parent.type === "CallExpression") {
if (parent.callee === node && traceMap[CALL]) {
yield { node: parent, path, type: CALL, info: traceMap[CALL] };
}
return
}
if (parent.type === "NewExpression") {
if (parent.callee === node && traceMap[CONSTRUCT]) {
yield {
node: parent,
path,
type: CONSTRUCT,
info: traceMap[CONSTRUCT],
};
}
return
}
if (parent.type === "AssignmentExpression") {
if (parent.right === node) {
yield* this._iterateLhsReferences(parent.left, path, traceMap);
yield* this._iteratePropertyReferences(parent, path, traceMap);
}
return
}
if (parent.type === "AssignmentPattern") {
if (parent.right === node) {
yield* this._iterateLhsReferences(parent.left, path, traceMap);
}
return
}
if (parent.type === "VariableDeclarator") {
if (parent.init === node) {
yield* this._iterateLhsReferences(parent.id, path, traceMap);
}
}
}
/**
* Iterate the references for a given Pattern node.
* @private
* @template T
* @param {Pattern} patternNode The Pattern node to iterate references.
* @param {string[]} path The current path.
* @param {TraceMapObject<T>} traceMap The trace map.
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
*/
*_iterateLhsReferences(patternNode, path, traceMap) {
if (patternNode.type === "Identifier") {
const variable = findVariable(this.globalScope, patternNode);
if (variable != null) {
yield* this._iterateVariableReferences(
variable,
path,
traceMap,
false,
);
}
return
}
if (patternNode.type === "ObjectPattern") {
for (const property of patternNode.properties) {
const key = getPropertyName(
/** @type {AssignmentProperty} */ (property),
);
if (key == null || !has(traceMap, key)) {
continue
}
const nextPath = path.concat(key);
const nextTraceMap = traceMap[key];
if (nextTraceMap[READ]) {
yield {
node: /** @type {RuleNode} */ (property),
path: nextPath,
type: READ,
info: nextTraceMap[READ],
};
}
yield* this._iterateLhsReferences(
/** @type {AssignmentProperty} */ (property).value,
nextPath,
nextTraceMap,
);
}
return
}
if (patternNode.type === "AssignmentPattern") {
yield* this._iterateLhsReferences(patternNode.left, path, traceMap);
}
}
/**
* Iterate the references for a given ModuleSpecifier node.
* @private
* @template T
* @param {ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier} specifierNode The ModuleSpecifier node to iterate references.
* @param {string[]} path The current path.
* @param {TraceMapObject<T>} traceMap The trace map.
* @returns {IterableIterator<TrackedReferences<T>>} The iterator to iterate references.
*/
*_iterateImportReferences(specifierNode, path, traceMap) {
const type = specifierNode.type;
if (type === "ImportSpecifier" || type === "ImportDefaultSpecifier") {
const key =
type === "ImportDefaultSpecifier"
? "default"
: specifierNode.imported.type === "Identifier"
? specifierNode.imported.name
: specifierNode.imported.value;
if (!has(traceMap, key)) {
return
}
path = path.concat(key); //eslint-disable-line no-param-reassign
const nextTraceMap = traceMap[key];
if (nextTraceMap[READ]) {
yield {
node: /** @type {RuleNode} */ (specifierNode),
path,
type: READ,
info: nextTraceMap[READ],
};
}
yield* this._iterateVariableReferences(
/** @type {Variable} */ (
findVariable(this.globalScope, specifierNode.local)
),
path,
nextTraceMap,
false,
);
return
}
if (type === "ImportNamespaceSpecifier") {
yield* this._iterateVariableReferences(
/** @type {Variable} */ (
findVariable(this.globalScope, specifierNode.local)
),
path,
traceMap,
false,
);
return
}
if (type === "ExportSpecifier") {
const key =
specifierNode.local.type === "Identifier"
? specifierNode.local.name
: specifierNode.local.value;
if (!has(traceMap, key)) {
return
}
path = path.concat(key); //eslint-disable-line no-param-reassign
const nextTraceMap = traceMap[key];
if (nextTraceMap[READ]) {
yield {
node: /** @type {RuleNode} */ (specifierNode),
path,
type: READ,
info: nextTraceMap[READ],
};
}
}
}
}
ReferenceTracker.READ = READ;
ReferenceTracker.CALL = CALL;
ReferenceTracker.CONSTRUCT = CONSTRUCT;
ReferenceTracker.ESM = ESM;
/**
* This is a predicate function for Array#filter.
* @param {string} name A name part.
* @param {number} index The index of the name.
* @returns {boolean} `false` if it's default.
*/
function exceptDefault(name, index) {
return !(index === 1 && name === "default")
}
/** @typedef {import("./types.mjs").StaticValue} StaticValue */
var index = {
CALL,
CONSTRUCT,
ESM,
findVariable,
getFunctionHeadLocation,
getFunctionNameWithKind,
getInnermostScope,
getPropertyName,
getStaticValue,
getStringIfConstant,
hasSideEffect,
isArrowToken,
isClosingBraceToken,
isClosingBracketToken,
isClosingParenToken,
isColonToken,
isCommaToken,
isCommentToken,
isNotArrowToken,
isNotClosingBraceToken,
isNotClosingBracketToken,
isNotClosingParenToken,
isNotColonToken,
isNotCommaToken,
isNotCommentToken,
isNotOpeningBraceToken,
isNotOpeningBracketToken,
isNotOpeningParenToken,
isNotSemicolonToken,
isOpeningBraceToken,
isOpeningBracketToken,
isOpeningParenToken,
isParenthesized,
isSemicolonToken,
PatternMatcher,
READ,
ReferenceTracker,
};
exports.CALL = CALL;
exports.CONSTRUCT = CONSTRUCT;
exports.ESM = ESM;
exports.PatternMatcher = PatternMatcher;
exports.READ = READ;
exports.ReferenceTracker = ReferenceTracker;
exports["default"] = index;
exports.findVariable = findVariable;
exports.getFunctionHeadLocation = getFunctionHeadLocation;
exports.getFunctionNameWithKind = getFunctionNameWithKind;
exports.getInnermostScope = getInnermostScope;
exports.getPropertyName = getPropertyName;
exports.getStaticValue = getStaticValue;
exports.getStringIfConstant = getStringIfConstant;
exports.hasSideEffect = hasSideEffect;
exports.isArrowToken = isArrowToken;
exports.isClosingBraceToken = isClosingBraceToken;
exports.isClosingBracketToken = isClosingBracketToken;
exports.isClosingParenToken = isClosingParenToken;
exports.isColonToken = isColonToken;
exports.isCommaToken = isCommaToken;
exports.isCommentToken = isCommentToken;
exports.isNotArrowToken = isNotArrowToken;
exports.isNotClosingBraceToken = isNotClosingBraceToken;
exports.isNotClosingBracketToken = isNotClosingBracketToken;
exports.isNotClosingParenToken = isNotClosingParenToken;
exports.isNotColonToken = isNotColonToken;
exports.isNotCommaToken = isNotCommaToken;
exports.isNotCommentToken = isNotCommentToken;
exports.isNotOpeningBraceToken = isNotOpeningBraceToken;
exports.isNotOpeningBracketToken = isNotOpeningBracketToken;
exports.isNotOpeningParenToken = isNotOpeningParenToken;
exports.isNotSemicolonToken = isNotSemicolonToken;
exports.isOpeningBraceToken = isOpeningBraceToken;
exports.isOpeningBracketToken = isOpeningBracketToken;
exports.isOpeningParenToken = isOpeningParenToken;
exports.isParenthesized = isParenthesized;
exports.isSemicolonToken = isSemicolonToken;
//# sourceMappingURL=index.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+89
View File
@@ -0,0 +1,89 @@
{
"name": "@eslint-community/eslint-utils",
"version": "4.9.1",
"description": "Utilities for ESLint plugins.",
"keywords": [
"eslint"
],
"homepage": "https://github.com/eslint-community/eslint-utils#readme",
"bugs": {
"url": "https://github.com/eslint-community/eslint-utils/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/eslint-community/eslint-utils"
},
"license": "MIT",
"author": "Toru Nagashima",
"sideEffects": false,
"exports": {
".": {
"import": "./index.mjs",
"require": "./index.js"
},
"./package.json": "./package.json"
},
"main": "index",
"module": "index.mjs",
"files": [
"index.*"
],
"scripts": {
"prebuild": "npm run -s clean",
"build": "npm run build:dts && npm run build:rollup",
"build:dts": "tsc -p tsconfig.build.json",
"build:rollup": "rollup -c",
"clean": "rimraf .nyc_output coverage index.* dist",
"coverage": "opener ./coverage/lcov-report/index.html",
"docs:build": "vitepress build docs",
"docs:watch": "vitepress dev docs",
"format": "npm run -s format:prettier -- --write",
"format:prettier": "prettier .",
"format:check": "npm run -s format:prettier -- --check",
"lint:eslint": "eslint .",
"lint:format": "npm run -s format:check",
"lint:installed-check": "installed-check -v -i installed-check -i npm-run-all2 -i knip -i rollup-plugin-dts",
"lint:knip": "knip",
"lint": "run-p lint:*",
"test-coverage": "c8 mocha --reporter dot \"test/*.mjs\"",
"test": "mocha --reporter dot \"test/*.mjs\"",
"preversion": "npm run test-coverage && npm run -s build",
"postversion": "git push && git push --tags",
"prewatch": "npm run -s clean",
"watch": "warun \"{src,test}/**/*.mjs\" -- npm run -s test:mocha"
},
"dependencies": {
"eslint-visitor-keys": "^3.4.3"
},
"devDependencies": {
"@eslint-community/eslint-plugin-mysticatea": "^15.6.1",
"@types/eslint": "^9.6.1",
"@types/estree": "^1.0.7",
"@typescript-eslint/parser": "^5.62.0",
"@typescript-eslint/types": "^5.62.0",
"c8": "^8.0.1",
"dot-prop": "^7.2.0",
"eslint": "^8.57.1",
"installed-check": "^8.0.1",
"knip": "^5.33.3",
"mocha": "^9.2.2",
"npm-run-all2": "^6.2.3",
"opener": "^1.5.2",
"prettier": "2.8.8",
"rimraf": "^3.0.2",
"rollup": "^2.79.2",
"rollup-plugin-dts": "^4.2.3",
"rollup-plugin-sourcemaps": "^0.6.3",
"semver": "^7.6.3",
"typescript": "^4.9.5",
"vitepress": "^1.4.1",
"warun": "^1.0.0"
},
"peerDependencies": {
"eslint": "^6.0.0 || ^7.0.0 || >=8.0.0"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": "https://opencollective.com/eslint"
}
+177
View File
@@ -0,0 +1,177 @@
# @eslint-community/regexpp
[![npm version](https://img.shields.io/npm/v/@eslint-community/regexpp.svg)](https://www.npmjs.com/package/@eslint-community/regexpp)
[![Downloads/month](https://img.shields.io/npm/dm/@eslint-community/regexpp.svg)](http://www.npmtrends.com/@eslint-community/regexpp)
[![Build Status](https://github.com/eslint-community/regexpp/workflows/CI/badge.svg)](https://github.com/eslint-community/regexpp/actions)
[![codecov](https://codecov.io/gh/eslint-community/regexpp/branch/main/graph/badge.svg)](https://codecov.io/gh/eslint-community/regexpp)
A regular expression parser for ECMAScript.
## 💿 Installation
```bash
$ npm install @eslint-community/regexpp
```
- require Node@^12.0.0 || ^14.0.0 || >=16.0.0.
## 📖 Usage
```ts
import {
AST,
RegExpParser,
RegExpValidator,
RegExpVisitor,
parseRegExpLiteral,
validateRegExpLiteral,
visitRegExpAST
} from "@eslint-community/regexpp"
```
### parseRegExpLiteral(source, options?)
Parse a given regular expression literal then make AST object.
This is equivalent to `new RegExpParser(options).parseLiteral(source)`.
- **Parameters:**
- `source` (`string | RegExp`) The source code to parse.
- `options?` ([`RegExpParser.Options`]) The options to parse.
- **Return:**
- The AST of the regular expression.
### validateRegExpLiteral(source, options?)
Validate a given regular expression literal.
This is equivalent to `new RegExpValidator(options).validateLiteral(source)`.
- **Parameters:**
- `source` (`string`) The source code to validate.
- `options?` ([`RegExpValidator.Options`]) The options to validate.
### visitRegExpAST(ast, handlers)
Visit each node of a given AST.
This is equivalent to `new RegExpVisitor(handlers).visit(ast)`.
- **Parameters:**
- `ast` ([`AST.Node`]) The AST to visit.
- `handlers` ([`RegExpVisitor.Handlers`]) The callbacks.
### RegExpParser
#### new RegExpParser(options?)
- **Parameters:**
- `options?` ([`RegExpParser.Options`]) The options to parse.
#### parser.parseLiteral(source, start?, end?)
Parse a regular expression literal.
- **Parameters:**
- `source` (`string`) The source code to parse. E.g. `"/abc/g"`.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
- **Return:**
- The AST of the regular expression.
#### parser.parsePattern(source, start?, end?, flags?)
Parse a regular expression pattern.
- **Parameters:**
- `source` (`string`) The source code to parse. E.g. `"abc"`.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
- `flags?` (`{ unicode?: boolean, unicodeSets?: boolean }`) The flags to enable Unicode mode, and Unicode Set mode.
- **Return:**
- The AST of the regular expression pattern.
#### parser.parseFlags(source, start?, end?)
Parse a regular expression flags.
- **Parameters:**
- `source` (`string`) The source code to parse. E.g. `"gim"`.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
- **Return:**
- The AST of the regular expression flags.
### RegExpValidator
#### new RegExpValidator(options)
- **Parameters:**
- `options` ([`RegExpValidator.Options`]) The options to validate.
#### validator.validateLiteral(source, start, end)
Validate a regular expression literal.
- **Parameters:**
- `source` (`string`) The source code to validate.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
#### validator.validatePattern(source, start, end, flags)
Validate a regular expression pattern.
- **Parameters:**
- `source` (`string`) The source code to validate.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
- `flags?` (`{ unicode?: boolean, unicodeSets?: boolean }`) The flags to enable Unicode mode, and Unicode Set mode.
#### validator.validateFlags(source, start, end)
Validate a regular expression flags.
- **Parameters:**
- `source` (`string`) The source code to validate.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
### RegExpVisitor
#### new RegExpVisitor(handlers)
- **Parameters:**
- `handlers` ([`RegExpVisitor.Handlers`]) The callbacks.
#### visitor.visit(ast)
Validate a regular expression literal.
- **Parameters:**
- `ast` ([`AST.Node`]) The AST to visit.
## 📰 Changelog
- [GitHub Releases](https://github.com/eslint-community/regexpp/releases)
## 🍻 Contributing
Welcome contributing!
Please use GitHub's Issues/PRs.
### Development Tools
- `npm test` runs tests and measures coverage.
- `npm run build` compiles TypeScript source code to `index.js`, `index.js.map`, and `index.d.ts`.
- `npm run clean` removes the temporary files which are created by `npm test` and `npm run build`.
- `npm run lint` runs ESLint.
- `npm run update:test` updates test fixtures.
- `npm run update:ids` updates `src/unicode/ids.ts`.
- `npm run watch` runs tests with `--watch` option.
[`AST.Node`]: src/ast.ts#L4
[`RegExpParser.Options`]: src/parser.ts#L743
[`RegExpValidator.Options`]: src/validator.ts#L220
[`RegExpVisitor.Handlers`]: src/visitor.ts#L291
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+91
View File
@@ -0,0 +1,91 @@
{
"name": "@eslint-community/regexpp",
"version": "4.12.2",
"description": "Regular expression parser for ECMAScript.",
"keywords": [
"regexp",
"regular",
"expression",
"parser",
"validator",
"ast",
"abstract",
"syntax",
"tree",
"ecmascript",
"es2015",
"es2016",
"es2017",
"es2018",
"es2019",
"es2020",
"es2021",
"annexB"
],
"homepage": "https://github.com/eslint-community/regexpp#readme",
"bugs": {
"url": "https://github.com/eslint-community/regexpp/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/eslint-community/regexpp"
},
"license": "MIT",
"author": "Toru Nagashima",
"exports": {
".": {
"types": "./index.d.ts",
"import": "./index.mjs",
"default": "./index.js"
},
"./package.json": "./package.json"
},
"main": "index",
"files": [
"index.*"
],
"scripts": {
"prebuild": "npm run -s clean",
"build": "run-s build:*",
"build:tsc": "tsc --module es2015",
"build:rollup": "rollup -c",
"build:dts": "npm run -s build:tsc -- --removeComments false && dts-bundle --name @eslint-community/regexpp --main .temp/index.d.ts --out ../index.d.ts && prettier --write index.d.ts",
"clean": "rimraf .temp index.*",
"lint": "eslint . --ext .ts",
"test": "nyc _mocha \"test/*.ts\" --reporter dot --timeout 10000",
"debug": "mocha --require ts-node/register/transpile-only \"test/*.ts\" --reporter dot --timeout 10000",
"update:test": "ts-node scripts/update-fixtures.ts",
"update:unicode": "run-s update:unicode:*",
"update:unicode:ids": "ts-node scripts/update-unicode-ids.ts",
"update:unicode:props": "ts-node scripts/update-unicode-properties.ts",
"update:test262:extract": "ts-node -T scripts/extract-test262.ts",
"preversion": "npm test && npm run -s build",
"postversion": "git push && git push --tags",
"prewatch": "npm run -s clean",
"watch": "_mocha \"test/*.ts\" --require ts-node/register --reporter dot --timeout 10000 --watch-extensions ts --watch --growl"
},
"dependencies": {},
"devDependencies": {
"@eslint-community/eslint-plugin-mysticatea": "^15.5.1",
"@rollup/plugin-node-resolve": "^14.1.0",
"@types/eslint": "^8.44.3",
"@types/jsdom": "^16.2.15",
"@types/mocha": "^9.1.1",
"@types/node": "^12.20.55",
"dts-bundle": "^0.7.3",
"eslint": "^8.50.0",
"js-tokens": "^8.0.2",
"jsdom": "^19.0.0",
"mocha": "^9.2.2",
"npm-run-all2": "^6.2.2",
"nyc": "^14.1.1",
"rimraf": "^3.0.2",
"rollup": "^2.79.1",
"rollup-plugin-sourcemaps": "^0.6.3",
"ts-node": "^10.9.1",
"typescript": "~5.0.2"
},
"engines": {
"node": "^12.0.0 || ^14.0.0 || >=16.0.0"
}
}