mirror of
https://github.com/chrisnov-it/quantumbotx.git
synced 2026-07-27 18:57:47 +00:00
chore: Untrack node_modules and other generated files
This commit is contained in:
-16
@@ -1,16 +0,0 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*)
|
||||
if command -v cygpath > /dev/null 2>&1; then
|
||||
basedir=`cygpath -w "$basedir"`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../acorn/bin/acorn" "$@"
|
||||
else
|
||||
exec node "$basedir/../acorn/bin/acorn" "$@"
|
||||
fi
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\acorn\bin\acorn" %*
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../acorn/bin/acorn" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../acorn/bin/acorn" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../acorn/bin/acorn" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../acorn/bin/acorn" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*)
|
||||
if command -v cygpath > /dev/null 2>&1; then
|
||||
basedir=`cygpath -w "$basedir"`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../eslint/bin/eslint.js" "$@"
|
||||
else
|
||||
exec node "$basedir/../eslint/bin/eslint.js" "$@"
|
||||
fi
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\eslint\bin\eslint.js" %*
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../eslint/bin/eslint.js" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../eslint/bin/eslint.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../eslint/bin/eslint.js" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../eslint/bin/eslint.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*)
|
||||
if command -v cygpath > /dev/null 2>&1; then
|
||||
basedir=`cygpath -w "$basedir"`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../js-yaml/bin/js-yaml.js" "$@"
|
||||
else
|
||||
exec node "$basedir/../js-yaml/bin/js-yaml.js" "$@"
|
||||
fi
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\js-yaml\bin\js-yaml.js" %*
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*)
|
||||
if command -v cygpath > /dev/null 2>&1; then
|
||||
basedir=`cygpath -w "$basedir"`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../which/bin/node-which" "$@"
|
||||
else
|
||||
exec node "$basedir/../which/bin/node-which" "$@"
|
||||
fi
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\which\bin\node-which" %*
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../which/bin/node-which" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../which/bin/node-which" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../which/bin/node-which" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../which/bin/node-which" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
-2268
File diff suppressed because it is too large
Load Diff
-21
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018 Toru Nagashima
|
||||
|
||||
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.
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
# @eslint-community/eslint-utils
|
||||
|
||||
[](https://www.npmjs.com/package/@eslint-community/eslint-utils)
|
||||
[](http://www.npmtrends.com/@eslint-community/eslint-utils)
|
||||
[](https://github.com/eslint-community/eslint-utils/actions)
|
||||
[](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
@@ -1,217 +0,0 @@
|
||||
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
@@ -1,217 +0,0 @@
|
||||
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 };
|
||||
-2494
File diff suppressed because it is too large
Load Diff
-1
File diff suppressed because one or more lines are too long
-2453
File diff suppressed because it is too large
Load Diff
-1
File diff suppressed because one or more lines are too long
Generated
Vendored
-201
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright contributors
|
||||
|
||||
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
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Generated
Vendored
-105
@@ -1,105 +0,0 @@
|
||||
# eslint-visitor-keys
|
||||
|
||||
[](https://www.npmjs.com/package/eslint-visitor-keys)
|
||||
[](http://www.npmtrends.com/eslint-visitor-keys)
|
||||
[](https://github.com/eslint/eslint-visitor-keys/actions)
|
||||
|
||||
Constants and utilities about visitor keys to traverse AST.
|
||||
|
||||
## 💿 Installation
|
||||
|
||||
Use [npm] to install.
|
||||
|
||||
```bash
|
||||
$ npm install eslint-visitor-keys
|
||||
```
|
||||
|
||||
### Requirements
|
||||
|
||||
- [Node.js] `^12.22.0`, `^14.17.0`, or `>=16.0.0`
|
||||
|
||||
|
||||
## 📖 Usage
|
||||
|
||||
To use in an ESM file:
|
||||
|
||||
```js
|
||||
import * as evk from "eslint-visitor-keys"
|
||||
```
|
||||
|
||||
To use in a CommonJS file:
|
||||
|
||||
```js
|
||||
const evk = require("eslint-visitor-keys")
|
||||
```
|
||||
|
||||
### evk.KEYS
|
||||
|
||||
> type: `{ [type: string]: string[] | undefined }`
|
||||
|
||||
Visitor keys. This keys are frozen.
|
||||
|
||||
This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes.
|
||||
|
||||
For example:
|
||||
|
||||
```
|
||||
console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"]
|
||||
```
|
||||
|
||||
### evk.getKeys(node)
|
||||
|
||||
> type: `(node: object) => string[]`
|
||||
|
||||
Get the visitor keys of a given AST node.
|
||||
|
||||
This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`.
|
||||
|
||||
This will be used to traverse unknown nodes.
|
||||
|
||||
For example:
|
||||
|
||||
```js
|
||||
const node = {
|
||||
type: "AssignmentExpression",
|
||||
left: { type: "Identifier", name: "foo" },
|
||||
right: { type: "Literal", value: 0 }
|
||||
}
|
||||
console.log(evk.getKeys(node)) // → ["type", "left", "right"]
|
||||
```
|
||||
|
||||
### evk.unionWith(additionalKeys)
|
||||
|
||||
> type: `(additionalKeys: object) => { [type: string]: string[] | undefined }`
|
||||
|
||||
Make the union set with `evk.KEYS` and the given keys.
|
||||
|
||||
- The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that.
|
||||
- It removes duplicated keys as keeping the first one.
|
||||
|
||||
For example:
|
||||
|
||||
```js
|
||||
console.log(evk.unionWith({
|
||||
MethodDefinition: ["decorators"]
|
||||
})) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... }
|
||||
```
|
||||
|
||||
## 📰 Change log
|
||||
|
||||
See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases).
|
||||
|
||||
## 🍻 Contributing
|
||||
|
||||
Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/).
|
||||
|
||||
### Development commands
|
||||
|
||||
- `npm test` runs tests and measures code coverage.
|
||||
- `npm run lint` checks source codes with ESLint.
|
||||
- `npm run test:open-coverage` opens the code coverage report of the previous test with your default browser.
|
||||
|
||||
|
||||
[npm]: https://www.npmjs.com/
|
||||
[Node.js]: https://nodejs.org/
|
||||
[ESTree]: https://github.com/estree/estree
|
||||
Generated
Vendored
-65
@@ -1,65 +0,0 @@
|
||||
/**
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
* See LICENSE file in root directory for full license.
|
||||
*/
|
||||
import KEYS from "./visitor-keys.js";
|
||||
|
||||
/**
|
||||
* @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys
|
||||
*/
|
||||
|
||||
// List to ignore keys.
|
||||
const KEY_BLACKLIST = new Set([
|
||||
"parent",
|
||||
"leadingComments",
|
||||
"trailingComments"
|
||||
]);
|
||||
|
||||
/**
|
||||
* Check whether a given key should be used or not.
|
||||
* @param {string} key The key to check.
|
||||
* @returns {boolean} `true` if the key should be used.
|
||||
*/
|
||||
function filterKey(key) {
|
||||
return !KEY_BLACKLIST.has(key) && key[0] !== "_";
|
||||
}
|
||||
|
||||
/**
|
||||
* Get visitor keys of a given node.
|
||||
* @param {object} node The AST node to get keys.
|
||||
* @returns {readonly string[]} Visitor keys of the node.
|
||||
*/
|
||||
export function getKeys(node) {
|
||||
return Object.keys(node).filter(filterKey);
|
||||
}
|
||||
|
||||
// Disable valid-jsdoc rule because it reports syntax error on the type of @returns.
|
||||
// eslint-disable-next-line valid-jsdoc
|
||||
/**
|
||||
* Make the union set with `KEYS` and given keys.
|
||||
* @param {VisitorKeys} additionalKeys The additional keys.
|
||||
* @returns {VisitorKeys} The union set.
|
||||
*/
|
||||
export function unionWith(additionalKeys) {
|
||||
const retv = /** @type {{
|
||||
[type: string]: ReadonlyArray<string>
|
||||
}} */ (Object.assign({}, KEYS));
|
||||
|
||||
for (const type of Object.keys(additionalKeys)) {
|
||||
if (Object.prototype.hasOwnProperty.call(retv, type)) {
|
||||
const keys = new Set(additionalKeys[type]);
|
||||
|
||||
for (const key of retv[type]) {
|
||||
keys.add(key);
|
||||
}
|
||||
|
||||
retv[type] = Object.freeze(Array.from(keys));
|
||||
} else {
|
||||
retv[type] = Object.freeze(Array.from(additionalKeys[type]));
|
||||
}
|
||||
}
|
||||
|
||||
return Object.freeze(retv);
|
||||
}
|
||||
|
||||
export { KEYS };
|
||||
Generated
Vendored
-315
@@ -1,315 +0,0 @@
|
||||
/**
|
||||
* @typedef {{ readonly [type: string]: ReadonlyArray<string> }} VisitorKeys
|
||||
*/
|
||||
|
||||
/**
|
||||
* @type {VisitorKeys}
|
||||
*/
|
||||
const KEYS = {
|
||||
ArrayExpression: [
|
||||
"elements"
|
||||
],
|
||||
ArrayPattern: [
|
||||
"elements"
|
||||
],
|
||||
ArrowFunctionExpression: [
|
||||
"params",
|
||||
"body"
|
||||
],
|
||||
AssignmentExpression: [
|
||||
"left",
|
||||
"right"
|
||||
],
|
||||
AssignmentPattern: [
|
||||
"left",
|
||||
"right"
|
||||
],
|
||||
AwaitExpression: [
|
||||
"argument"
|
||||
],
|
||||
BinaryExpression: [
|
||||
"left",
|
||||
"right"
|
||||
],
|
||||
BlockStatement: [
|
||||
"body"
|
||||
],
|
||||
BreakStatement: [
|
||||
"label"
|
||||
],
|
||||
CallExpression: [
|
||||
"callee",
|
||||
"arguments"
|
||||
],
|
||||
CatchClause: [
|
||||
"param",
|
||||
"body"
|
||||
],
|
||||
ChainExpression: [
|
||||
"expression"
|
||||
],
|
||||
ClassBody: [
|
||||
"body"
|
||||
],
|
||||
ClassDeclaration: [
|
||||
"id",
|
||||
"superClass",
|
||||
"body"
|
||||
],
|
||||
ClassExpression: [
|
||||
"id",
|
||||
"superClass",
|
||||
"body"
|
||||
],
|
||||
ConditionalExpression: [
|
||||
"test",
|
||||
"consequent",
|
||||
"alternate"
|
||||
],
|
||||
ContinueStatement: [
|
||||
"label"
|
||||
],
|
||||
DebuggerStatement: [],
|
||||
DoWhileStatement: [
|
||||
"body",
|
||||
"test"
|
||||
],
|
||||
EmptyStatement: [],
|
||||
ExperimentalRestProperty: [
|
||||
"argument"
|
||||
],
|
||||
ExperimentalSpreadProperty: [
|
||||
"argument"
|
||||
],
|
||||
ExportAllDeclaration: [
|
||||
"exported",
|
||||
"source"
|
||||
],
|
||||
ExportDefaultDeclaration: [
|
||||
"declaration"
|
||||
],
|
||||
ExportNamedDeclaration: [
|
||||
"declaration",
|
||||
"specifiers",
|
||||
"source"
|
||||
],
|
||||
ExportSpecifier: [
|
||||
"exported",
|
||||
"local"
|
||||
],
|
||||
ExpressionStatement: [
|
||||
"expression"
|
||||
],
|
||||
ForInStatement: [
|
||||
"left",
|
||||
"right",
|
||||
"body"
|
||||
],
|
||||
ForOfStatement: [
|
||||
"left",
|
||||
"right",
|
||||
"body"
|
||||
],
|
||||
ForStatement: [
|
||||
"init",
|
||||
"test",
|
||||
"update",
|
||||
"body"
|
||||
],
|
||||
FunctionDeclaration: [
|
||||
"id",
|
||||
"params",
|
||||
"body"
|
||||
],
|
||||
FunctionExpression: [
|
||||
"id",
|
||||
"params",
|
||||
"body"
|
||||
],
|
||||
Identifier: [],
|
||||
IfStatement: [
|
||||
"test",
|
||||
"consequent",
|
||||
"alternate"
|
||||
],
|
||||
ImportDeclaration: [
|
||||
"specifiers",
|
||||
"source"
|
||||
],
|
||||
ImportDefaultSpecifier: [
|
||||
"local"
|
||||
],
|
||||
ImportExpression: [
|
||||
"source"
|
||||
],
|
||||
ImportNamespaceSpecifier: [
|
||||
"local"
|
||||
],
|
||||
ImportSpecifier: [
|
||||
"imported",
|
||||
"local"
|
||||
],
|
||||
JSXAttribute: [
|
||||
"name",
|
||||
"value"
|
||||
],
|
||||
JSXClosingElement: [
|
||||
"name"
|
||||
],
|
||||
JSXClosingFragment: [],
|
||||
JSXElement: [
|
||||
"openingElement",
|
||||
"children",
|
||||
"closingElement"
|
||||
],
|
||||
JSXEmptyExpression: [],
|
||||
JSXExpressionContainer: [
|
||||
"expression"
|
||||
],
|
||||
JSXFragment: [
|
||||
"openingFragment",
|
||||
"children",
|
||||
"closingFragment"
|
||||
],
|
||||
JSXIdentifier: [],
|
||||
JSXMemberExpression: [
|
||||
"object",
|
||||
"property"
|
||||
],
|
||||
JSXNamespacedName: [
|
||||
"namespace",
|
||||
"name"
|
||||
],
|
||||
JSXOpeningElement: [
|
||||
"name",
|
||||
"attributes"
|
||||
],
|
||||
JSXOpeningFragment: [],
|
||||
JSXSpreadAttribute: [
|
||||
"argument"
|
||||
],
|
||||
JSXSpreadChild: [
|
||||
"expression"
|
||||
],
|
||||
JSXText: [],
|
||||
LabeledStatement: [
|
||||
"label",
|
||||
"body"
|
||||
],
|
||||
Literal: [],
|
||||
LogicalExpression: [
|
||||
"left",
|
||||
"right"
|
||||
],
|
||||
MemberExpression: [
|
||||
"object",
|
||||
"property"
|
||||
],
|
||||
MetaProperty: [
|
||||
"meta",
|
||||
"property"
|
||||
],
|
||||
MethodDefinition: [
|
||||
"key",
|
||||
"value"
|
||||
],
|
||||
NewExpression: [
|
||||
"callee",
|
||||
"arguments"
|
||||
],
|
||||
ObjectExpression: [
|
||||
"properties"
|
||||
],
|
||||
ObjectPattern: [
|
||||
"properties"
|
||||
],
|
||||
PrivateIdentifier: [],
|
||||
Program: [
|
||||
"body"
|
||||
],
|
||||
Property: [
|
||||
"key",
|
||||
"value"
|
||||
],
|
||||
PropertyDefinition: [
|
||||
"key",
|
||||
"value"
|
||||
],
|
||||
RestElement: [
|
||||
"argument"
|
||||
],
|
||||
ReturnStatement: [
|
||||
"argument"
|
||||
],
|
||||
SequenceExpression: [
|
||||
"expressions"
|
||||
],
|
||||
SpreadElement: [
|
||||
"argument"
|
||||
],
|
||||
StaticBlock: [
|
||||
"body"
|
||||
],
|
||||
Super: [],
|
||||
SwitchCase: [
|
||||
"test",
|
||||
"consequent"
|
||||
],
|
||||
SwitchStatement: [
|
||||
"discriminant",
|
||||
"cases"
|
||||
],
|
||||
TaggedTemplateExpression: [
|
||||
"tag",
|
||||
"quasi"
|
||||
],
|
||||
TemplateElement: [],
|
||||
TemplateLiteral: [
|
||||
"quasis",
|
||||
"expressions"
|
||||
],
|
||||
ThisExpression: [],
|
||||
ThrowStatement: [
|
||||
"argument"
|
||||
],
|
||||
TryStatement: [
|
||||
"block",
|
||||
"handler",
|
||||
"finalizer"
|
||||
],
|
||||
UnaryExpression: [
|
||||
"argument"
|
||||
],
|
||||
UpdateExpression: [
|
||||
"argument"
|
||||
],
|
||||
VariableDeclaration: [
|
||||
"declarations"
|
||||
],
|
||||
VariableDeclarator: [
|
||||
"id",
|
||||
"init"
|
||||
],
|
||||
WhileStatement: [
|
||||
"test",
|
||||
"body"
|
||||
],
|
||||
WithStatement: [
|
||||
"object",
|
||||
"body"
|
||||
],
|
||||
YieldExpression: [
|
||||
"argument"
|
||||
]
|
||||
};
|
||||
|
||||
// Types.
|
||||
const NODE_TYPES = Object.keys(KEYS);
|
||||
|
||||
// Freeze the keys.
|
||||
for (const type of NODE_TYPES) {
|
||||
Object.freeze(KEYS[type]);
|
||||
}
|
||||
Object.freeze(KEYS);
|
||||
|
||||
export default KEYS;
|
||||
Generated
Vendored
-74
@@ -1,74 +0,0 @@
|
||||
{
|
||||
"name": "eslint-visitor-keys",
|
||||
"version": "3.4.3",
|
||||
"description": "Constants and utilities about visitor keys to traverse AST.",
|
||||
"type": "module",
|
||||
"main": "dist/eslint-visitor-keys.cjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": [
|
||||
{
|
||||
"import": "./lib/index.js",
|
||||
"require": "./dist/eslint-visitor-keys.cjs"
|
||||
},
|
||||
"./dist/eslint-visitor-keys.cjs"
|
||||
],
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"dist/index.d.ts",
|
||||
"dist/visitor-keys.d.ts",
|
||||
"dist/eslint-visitor-keys.cjs",
|
||||
"dist/eslint-visitor-keys.d.cts",
|
||||
"lib"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/estree": "^0.0.51",
|
||||
"@types/estree-jsx": "^0.0.1",
|
||||
"@typescript-eslint/parser": "^5.14.0",
|
||||
"c8": "^7.11.0",
|
||||
"chai": "^4.3.6",
|
||||
"eslint": "^7.29.0",
|
||||
"eslint-config-eslint": "^7.0.0",
|
||||
"eslint-plugin-jsdoc": "^35.4.0",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-release": "^3.2.0",
|
||||
"esquery": "^1.4.0",
|
||||
"json-diff": "^0.7.3",
|
||||
"mocha": "^9.2.1",
|
||||
"opener": "^1.5.2",
|
||||
"rollup": "^2.70.0",
|
||||
"rollup-plugin-dts": "^4.2.3",
|
||||
"tsd": "^0.19.1",
|
||||
"typescript": "^4.6.2"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "npm run build:cjs && npm run build:types",
|
||||
"build:cjs": "rollup -c",
|
||||
"build:debug": "npm run build:cjs -- -m && npm run build:types",
|
||||
"build:keys": "node tools/build-keys-from-ts",
|
||||
"build:types": "tsc",
|
||||
"lint": "eslint .",
|
||||
"prepare": "npm run build",
|
||||
"release:generate:latest": "eslint-generate-release",
|
||||
"release:generate:alpha": "eslint-generate-prerelease alpha",
|
||||
"release:generate:beta": "eslint-generate-prerelease beta",
|
||||
"release:generate:rc": "eslint-generate-prerelease rc",
|
||||
"release:publish": "eslint-publish-release",
|
||||
"test": "mocha tests/lib/**/*.cjs && c8 mocha tests/lib/**/*.js && npm run test:types",
|
||||
"test:open-coverage": "c8 report --reporter lcov && opener coverage/lcov-report/index.html",
|
||||
"test:types": "tsd"
|
||||
},
|
||||
"repository": "eslint/eslint-visitor-keys",
|
||||
"funding": "https://opencollective.com/eslint",
|
||||
"keywords": [],
|
||||
"author": "Toru Nagashima (https://github.com/mysticatea)",
|
||||
"license": "Apache-2.0",
|
||||
"bugs": {
|
||||
"url": "https://github.com/eslint/eslint-visitor-keys/issues"
|
||||
},
|
||||
"homepage": "https://github.com/eslint/eslint-visitor-keys#readme"
|
||||
}
|
||||
-89
@@ -1,89 +0,0 @@
|
||||
{
|
||||
"name": "@eslint-community/eslint-utils",
|
||||
"version": "4.7.0",
|
||||
"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"
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018 Toru Nagashima
|
||||
|
||||
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.
|
||||
-177
@@ -1,177 +0,0 @@
|
||||
# @eslint-community/regexpp
|
||||
|
||||
[](https://www.npmjs.com/package/@eslint-community/regexpp)
|
||||
[](http://www.npmtrends.com/@eslint-community/regexpp)
|
||||
[](https://github.com/eslint-community/regexpp/actions)
|
||||
[](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
|
||||
-1163
File diff suppressed because it is too large
Load Diff
-3037
File diff suppressed because it is too large
Load Diff
-1
File diff suppressed because one or more lines are too long
-3027
File diff suppressed because it is too large
Load Diff
-1
File diff suppressed because one or more lines are too long
-91
@@ -1,91 +0,0 @@
|
||||
{
|
||||
"name": "@eslint-community/regexpp",
|
||||
"version": "4.12.1",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
-201
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
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
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
-369
@@ -1,369 +0,0 @@
|
||||
# Config Array
|
||||
|
||||
## Description
|
||||
|
||||
A config array is a way of managing configurations that are based on glob pattern matching of filenames. Each config array contains the information needed to determine the correct configuration for any file based on the filename.
|
||||
|
||||
**Note:** This is a generic package that can be used outside of ESLint. It contains no ESLint-specific functionality.
|
||||
|
||||
## Installation
|
||||
|
||||
For Node.js and compatible runtimes:
|
||||
|
||||
```shell
|
||||
npm install @eslint/config-array
|
||||
# or
|
||||
yarn add @eslint/config-array
|
||||
# or
|
||||
pnpm install @eslint/config-array
|
||||
# or
|
||||
bun add @eslint/config-array
|
||||
```
|
||||
|
||||
For Deno:
|
||||
|
||||
```shell
|
||||
deno add @eslint/config-array
|
||||
```
|
||||
|
||||
## Background
|
||||
|
||||
The basic idea is that all configuration, including overrides, can be represented by a single array where each item in the array is a config object. Config objects appearing later in the array override config objects appearing earlier in the array. You can calculate a config for a given file by traversing all config objects in the array to find the ones that match the filename. Matching is done by specifying glob patterns in `files` and `ignores` properties on each config object. Here's an example:
|
||||
|
||||
```js
|
||||
export default [
|
||||
// match all JSON files
|
||||
{
|
||||
name: "JSON Handler",
|
||||
files: ["**/*.json"],
|
||||
handler: jsonHandler,
|
||||
},
|
||||
|
||||
// match only package.json
|
||||
{
|
||||
name: "package.json Handler",
|
||||
files: ["package.json"],
|
||||
handler: packageJsonHandler,
|
||||
},
|
||||
];
|
||||
```
|
||||
|
||||
In this example, there are two config objects: the first matches all JSON files in all directories and the second matches just `package.json` in the base path directory (all the globs are evaluated as relative to a base path that can be specified). When you retrieve a configuration for `foo.json`, only the first config object matches so `handler` is equal to `jsonHandler`; when you retrieve a configuration for `package.json`, `handler` is equal to `packageJsonHandler` (because both config objects match, the second one wins).
|
||||
|
||||
## Usage
|
||||
|
||||
First, import the `ConfigArray` constructor:
|
||||
|
||||
```js
|
||||
import { ConfigArray } from "@eslint/config-array";
|
||||
|
||||
// or using CommonJS
|
||||
|
||||
const { ConfigArray } = require("@eslint/config-array");
|
||||
```
|
||||
|
||||
When you create a new instance of `ConfigArray`, you must pass in two arguments: an array of configs and an options object. The array of configs is most likely read in from a configuration file, so here's a typical example:
|
||||
|
||||
```js
|
||||
const configFilename = path.resolve(process.cwd(), "my.config.js");
|
||||
const { default: rawConfigs } = await import(configFilename);
|
||||
const configs = new ConfigArray(rawConfigs, {
|
||||
// the path to match filenames from
|
||||
basePath: process.cwd(),
|
||||
|
||||
// additional items in each config
|
||||
schema: mySchema,
|
||||
});
|
||||
```
|
||||
|
||||
This example reads in an object or array from `my.config.js` and passes it into the `ConfigArray` constructor as the first argument. The second argument is an object specifying the `basePath` (the directory in which `my.config.js` is found) and a `schema` to define the additional properties of a config object beyond `files`, `ignores`, `basePath`, and `name`.
|
||||
|
||||
### Specifying a Schema
|
||||
|
||||
The `schema` option is required for you to use additional properties in config objects. The schema is an object that follows the format of an [`ObjectSchema`](https://npmjs.com/package/@eslint/object-schema). The schema specifies both validation and merge rules that the `ConfigArray` instance needs to combine configs when there are multiple matches. Here's an example:
|
||||
|
||||
```js
|
||||
const configFilename = path.resolve(process.cwd(), "my.config.js");
|
||||
const { default: rawConfigs } = await import(configFilename);
|
||||
|
||||
const mySchema = {
|
||||
|
||||
// define the handler key in configs
|
||||
handler: {
|
||||
required: true,
|
||||
merge(a, b) {
|
||||
if (!b) return a;
|
||||
if (!a) return b;
|
||||
},
|
||||
validate(value) {
|
||||
if (typeof value !== "function") {
|
||||
throw new TypeError("Function expected.");
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const configs = new ConfigArray(rawConfigs, {
|
||||
|
||||
// the path to match filenames from
|
||||
basePath: process.cwd(),
|
||||
|
||||
// additional item schemas in each config
|
||||
schema: mySchema,
|
||||
|
||||
// additional config types supported (default: [])
|
||||
extraConfigTypes: ["array", "function"];
|
||||
});
|
||||
```
|
||||
|
||||
### Config Arrays
|
||||
|
||||
Config arrays can be multidimensional, so it's possible for a config array to contain another config array when `extraConfigTypes` contains `"array"`, such as:
|
||||
|
||||
```js
|
||||
export default [
|
||||
// JS config
|
||||
{
|
||||
files: ["**/*.js"],
|
||||
handler: jsHandler,
|
||||
},
|
||||
|
||||
// JSON configs
|
||||
[
|
||||
// match all JSON files
|
||||
{
|
||||
name: "JSON Handler",
|
||||
files: ["**/*.json"],
|
||||
handler: jsonHandler,
|
||||
},
|
||||
|
||||
// match only package.json
|
||||
{
|
||||
name: "package.json Handler",
|
||||
files: ["package.json"],
|
||||
handler: packageJsonHandler,
|
||||
},
|
||||
],
|
||||
|
||||
// filename must match function
|
||||
{
|
||||
files: [filePath => filePath.endsWith(".md")],
|
||||
handler: markdownHandler,
|
||||
},
|
||||
|
||||
// filename must match all patterns in subarray
|
||||
{
|
||||
files: [["*.test.*", "*.js"]],
|
||||
handler: jsTestHandler,
|
||||
},
|
||||
|
||||
// filename must not match patterns beginning with !
|
||||
{
|
||||
name: "Non-JS files",
|
||||
files: ["!*.js"],
|
||||
settings: {
|
||||
js: false,
|
||||
},
|
||||
},
|
||||
|
||||
// specific settings for files inside `src` directory
|
||||
{
|
||||
name: "Source files",
|
||||
basePath: "src",
|
||||
files: ["**/*"],
|
||||
settings: {
|
||||
source: true,
|
||||
},
|
||||
},
|
||||
];
|
||||
```
|
||||
|
||||
In this example, the array contains both config objects and a config array. When a config array is normalized (see details below), it is flattened so only config objects remain. However, the order of evaluation remains the same.
|
||||
|
||||
If the `files` array contains a function, then that function is called with the path of the file as it was passed in. The function is expected to return `true` if there is a match and `false` if not. (The `ignores` array can also contain functions.)
|
||||
|
||||
If the `files` array contains an item that is an array of strings and functions, then all patterns must match in order for the config to match. In the preceding examples, both `*.test.*` and `*.js` must match in order for the config object to be used.
|
||||
|
||||
If a pattern in the files array begins with `!` then it excludes that pattern. In the preceding example, any filename that doesn't end with `.js` will automatically get a `settings.js` property set to `false`.
|
||||
|
||||
You can also specify an `ignores` key that will force files matching those patterns to not be included. If the `ignores` key is in a config object without any other keys, then those ignores will always be applied; otherwise those ignores act as exclusions. Here's an example:
|
||||
|
||||
```js
|
||||
export default [
|
||||
|
||||
// Always ignored
|
||||
{
|
||||
ignores: ["**/.git/**", "**/node_modules/**"]
|
||||
},
|
||||
|
||||
// .eslintrc.js file is ignored only when .js file matches
|
||||
{
|
||||
files: ["**/*.js"],
|
||||
ignores: [".eslintrc.js"]
|
||||
handler: jsHandler
|
||||
}
|
||||
];
|
||||
```
|
||||
|
||||
You can use negated patterns in `ignores` to exclude a file that was already ignored, such as:
|
||||
|
||||
```js
|
||||
export default [
|
||||
// Ignore all JSON files except tsconfig.json
|
||||
{
|
||||
files: ["**/*"],
|
||||
ignores: ["**/*.json", "!tsconfig.json"],
|
||||
},
|
||||
];
|
||||
```
|
||||
|
||||
### Config Functions
|
||||
|
||||
Config arrays can also include config functions when `extraConfigTypes` contains `"function"`. A config function accepts a single parameter, `context` (defined by you), and must return either a config object or a config array (it cannot return another function). Config functions allow end users to execute code in the creation of appropriate config objects. Here's an example:
|
||||
|
||||
```js
|
||||
export default [
|
||||
// JS config
|
||||
{
|
||||
files: ["**/*.js"],
|
||||
handler: jsHandler,
|
||||
},
|
||||
|
||||
// JSON configs
|
||||
function (context) {
|
||||
return [
|
||||
// match all JSON files
|
||||
{
|
||||
name: context.name + " JSON Handler",
|
||||
files: ["**/*.json"],
|
||||
handler: jsonHandler,
|
||||
},
|
||||
|
||||
// match only package.json
|
||||
{
|
||||
name: context.name + " package.json Handler",
|
||||
files: ["package.json"],
|
||||
handler: packageJsonHandler,
|
||||
},
|
||||
];
|
||||
},
|
||||
];
|
||||
```
|
||||
|
||||
When a config array is normalized, each function is executed and replaced in the config array with the return value.
|
||||
|
||||
**Note:** Config functions can also be async.
|
||||
|
||||
### Normalizing Config Arrays
|
||||
|
||||
Once a config array has been created and loaded with all of the raw config data, it must be normalized before it can be used. The normalization process goes through and flattens the config array as well as executing all config functions to get their final values.
|
||||
|
||||
To normalize a config array, call the `normalize()` method and pass in a context object:
|
||||
|
||||
```js
|
||||
await configs.normalize({
|
||||
name: "MyApp",
|
||||
});
|
||||
```
|
||||
|
||||
The `normalize()` method returns a promise, so be sure to use the `await` operator. The config array instance is normalized in-place, so you don't need to create a new variable.
|
||||
|
||||
If you want to disallow async config functions, you can call `normalizeSync()` instead. This method is completely synchronous and does not require using the `await` operator as it does not return a promise:
|
||||
|
||||
```js
|
||||
await configs.normalizeSync({
|
||||
name: "MyApp",
|
||||
});
|
||||
```
|
||||
|
||||
**Important:** Once a `ConfigArray` is normalized, it cannot be changed further. You can, however, create a new `ConfigArray` and pass in the normalized instance to create an unnormalized copy.
|
||||
|
||||
### Getting Config for a File
|
||||
|
||||
To get the config for a file, use the `getConfig()` method on a normalized config array and pass in the filename to get a config for:
|
||||
|
||||
```js
|
||||
// pass in filename
|
||||
const fileConfig = configs.getConfig(
|
||||
path.resolve(process.cwd(), "package.json"),
|
||||
);
|
||||
```
|
||||
|
||||
The config array always returns an object, even if there are no configs matching the given filename. You can then inspect the returned config object to determine how to proceed.
|
||||
|
||||
A few things to keep in mind:
|
||||
|
||||
- If a filename is not an absolute path, it will be resolved relative to the base path directory.
|
||||
- The returned config object never has `files`, `ignores`, `basePath`, or `name` properties; the only properties on the object will be the other configuration options specified.
|
||||
- The config array caches configs, so subsequent calls to `getConfig()` with the same filename will return in a fast lookup rather than another calculation.
|
||||
- A config will only be generated if the filename matches an entry in a `files` key. A config will not be generated without matching a `files` key (configs without a `files` key are only applied when another config with a `files` key is applied; configs without `files` are never applied on their own). Any config with a `files` key entry that is `*` or ends with `/**` or `/*` will only be applied if another entry in the same `files` key matches or another config matches.
|
||||
|
||||
## Determining Ignored Paths
|
||||
|
||||
You can determine if a file is ignored by using the `isFileIgnored()` method and passing in the path of any file, as in this example:
|
||||
|
||||
```js
|
||||
const ignored = configs.isFileIgnored("/foo/bar/baz.txt");
|
||||
```
|
||||
|
||||
A file is considered ignored if any of the following is true:
|
||||
|
||||
- **It's parent directory is ignored.** For example, if `foo` is in `ignores`, then `foo/a.js` is considered ignored.
|
||||
- **It has an ancestor directory that is ignored.** For example, if `foo` is in `ignores`, then `foo/baz/a.js` is considered ignored.
|
||||
- **It matches an ignored file pattern.** For example, if `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
|
||||
- **If it matches an entry in `files` and also in `ignores`.** For example, if `**/*.js` is in `files` and `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
|
||||
- **The file is outside the `basePath`.** If the `basePath` is `/usr/me`, then `/foo/a.js` is considered ignored.
|
||||
|
||||
For directories, use the `isDirectoryIgnored()` method and pass in the path of any directory, as in this example:
|
||||
|
||||
```js
|
||||
const ignored = configs.isDirectoryIgnored("/foo/bar/");
|
||||
```
|
||||
|
||||
A directory is considered ignored if any of the following is true:
|
||||
|
||||
- **It's parent directory is ignored.** For example, if `foo` is in `ignores`, then `foo/baz` is considered ignored.
|
||||
- **It has an ancestor directory that is ignored.** For example, if `foo` is in `ignores`, then `foo/bar/baz/a.js` is considered ignored.
|
||||
- **It matches and ignored file pattern.** For example, if `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
|
||||
- **If it matches an entry in `files` and also in `ignores`.** For example, if `**/*.js` is in `files` and `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
|
||||
- **The file is outside the `basePath`.** If the `basePath` is `/usr/me`, then `/foo/a.js` is considered ignored.
|
||||
|
||||
**Important:** A pattern such as `foo/**` means that `foo` and `foo/` are _not_ ignored whereas `foo/bar` is ignored. If you want to ignore `foo` and all of its subdirectories, use the pattern `foo` or `foo/` in `ignores`.
|
||||
|
||||
## Caching Mechanisms
|
||||
|
||||
Each `ConfigArray` aggressively caches configuration objects to avoid unnecessary work. This caching occurs in two ways:
|
||||
|
||||
1. **File-based Caching.** For each filename that is passed into a method, the resulting config is cached against that filename so you're always guaranteed to get the same object returned from `getConfig()` whenever you pass the same filename in.
|
||||
2. **Index-based Caching.** Whenever a config is calculated, the config elements that were used to create the config are also cached. So if a given filename matches elements 1, 5, and 7, the resulting config is cached with a key of `1,5,7`. That way, if another file is passed that matches the same config elements, the result is already known and doesn't have to be recalculated. That means two files that match all the same elements will return the same config from `getConfig()`.
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
The design of this project was influenced by feedback on the ESLint RFC, and incorporates ideas from:
|
||||
|
||||
- Teddy Katz (@not-an-aardvark)
|
||||
- Toru Nagashima (@mysticatea)
|
||||
- Kai Cataldo (@kaicataldo)
|
||||
|
||||
## License
|
||||
|
||||
Apache 2.0
|
||||
|
||||
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
|
||||
<!--sponsorsstart-->
|
||||
|
||||
## Sponsors
|
||||
|
||||
The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
|
||||
to get your logo on our READMEs and [website](https://eslint.org/sponsors).
|
||||
|
||||
<h3>Diamond Sponsors</h3>
|
||||
<p><a href="https://www.ag-grid.com/"><img src="https://images.opencollective.com/ag-grid/bec0580/logo.png" alt="AG Grid" height="128"></a></p><h3>Platinum Sponsors</h3>
|
||||
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/automattic/d0ef3e1/logo.png" alt="Automattic" height="128"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="128"></a></p><h3>Gold Sponsors</h3>
|
||||
<p><a href="https://qlty.sh/"><img src="https://images.opencollective.com/qltysh/33d157d/logo.png" alt="Qlty Software" height="96"></a> <a href="https://trunk.io/"><img src="https://images.opencollective.com/trunkio/fb92d60/avatar.png" alt="trunk.io" height="96"></a> <a href="https://shopify.engineering/"><img src="https://avatars.githubusercontent.com/u/8085" alt="Shopify" height="96"></a></p><h3>Silver Sponsors</h3>
|
||||
<p><a href="https://vite.dev/"><img src="https://images.opencollective.com/vite/e6d15e1/logo.png" alt="Vite" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a> <a href="https://americanexpress.io"><img src="https://avatars.githubusercontent.com/u/3853301" alt="American Express" height="64"></a> <a href="https://stackblitz.com"><img src="https://avatars.githubusercontent.com/u/28635252" alt="StackBlitz" height="64"></a></p><h3>Bronze Sponsors</h3>
|
||||
<p><a href="https://sentry.io"><img src="https://github.com/getsentry.png" alt="Sentry" height="32"></a> <a href="https://syntax.fm"><img src="https://github.com/syntaxfm.png" alt="Syntax" height="32"></a> <a href="https://cybozu.co.jp/"><img src="https://images.opencollective.com/cybozu/933e46d/logo.png" alt="Cybozu" height="32"></a> <a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="https://icons8.com/"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://www.gitbook.com"><img src="https://avatars.githubusercontent.com/u/7111340" alt="GitBook" height="32"></a> <a href="https://nolebase.ayaka.io"><img src="https://avatars.githubusercontent.com/u/11081491" alt="Neko" height="32"></a> <a href="https://nx.dev"><img src="https://avatars.githubusercontent.com/u/23692104" alt="Nx" height="32"></a> <a href="https://opensource.mercedes-benz.com/"><img src="https://avatars.githubusercontent.com/u/34240465" alt="Mercedes-Benz Group" height="32"></a> <a href="https://herocoders.com"><img src="https://avatars.githubusercontent.com/u/37549774" alt="HeroCoders" height="32"></a> <a href="https://www.lambdatest.com"><img src="https://avatars.githubusercontent.com/u/171592363" alt="LambdaTest" height="32"></a></p>
|
||||
<h3>Technology Sponsors</h3>
|
||||
Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work.
|
||||
<p><a href="https://netlify.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/netlify-icon.svg" alt="Netlify" height="32"></a> <a href="https://algolia.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/algolia-icon.svg" alt="Algolia" height="32"></a> <a href="https://1password.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/1password-icon.svg" alt="1Password" height="32"></a></p>
|
||||
<!--sponsorsend-->
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
{
|
||||
"name": "@eslint/config-array",
|
||||
"version": "0.21.0",
|
||||
"description": "General purpose glob-based configuration matching.",
|
||||
"author": "Nicholas C. Zakas",
|
||||
"type": "module",
|
||||
"main": "dist/esm/index.js",
|
||||
"types": "dist/esm/index.d.ts",
|
||||
"exports": {
|
||||
"require": {
|
||||
"types": "./dist/cjs/index.d.cts",
|
||||
"default": "./dist/cjs/index.cjs"
|
||||
},
|
||||
"import": {
|
||||
"types": "./dist/esm/index.d.ts",
|
||||
"default": "./dist/esm/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/eslint/rewrite.git",
|
||||
"directory": "packages/config-array"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/eslint/rewrite/issues"
|
||||
},
|
||||
"homepage": "https://github.com/eslint/rewrite/tree/main/packages/config-array#readme",
|
||||
"scripts": {
|
||||
"build:dedupe-types": "node ../../tools/dedupe-types.js dist/cjs/index.cjs dist/esm/index.js",
|
||||
"build:cts": "node ../../tools/build-cts.js dist/esm/index.d.ts dist/cjs/index.d.cts",
|
||||
"build:std__path": "rollup -c rollup.std__path-config.js && node fix-std__path-imports",
|
||||
"build": "rollup -c && npm run build:dedupe-types && tsc -p tsconfig.esm.json && npm run build:cts && npm run build:std__path",
|
||||
"test:jsr": "npx jsr@latest publish --dry-run",
|
||||
"pretest": "npm run build",
|
||||
"test": "mocha tests/",
|
||||
"test:coverage": "c8 npm test"
|
||||
},
|
||||
"keywords": [
|
||||
"configuration",
|
||||
"configarray",
|
||||
"config file"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@eslint/object-schema": "^2.1.6",
|
||||
"debug": "^4.3.1",
|
||||
"minimatch": "^3.1.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@jsr/std__path": "^1.0.4",
|
||||
"@types/minimatch": "^3.0.5",
|
||||
"rollup-plugin-copy": "^3.5.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
}
|
||||
}
|
||||
-201
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
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
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
-98
@@ -1,98 +0,0 @@
|
||||
# @eslint/config-helpers
|
||||
|
||||
## Description
|
||||
|
||||
Helper utilities for creating ESLint configuration.
|
||||
|
||||
## Installation
|
||||
|
||||
For Node.js and compatible runtimes:
|
||||
|
||||
```shell
|
||||
npm install @eslint/config-helpers
|
||||
# or
|
||||
yarn add @eslint/config-helpers
|
||||
# or
|
||||
pnpm install @eslint/config-helpers
|
||||
# or
|
||||
bun add @eslint/config-helpers
|
||||
```
|
||||
|
||||
For Deno:
|
||||
|
||||
```shell
|
||||
deno add @eslint/config-helpers
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### `defineConfig()`
|
||||
|
||||
The `defineConfig()` function allows you to specify an ESLint configuration with full type checking and additional capabilities, such as `extends`. Here's an example:
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import { defineConfig } from "@eslint/config-helpers";
|
||||
import js from "@eslint/js";
|
||||
|
||||
export default defineConfig([
|
||||
{
|
||||
files: ["src/**/*.js"],
|
||||
plugins: { js },
|
||||
extends: ["js/recommended"],
|
||||
rules: {
|
||||
semi: "error",
|
||||
"prefer-const": "error",
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ["test/**/*.js"],
|
||||
rules: {
|
||||
"no-console": "off",
|
||||
},
|
||||
},
|
||||
]);
|
||||
```
|
||||
|
||||
### `globalIgnores()`
|
||||
|
||||
The `globalIgnores()` function allows you to specify patterns for files and directories that should be globally ignored by ESLint. This is useful for excluding files that you don't want to lint, such as build directories or third-party libraries. Here's an example:
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import { defineConfig, globalIgnores } from "@eslint/config-helpers";
|
||||
|
||||
export default defineConfig([
|
||||
{
|
||||
files: ["src/**/*.js"],
|
||||
rules: {
|
||||
semi: "error",
|
||||
"prefer-const": "error",
|
||||
},
|
||||
},
|
||||
globalIgnores(["node_modules/", "dist/", "coverage/"]),
|
||||
]);
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
Apache 2.0
|
||||
|
||||
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
|
||||
<!--sponsorsstart-->
|
||||
|
||||
## Sponsors
|
||||
|
||||
The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
|
||||
to get your logo on our READMEs and [website](https://eslint.org/sponsors).
|
||||
|
||||
<h3>Diamond Sponsors</h3>
|
||||
<p><a href="https://www.ag-grid.com/"><img src="https://images.opencollective.com/ag-grid/bec0580/logo.png" alt="AG Grid" height="128"></a></p><h3>Platinum Sponsors</h3>
|
||||
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/automattic/d0ef3e1/logo.png" alt="Automattic" height="128"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="128"></a></p><h3>Gold Sponsors</h3>
|
||||
<p><a href="https://qlty.sh/"><img src="https://images.opencollective.com/qltysh/33d157d/logo.png" alt="Qlty Software" height="96"></a> <a href="https://trunk.io/"><img src="https://images.opencollective.com/trunkio/fb92d60/avatar.png" alt="trunk.io" height="96"></a> <a href="https://shopify.engineering/"><img src="https://avatars.githubusercontent.com/u/8085" alt="Shopify" height="96"></a></p><h3>Silver Sponsors</h3>
|
||||
<p><a href="https://vite.dev/"><img src="https://images.opencollective.com/vite/e6d15e1/logo.png" alt="Vite" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a> <a href="https://americanexpress.io"><img src="https://avatars.githubusercontent.com/u/3853301" alt="American Express" height="64"></a> <a href="https://stackblitz.com"><img src="https://avatars.githubusercontent.com/u/28635252" alt="StackBlitz" height="64"></a></p><h3>Bronze Sponsors</h3>
|
||||
<p><a href="https://sentry.io"><img src="https://github.com/getsentry.png" alt="Sentry" height="32"></a> <a href="https://syntax.fm"><img src="https://github.com/syntaxfm.png" alt="Syntax" height="32"></a> <a href="https://cybozu.co.jp/"><img src="https://images.opencollective.com/cybozu/933e46d/logo.png" alt="Cybozu" height="32"></a> <a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="https://icons8.com/"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://www.gitbook.com"><img src="https://avatars.githubusercontent.com/u/7111340" alt="GitBook" height="32"></a> <a href="https://nolebase.ayaka.io"><img src="https://avatars.githubusercontent.com/u/11081491" alt="Neko" height="32"></a> <a href="https://nx.dev"><img src="https://avatars.githubusercontent.com/u/23692104" alt="Nx" height="32"></a> <a href="https://opensource.mercedes-benz.com/"><img src="https://avatars.githubusercontent.com/u/34240465" alt="Mercedes-Benz Group" height="32"></a> <a href="https://herocoders.com"><img src="https://avatars.githubusercontent.com/u/37549774" alt="HeroCoders" height="32"></a> <a href="https://www.lambdatest.com"><img src="https://avatars.githubusercontent.com/u/171592363" alt="LambdaTest" height="32"></a></p>
|
||||
<h3>Technology Sponsors</h3>
|
||||
Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work.
|
||||
<p><a href="https://netlify.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/netlify-icon.svg" alt="Netlify" height="32"></a> <a href="https://algolia.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/algolia-icon.svg" alt="Algolia" height="32"></a> <a href="https://1password.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/1password-icon.svg" alt="1Password" height="32"></a></p>
|
||||
<!--sponsorsend-->
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
{
|
||||
"name": "@eslint/config-helpers",
|
||||
"version": "0.3.0",
|
||||
"description": "Helper utilities for creating ESLint configuration",
|
||||
"type": "module",
|
||||
"main": "dist/esm/index.js",
|
||||
"types": "dist/esm/index.d.ts",
|
||||
"exports": {
|
||||
"require": {
|
||||
"types": "./dist/cjs/index.d.cts",
|
||||
"default": "./dist/cjs/index.cjs"
|
||||
},
|
||||
"import": {
|
||||
"types": "./dist/esm/index.d.ts",
|
||||
"default": "./dist/esm/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"directories": {
|
||||
"test": "tests"
|
||||
},
|
||||
"scripts": {
|
||||
"build:dedupe-types": "node ../../tools/dedupe-types.js dist/cjs/index.cjs dist/esm/index.js",
|
||||
"build:cts": "node ../../tools/build-cts.js dist/esm/index.d.ts dist/cjs/index.d.cts",
|
||||
"build": "rollup -c && npm run build:dedupe-types && tsc -p tsconfig.esm.json && npm run build:cts",
|
||||
"test:jsr": "npx jsr@latest publish --dry-run",
|
||||
"test": "mocha tests/*.js",
|
||||
"test:coverage": "c8 npm test",
|
||||
"test:types": "tsc -p tests/types/tsconfig.json"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/eslint/rewrite.git",
|
||||
"directory": "packages/config-helpers"
|
||||
},
|
||||
"keywords": [
|
||||
"eslint"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"bugs": {
|
||||
"url": "https://github.com/eslint/rewrite/issues"
|
||||
},
|
||||
"homepage": "https://github.com/eslint/rewrite/tree/main/packages/config-helpers#readme",
|
||||
"devDependencies": {
|
||||
"@eslint/core": "^0.15.1",
|
||||
"eslint": "^9.27.0",
|
||||
"rollup-plugin-copy": "^3.5.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
}
|
||||
}
|
||||
-201
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
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
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
# ESLint Core
|
||||
|
||||
## Overview
|
||||
|
||||
This package is the future home of the rewritten, runtime-agnostic ESLint core.
|
||||
|
||||
Right now, it exports the core types necessary to implement language plugins.
|
||||
|
||||
## License
|
||||
|
||||
Apache 2.0
|
||||
|
||||
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
|
||||
<!--sponsorsstart-->
|
||||
|
||||
## Sponsors
|
||||
|
||||
The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
|
||||
to get your logo on our READMEs and [website](https://eslint.org/sponsors).
|
||||
|
||||
<h3>Diamond Sponsors</h3>
|
||||
<p><a href="https://www.ag-grid.com/"><img src="https://images.opencollective.com/ag-grid/bec0580/logo.png" alt="AG Grid" height="128"></a></p><h3>Platinum Sponsors</h3>
|
||||
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/automattic/d0ef3e1/logo.png" alt="Automattic" height="128"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="128"></a></p><h3>Gold Sponsors</h3>
|
||||
<p><a href="https://qlty.sh/"><img src="https://images.opencollective.com/qltysh/33d157d/logo.png" alt="Qlty Software" height="96"></a> <a href="https://trunk.io/"><img src="https://images.opencollective.com/trunkio/fb92d60/avatar.png" alt="trunk.io" height="96"></a> <a href="https://shopify.engineering/"><img src="https://avatars.githubusercontent.com/u/8085" alt="Shopify" height="96"></a></p><h3>Silver Sponsors</h3>
|
||||
<p><a href="https://vite.dev/"><img src="https://images.opencollective.com/vite/e6d15e1/logo.png" alt="Vite" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a> <a href="https://americanexpress.io"><img src="https://avatars.githubusercontent.com/u/3853301" alt="American Express" height="64"></a> <a href="https://stackblitz.com"><img src="https://avatars.githubusercontent.com/u/28635252" alt="StackBlitz" height="64"></a></p><h3>Bronze Sponsors</h3>
|
||||
<p><a href="https://sentry.io"><img src="https://github.com/getsentry.png" alt="Sentry" height="32"></a> <a href="https://syntax.fm"><img src="https://github.com/syntaxfm.png" alt="Syntax" height="32"></a> <a href="https://cybozu.co.jp/"><img src="https://images.opencollective.com/cybozu/933e46d/logo.png" alt="Cybozu" height="32"></a> <a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="https://icons8.com/"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://www.gitbook.com"><img src="https://avatars.githubusercontent.com/u/7111340" alt="GitBook" height="32"></a> <a href="https://nolebase.ayaka.io"><img src="https://avatars.githubusercontent.com/u/11081491" alt="Neko" height="32"></a> <a href="https://nx.dev"><img src="https://avatars.githubusercontent.com/u/23692104" alt="Nx" height="32"></a> <a href="https://opensource.mercedes-benz.com/"><img src="https://avatars.githubusercontent.com/u/34240465" alt="Mercedes-Benz Group" height="32"></a> <a href="https://herocoders.com"><img src="https://avatars.githubusercontent.com/u/37549774" alt="HeroCoders" height="32"></a> <a href="https://www.lambdatest.com"><img src="https://avatars.githubusercontent.com/u/171592363" alt="LambdaTest" height="32"></a></p>
|
||||
<h3>Technology Sponsors</h3>
|
||||
Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work.
|
||||
<p><a href="https://netlify.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/netlify-icon.svg" alt="Netlify" height="32"></a> <a href="https://algolia.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/algolia-icon.svg" alt="Algolia" height="32"></a> <a href="https://1password.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/1password-icon.svg" alt="1Password" height="32"></a></p>
|
||||
<!--sponsorsend-->
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
{
|
||||
"name": "@eslint/core",
|
||||
"version": "0.15.1",
|
||||
"description": "Runtime-agnostic core of ESLint",
|
||||
"type": "module",
|
||||
"types": "./dist/esm/types.d.ts",
|
||||
"exports": {
|
||||
"types": {
|
||||
"import": "./dist/esm/types.d.ts",
|
||||
"require": "./dist/cjs/types.d.cts"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"build:cts": "node -e \"fs.cpSync('dist/esm/types.d.ts', 'dist/cjs/types.d.cts')\"",
|
||||
"build": "tsc && npm run build:cts",
|
||||
"test:jsr": "npx jsr@latest publish --dry-run",
|
||||
"test:types": "tsc -p tests/types/tsconfig.json"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/eslint/rewrite.git",
|
||||
"directory": "packages/core"
|
||||
},
|
||||
"keywords": [
|
||||
"eslint",
|
||||
"core"
|
||||
],
|
||||
"author": "Nicholas C. Zakas",
|
||||
"license": "Apache-2.0",
|
||||
"bugs": {
|
||||
"url": "https://github.com/eslint/rewrite/issues"
|
||||
},
|
||||
"homepage": "https://github.com/eslint/rewrite/tree/main/packages/core#readme",
|
||||
"dependencies": {
|
||||
"@types/json-schema": "^7.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"json-schema": "^0.4.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
}
|
||||
}
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
Copyright (C) 2016-2024 by Roman Dvornov
|
||||
Copyright OpenJS Foundation and other contributors, <www.openjsf.org>
|
||||
|
||||
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.
|
||||
-194
@@ -1,194 +0,0 @@
|
||||
<img align="right" width="111" height="111" alt="CSSTree logo" src="assets/csstree-logo-rounded.svg" />
|
||||
|
||||
# CSSTree (ESLint Fork)
|
||||
|
||||
CSSTree is a tool set for CSS: [fast](https://github.com/postcss/benchmark) detailed parser (CSS → AST), walker (AST traversal), generator (AST → CSS) and lexer (validation and matching) based on specs and browser implementations. The main goal is to be efficient and W3C spec compliant, with focus on CSS analyzing and source-to-source transforming tasks.
|
||||
|
||||
## Features
|
||||
|
||||
- **Detailed parsing with an adjustable level of detail**
|
||||
|
||||
By default CSSTree parses CSS as detailed as possible, i.e. each single logical part is representing with its own AST node (see [AST format](docs/ast.md) for all possible node types). The parsing detail level can be changed through [parser options](docs/parsing.md#parsesource-options), for example, you can disable parsing of selectors or declaration values for component parts.
|
||||
|
||||
- **Tolerant to errors by design**
|
||||
|
||||
Parser behaves as [spec says](https://www.w3.org/TR/css-syntax-3/#error-handling): "When errors occur in CSS, the parser attempts to recover gracefully, throwing away only the minimum amount of content before returning to parsing as normal". The only thing the parser departs from the specification is that it doesn't throw away bad content, but wraps it in a special node type (`Raw`) that allows processing it later.
|
||||
|
||||
- **Fast and efficient**
|
||||
|
||||
CSSTree is created with focus on performance and effective memory consumption. Therefore it's [one of the fastest CSS parsers](https://github.com/postcss/benchmark) at the moment.
|
||||
|
||||
- **Syntax validation**
|
||||
|
||||
The built-in lexer can test CSS against syntaxes defined by W3C. CSSTree uses [mdn/data](https://github.com/mdn/data/) as a basis for lexer's dictionaries and extends it with vendor specific and legacy syntaxes. Lexer can only check the declaration values and at-rules currently, but this feature will be extended to other parts of the CSS in the future.
|
||||
|
||||
## Projects using CSSTree
|
||||
|
||||
- [Svelte](https://github.com/sveltejs/svelte) – Cybernetically enhanced web apps
|
||||
- [SVGO](https://github.com/svg/svgo) – Node.js tool for optimizing SVG files
|
||||
- [CSSO](https://github.com/css/csso) – CSS minifier with structural optimizations
|
||||
- [NativeScript](https://github.com/NativeScript/NativeScript) – NativeScript empowers you to access native APIs from JavaScript directly
|
||||
- [react-native-svg](https://github.com/react-native-svg/react-native-svg) – SVG library for React Native, React Native Web, and plain React web projects
|
||||
- [penthouse](https://github.com/pocketjoso/penthouse) – Critical Path CSS Generator
|
||||
- [Bit](https://github.com/teambit/bit) – Bit is the platform for collaborating on components
|
||||
- and more...
|
||||
|
||||
## Documentation
|
||||
|
||||
- [AST format](docs/ast.md)
|
||||
- [Parsing CSS → AST](docs/parsing.md)
|
||||
- [parse(source[, options])](docs/parsing.md#parsesource-options)
|
||||
- [Serialization AST → CSS](docs/generate.md)
|
||||
- [generate(ast[, options])](docs/generate.md#generateast-options)
|
||||
- [AST traversal](docs/traversal.md)
|
||||
- [walk(ast, options)](docs/traversal.md#walkast-options)
|
||||
- [find(ast, fn)](docs/traversal.md#findast-fn)
|
||||
- [findLast(ast, fn)](docs/traversal.md#findlastast-fn)
|
||||
- [findAll(ast, fn)](docs/traversal.md#findallast-fn)
|
||||
- [Util functions](docs/utils.md)
|
||||
- Value encoding & decoding
|
||||
- [property(name)](docs/utils.md#propertyname)
|
||||
- [keyword(name)](docs/utils.md#keywordname)
|
||||
- [ident](docs/utils.md#ident)
|
||||
- [string](docs/utils.md#string)
|
||||
- [url](docs/utils.md#url)
|
||||
- [List class](docs/list.md)
|
||||
- AST transforming
|
||||
- [clone(ast)](docs/utils.md#cloneast)
|
||||
- [fromPlainObject(object)](docs/utils.md#fromplainobjectobject)
|
||||
- [toPlainObject(ast)](docs/utils.md#toplainobjectast)
|
||||
- [Value Definition Syntax](docs/definition-syntax.md)
|
||||
- [parse(source)](docs/definition-syntax.md#parsesource)
|
||||
- [walk(node, options, context)](docs/definition-syntax.md#walknode-options-context)
|
||||
- [generate(node, options)](docs/definition-syntax.md#generatenode-options)
|
||||
- [AST format](docs/definition-syntax.md#ast-format)
|
||||
|
||||
## Tools
|
||||
|
||||
* [AST Explorer](https://astexplorer.net/#/gist/244e2fb4da940df52bf0f4b94277db44/e79aff44611020b22cfd9708f3a99ce09b7d67a8) – explore CSSTree AST format with zero setup
|
||||
* [CSS syntax reference](https://csstree.github.io/docs/syntax.html)
|
||||
* [CSS syntax validator](https://csstree.github.io/docs/validator.html)
|
||||
|
||||
## Related projects
|
||||
|
||||
* [csstree-validator](https://github.com/csstree/validator) – NPM package to validate CSS
|
||||
* [stylelint-csstree-validator](https://github.com/csstree/stylelint-validator) – plugin for stylelint to validate CSS
|
||||
* [Grunt plugin](https://github.com/sergejmueller/grunt-csstree-validator)
|
||||
* [Gulp plugin](https://github.com/csstree/gulp-csstree)
|
||||
* [Sublime plugin](https://github.com/csstree/SublimeLinter-contrib-csstree)
|
||||
* [VS Code plugin](https://github.com/csstree/vscode-plugin)
|
||||
* [Atom plugin](https://github.com/csstree/atom-plugin)
|
||||
|
||||
## Usage
|
||||
|
||||
Install with npm:
|
||||
|
||||
```
|
||||
npm install @eslint/css-tree
|
||||
```
|
||||
|
||||
Basic usage:
|
||||
|
||||
```js
|
||||
import * as csstree from '@eslint/css-tree';
|
||||
|
||||
// parse CSS to AST
|
||||
const ast = csstree.parse('.example { world: "!" }');
|
||||
|
||||
// traverse AST and modify it
|
||||
csstree.walk(ast, (node) => {
|
||||
if (node.type === 'ClassSelector' && node.name === 'example') {
|
||||
node.name = 'hello';
|
||||
}
|
||||
});
|
||||
|
||||
// generate CSS from AST
|
||||
console.log(csstree.generate(ast));
|
||||
// .hello{world:"!"}
|
||||
```
|
||||
|
||||
Syntax matching:
|
||||
|
||||
```js
|
||||
// parse CSS to AST as a declaration value
|
||||
const ast = csstree.parse('red 1px solid', { context: 'value' });
|
||||
|
||||
// match to syntax of `border` property
|
||||
const matchResult = csstree.lexer.matchProperty('border', ast);
|
||||
|
||||
// check first value node is a <color>
|
||||
console.log(matchResult.isType(ast.children.first, 'color'));
|
||||
// true
|
||||
|
||||
// get a type list matched to a node
|
||||
console.log(matchResult.getTrace(ast.children.first));
|
||||
// [ { type: 'Property', name: 'border' },
|
||||
// { type: 'Type', name: 'color' },
|
||||
// { type: 'Type', name: 'named-color' },
|
||||
// { type: 'Keyword', name: 'red' } ]
|
||||
```
|
||||
|
||||
### Exports
|
||||
|
||||
Is it possible to import just a needed part of library like a parser or a walker. That's might useful for loading time or bundle size optimisations.
|
||||
|
||||
```js
|
||||
import * as tokenizer from '@eslint/css-tree/tokenizer';
|
||||
import * as parser from '@eslint/css-tree/parser';
|
||||
import * as walker from '@eslint/css-tree/walker';
|
||||
import * as lexer from '@eslint/css-tree/lexer';
|
||||
import * as definitionSyntax from '@eslint/css-tree/definition-syntax';
|
||||
import * as data from '@eslint/css-tree/definition-syntax-data';
|
||||
import * as dataPatch from '@eslint/css-tree/definition-syntax-data-patch';
|
||||
import * as utils from '@eslint/css-tree/utils';
|
||||
```
|
||||
|
||||
### Using in a browser
|
||||
|
||||
Bundles are available for use in a browser:
|
||||
|
||||
- `dist/csstree.js` – minified IIFE with `csstree` as global
|
||||
```html
|
||||
<script src="node_modules/@eslint/css-tree/dist/csstree.js"></script>
|
||||
<script>
|
||||
csstree.parse('.example { color: green }');
|
||||
</script>
|
||||
```
|
||||
|
||||
- `dist/csstree.esm.js` – minified ES module
|
||||
```html
|
||||
<script type="module">
|
||||
import { parse } from 'node_modules/@eslint/css-tree/dist/csstree.esm.js'
|
||||
parse('.example { color: green }');
|
||||
</script>
|
||||
```
|
||||
|
||||
One of CDN services like `unpkg` or `jsDelivr` can be used. By default (for short path) a ESM version is exposing. For IIFE version a full path to a bundle should be specified:
|
||||
|
||||
```html
|
||||
<!-- ESM -->
|
||||
<script type="module">
|
||||
import * as csstree from 'https://cdn.jsdelivr.net/npm/@eslint/css-tree';
|
||||
import * as csstree from 'https://unpkg.com/@eslint/css-tree';
|
||||
</script>
|
||||
|
||||
<!-- IIFE with an export to global -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/@eslint/css-tree/dist/csstree.js"></script>
|
||||
<script src="https://unpkg.com/@eslint/css-tree/dist/csstree.js"></script>
|
||||
```
|
||||
|
||||
## Top level API
|
||||
|
||||

|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
|
||||
|
||||
## Branch Setup and Development
|
||||
|
||||
* `main` - the default branch for new development in the fork repo
|
||||
* `upstream` - kept in sync with `csstree/csstree`
|
||||
|
||||
When merging in changes from `csstree/csstree`, sync `upstream` in the GitHub UI (if possible). Then send a pull request to `main` to work through any merge conflicts.
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const List = require('../utils/List.cjs');
|
||||
|
||||
function createConvertor(walk) {
|
||||
return {
|
||||
fromPlainObject(ast) {
|
||||
walk(ast, {
|
||||
enter(node) {
|
||||
if (node.children && node.children instanceof List.List === false) {
|
||||
node.children = new List.List().fromArray(node.children);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return ast;
|
||||
},
|
||||
toPlainObject(ast) {
|
||||
walk(ast, {
|
||||
leave(node) {
|
||||
if (node.children && node.children instanceof List.List) {
|
||||
node.children = node.children.toArray();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return ast;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
exports.createConvertor = createConvertor;
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const create = require('./create.cjs');
|
||||
const index$1 = require('../walker/index.cjs');
|
||||
|
||||
const index = create.createConvertor(index$1);
|
||||
|
||||
module.exports = index;
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const patch = require('../data/patch.json');
|
||||
|
||||
const patch$1 = patch;
|
||||
|
||||
module.exports = patch$1;
|
||||
-120
@@ -1,120 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const dataPatch = require('./data-patch.cjs');
|
||||
|
||||
const mdnAtrules = require('mdn-data/css/at-rules.json');
|
||||
const mdnProperties = require('mdn-data/css/properties.json');
|
||||
const mdnSyntaxes = require('mdn-data/css/syntaxes.json');
|
||||
|
||||
const hasOwn = Object.hasOwn || ((object, property) => Object.prototype.hasOwnProperty.call(object, property));
|
||||
const extendSyntax = /^\s*\|\s*/;
|
||||
|
||||
function preprocessAtrules(dict) {
|
||||
const result = Object.create(null);
|
||||
|
||||
for (const [atruleName, atrule] of Object.entries(dict)) {
|
||||
let descriptors = null;
|
||||
|
||||
if (atrule.descriptors) {
|
||||
descriptors = Object.create(null);
|
||||
|
||||
for (const [name, descriptor] of Object.entries(atrule.descriptors)) {
|
||||
descriptors[name] = descriptor.syntax;
|
||||
}
|
||||
}
|
||||
|
||||
result[atruleName.substr(1)] = {
|
||||
prelude: atrule.syntax.trim().replace(/\{(.|\s)+\}/, '').match(/^@\S+\s+([^;\{]*)/)[1].trim() || null,
|
||||
descriptors
|
||||
};
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function patchDictionary(dict, patchDict) {
|
||||
const result = Object.create(null);
|
||||
|
||||
// copy all syntaxes for an original dict
|
||||
for (const [key, value] of Object.entries(dict)) {
|
||||
if (value) {
|
||||
result[key] = value.syntax || value;
|
||||
}
|
||||
}
|
||||
|
||||
// apply a patch
|
||||
for (const key of Object.keys(patchDict)) {
|
||||
if (hasOwn(dict, key)) {
|
||||
if (patchDict[key].syntax) {
|
||||
result[key] = extendSyntax.test(patchDict[key].syntax)
|
||||
? result[key] + ' ' + patchDict[key].syntax.trim()
|
||||
: patchDict[key].syntax;
|
||||
} else {
|
||||
delete result[key];
|
||||
}
|
||||
} else {
|
||||
if (patchDict[key].syntax) {
|
||||
result[key] = patchDict[key].syntax.replace(extendSyntax, '');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function preprocessPatchAtrulesDescritors(declarations) {
|
||||
const result = {};
|
||||
|
||||
for (const [key, value] of Object.entries(declarations || {})) {
|
||||
result[key] = typeof value === 'string'
|
||||
? { syntax: value }
|
||||
: value;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function patchAtrules(dict, patchDict) {
|
||||
const result = {};
|
||||
|
||||
// copy all syntaxes for an original dict
|
||||
for (const key in dict) {
|
||||
if (patchDict[key] === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const atrulePatch = patchDict[key] || {};
|
||||
|
||||
result[key] = {
|
||||
prelude: key in patchDict && 'prelude' in atrulePatch
|
||||
? atrulePatch.prelude
|
||||
: dict[key].prelude || null,
|
||||
descriptors: patchDictionary(
|
||||
dict[key].descriptors || {},
|
||||
preprocessPatchAtrulesDescritors(atrulePatch.descriptors)
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
// apply a patch
|
||||
for (const [key, atrulePatch] of Object.entries(patchDict)) {
|
||||
if (atrulePatch && !hasOwn(dict, key)) {
|
||||
result[key] = {
|
||||
prelude: atrulePatch.prelude || null,
|
||||
descriptors: atrulePatch.descriptors
|
||||
? patchDictionary({}, preprocessPatchAtrulesDescritors(atrulePatch.descriptors))
|
||||
: null
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
const definitions = {
|
||||
types: patchDictionary(mdnSyntaxes, dataPatch.types),
|
||||
atrules: patchAtrules(preprocessAtrules(mdnAtrules), dataPatch.atrules),
|
||||
properties: patchDictionary(mdnProperties, dataPatch.properties)
|
||||
};
|
||||
|
||||
module.exports = definitions;
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const createCustomError = require('../utils/create-custom-error.cjs');
|
||||
|
||||
function SyntaxError(message, input, offset) {
|
||||
return Object.assign(createCustomError.createCustomError('SyntaxError', message), {
|
||||
input,
|
||||
offset,
|
||||
rawMessage: message,
|
||||
message: message + '\n' +
|
||||
' ' + input + '\n' +
|
||||
'--' + new Array((offset || input.length) + 1).join('-') + '^'
|
||||
});
|
||||
}
|
||||
|
||||
exports.SyntaxError = SyntaxError;
|
||||
-139
@@ -1,139 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
function noop(value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
function generateMultiplier(multiplier) {
|
||||
const { min, max, comma } = multiplier;
|
||||
|
||||
if (min === 0 && max === 0) {
|
||||
return comma ? '#?' : '*';
|
||||
}
|
||||
|
||||
if (min === 0 && max === 1) {
|
||||
return '?';
|
||||
}
|
||||
|
||||
if (min === 1 && max === 0) {
|
||||
return comma ? '#' : '+';
|
||||
}
|
||||
|
||||
if (min === 1 && max === 1) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return (
|
||||
(comma ? '#' : '') +
|
||||
(min === max
|
||||
? '{' + min + '}'
|
||||
: '{' + min + ',' + (max !== 0 ? max : '') + '}'
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function generateTypeOpts(node) {
|
||||
switch (node.type) {
|
||||
case 'Range':
|
||||
return (
|
||||
' [' +
|
||||
(node.min === null ? '-∞' : node.min) +
|
||||
',' +
|
||||
(node.max === null ? '∞' : node.max) +
|
||||
']'
|
||||
);
|
||||
|
||||
default:
|
||||
throw new Error('Unknown node type `' + node.type + '`');
|
||||
}
|
||||
}
|
||||
|
||||
function generateSequence(node, decorate, forceBraces, compact) {
|
||||
const combinator = node.combinator === ' ' || compact ? node.combinator : ' ' + node.combinator + ' ';
|
||||
const result = node.terms
|
||||
.map(term => internalGenerate(term, decorate, forceBraces, compact))
|
||||
.join(combinator);
|
||||
|
||||
if (node.explicit || forceBraces) {
|
||||
return (compact || result[0] === ',' ? '[' : '[ ') + result + (compact ? ']' : ' ]');
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function internalGenerate(node, decorate, forceBraces, compact) {
|
||||
let result;
|
||||
|
||||
switch (node.type) {
|
||||
case 'Group':
|
||||
result =
|
||||
generateSequence(node, decorate, forceBraces, compact) +
|
||||
(node.disallowEmpty ? '!' : '');
|
||||
break;
|
||||
|
||||
case 'Multiplier':
|
||||
// return since node is a composition
|
||||
return (
|
||||
internalGenerate(node.term, decorate, forceBraces, compact) +
|
||||
decorate(generateMultiplier(node), node)
|
||||
);
|
||||
|
||||
case 'Boolean':
|
||||
result = '<boolean-expr[' + internalGenerate(node.term, decorate, forceBraces, compact) + ']>';
|
||||
break;
|
||||
|
||||
case 'Type':
|
||||
result = '<' + node.name + (node.opts ? decorate(generateTypeOpts(node.opts), node.opts) : '') + '>';
|
||||
break;
|
||||
|
||||
case 'Property':
|
||||
result = '<\'' + node.name + '\'>';
|
||||
break;
|
||||
|
||||
case 'Keyword':
|
||||
result = node.name;
|
||||
break;
|
||||
|
||||
case 'AtKeyword':
|
||||
result = '@' + node.name;
|
||||
break;
|
||||
|
||||
case 'Function':
|
||||
result = node.name + '(';
|
||||
break;
|
||||
|
||||
case 'String':
|
||||
case 'Token':
|
||||
result = node.value;
|
||||
break;
|
||||
|
||||
case 'Comma':
|
||||
result = ',';
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error('Unknown node type `' + node.type + '`');
|
||||
}
|
||||
|
||||
return decorate(result, node);
|
||||
}
|
||||
|
||||
function generate(node, options) {
|
||||
let decorate = noop;
|
||||
let forceBraces = false;
|
||||
let compact = false;
|
||||
|
||||
if (typeof options === 'function') {
|
||||
decorate = options;
|
||||
} else if (options) {
|
||||
forceBraces = Boolean(options.forceBraces);
|
||||
compact = Boolean(options.compact);
|
||||
if (typeof options.decorate === 'function') {
|
||||
decorate = options.decorate;
|
||||
}
|
||||
}
|
||||
|
||||
return internalGenerate(node, decorate, forceBraces, compact);
|
||||
}
|
||||
|
||||
exports.generate = generate;
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const SyntaxError = require('./SyntaxError.cjs');
|
||||
const generate = require('./generate.cjs');
|
||||
const parse = require('./parse.cjs');
|
||||
const walk = require('./walk.cjs');
|
||||
|
||||
|
||||
|
||||
exports.SyntaxError = SyntaxError.SyntaxError;
|
||||
exports.generate = generate.generate;
|
||||
exports.parse = parse.parse;
|
||||
exports.walk = walk.walk;
|
||||
-556
@@ -1,556 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const scanner = require('./scanner.cjs');
|
||||
|
||||
const TAB = 9;
|
||||
const N = 10;
|
||||
const F = 12;
|
||||
const R = 13;
|
||||
const SPACE = 32;
|
||||
const EXCLAMATIONMARK = 33; // !
|
||||
const NUMBERSIGN = 35; // #
|
||||
const AMPERSAND = 38; // &
|
||||
const APOSTROPHE = 39; // '
|
||||
const LEFTPARENTHESIS = 40; // (
|
||||
const RIGHTPARENTHESIS = 41; // )
|
||||
const ASTERISK = 42; // *
|
||||
const PLUSSIGN = 43; // +
|
||||
const COMMA = 44; // ,
|
||||
const HYPERMINUS = 45; // -
|
||||
const LESSTHANSIGN = 60; // <
|
||||
const GREATERTHANSIGN = 62; // >
|
||||
const QUESTIONMARK = 63; // ?
|
||||
const COMMERCIALAT = 64; // @
|
||||
const LEFTSQUAREBRACKET = 91; // [
|
||||
const RIGHTSQUAREBRACKET = 93; // ]
|
||||
const LEFTCURLYBRACKET = 123; // {
|
||||
const VERTICALLINE = 124; // |
|
||||
const RIGHTCURLYBRACKET = 125; // }
|
||||
const INFINITY = 8734; // ∞
|
||||
const COMBINATOR_PRECEDENCE = {
|
||||
' ': 1,
|
||||
'&&': 2,
|
||||
'||': 3,
|
||||
'|': 4
|
||||
};
|
||||
|
||||
function readMultiplierRange(scanner) {
|
||||
let min = null;
|
||||
let max = null;
|
||||
|
||||
scanner.eat(LEFTCURLYBRACKET);
|
||||
scanner.skipWs();
|
||||
|
||||
min = scanner.scanNumber(scanner);
|
||||
scanner.skipWs();
|
||||
|
||||
if (scanner.charCode() === COMMA) {
|
||||
scanner.pos++;
|
||||
scanner.skipWs();
|
||||
|
||||
if (scanner.charCode() !== RIGHTCURLYBRACKET) {
|
||||
max = scanner.scanNumber(scanner);
|
||||
scanner.skipWs();
|
||||
}
|
||||
} else {
|
||||
max = min;
|
||||
}
|
||||
|
||||
scanner.eat(RIGHTCURLYBRACKET);
|
||||
|
||||
return {
|
||||
min: Number(min),
|
||||
max: max ? Number(max) : 0
|
||||
};
|
||||
}
|
||||
|
||||
function readMultiplier(scanner) {
|
||||
let range = null;
|
||||
let comma = false;
|
||||
|
||||
switch (scanner.charCode()) {
|
||||
case ASTERISK:
|
||||
scanner.pos++;
|
||||
|
||||
range = {
|
||||
min: 0,
|
||||
max: 0
|
||||
};
|
||||
|
||||
break;
|
||||
|
||||
case PLUSSIGN:
|
||||
scanner.pos++;
|
||||
|
||||
range = {
|
||||
min: 1,
|
||||
max: 0
|
||||
};
|
||||
|
||||
break;
|
||||
|
||||
case QUESTIONMARK:
|
||||
scanner.pos++;
|
||||
|
||||
range = {
|
||||
min: 0,
|
||||
max: 1
|
||||
};
|
||||
|
||||
break;
|
||||
|
||||
case NUMBERSIGN:
|
||||
scanner.pos++;
|
||||
|
||||
comma = true;
|
||||
|
||||
if (scanner.charCode() === LEFTCURLYBRACKET) {
|
||||
range = readMultiplierRange(scanner);
|
||||
} else if (scanner.charCode() === QUESTIONMARK) {
|
||||
// https://www.w3.org/TR/css-values-4/#component-multipliers
|
||||
// > the # and ? multipliers may be stacked as #?
|
||||
// In this case just treat "#?" as a single multiplier
|
||||
// { min: 0, max: 0, comma: true }
|
||||
scanner.pos++;
|
||||
range = {
|
||||
min: 0,
|
||||
max: 0
|
||||
};
|
||||
} else {
|
||||
range = {
|
||||
min: 1,
|
||||
max: 0
|
||||
};
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case LEFTCURLYBRACKET:
|
||||
range = readMultiplierRange(scanner);
|
||||
break;
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'Multiplier',
|
||||
comma,
|
||||
min: range.min,
|
||||
max: range.max,
|
||||
term: null
|
||||
};
|
||||
}
|
||||
|
||||
function maybeMultiplied(scanner, node) {
|
||||
const multiplier = readMultiplier(scanner);
|
||||
|
||||
if (multiplier !== null) {
|
||||
multiplier.term = node;
|
||||
|
||||
// https://www.w3.org/TR/css-values-4/#component-multipliers
|
||||
// > The + and # multipliers may be stacked as +#;
|
||||
// Represent "+#" as nested multipliers:
|
||||
// { ...<multiplier #>,
|
||||
// term: {
|
||||
// ...<multipler +>,
|
||||
// term: node
|
||||
// }
|
||||
// }
|
||||
if (scanner.charCode() === NUMBERSIGN &&
|
||||
scanner.charCodeAt(scanner.pos - 1) === PLUSSIGN) {
|
||||
return maybeMultiplied(scanner, multiplier);
|
||||
}
|
||||
|
||||
return multiplier;
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
function maybeToken(scanner) {
|
||||
const ch = scanner.peek();
|
||||
|
||||
if (ch === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return maybeMultiplied(scanner, {
|
||||
type: 'Token',
|
||||
value: ch
|
||||
});
|
||||
}
|
||||
|
||||
function readProperty(scanner) {
|
||||
let name;
|
||||
|
||||
scanner.eat(LESSTHANSIGN);
|
||||
scanner.eat(APOSTROPHE);
|
||||
|
||||
name = scanner.scanWord();
|
||||
|
||||
scanner.eat(APOSTROPHE);
|
||||
scanner.eat(GREATERTHANSIGN);
|
||||
|
||||
return maybeMultiplied(scanner, {
|
||||
type: 'Property',
|
||||
name
|
||||
});
|
||||
}
|
||||
|
||||
// https://drafts.csswg.org/css-values-3/#numeric-ranges
|
||||
// 4.1. Range Restrictions and Range Definition Notation
|
||||
//
|
||||
// Range restrictions can be annotated in the numeric type notation using CSS bracketed
|
||||
// range notation—[min,max]—within the angle brackets, after the identifying keyword,
|
||||
// indicating a closed range between (and including) min and max.
|
||||
// For example, <integer [0, 10]> indicates an integer between 0 and 10, inclusive.
|
||||
function readTypeRange(scanner) {
|
||||
// use null for Infinity to make AST format JSON serializable/deserializable
|
||||
let min = null; // -Infinity
|
||||
let max = null; // Infinity
|
||||
let sign = 1;
|
||||
|
||||
scanner.eat(LEFTSQUAREBRACKET);
|
||||
|
||||
if (scanner.charCode() === HYPERMINUS) {
|
||||
scanner.peek();
|
||||
sign = -1;
|
||||
}
|
||||
|
||||
if (sign == -1 && scanner.charCode() === INFINITY) {
|
||||
scanner.peek();
|
||||
} else {
|
||||
min = sign * Number(scanner.scanNumber(scanner));
|
||||
|
||||
if (scanner.isNameCharCode()) {
|
||||
min += scanner.scanWord();
|
||||
}
|
||||
}
|
||||
|
||||
scanner.skipWs();
|
||||
scanner.eat(COMMA);
|
||||
scanner.skipWs();
|
||||
|
||||
if (scanner.charCode() === INFINITY) {
|
||||
scanner.peek();
|
||||
} else {
|
||||
sign = 1;
|
||||
|
||||
if (scanner.charCode() === HYPERMINUS) {
|
||||
scanner.peek();
|
||||
sign = -1;
|
||||
}
|
||||
|
||||
max = sign * Number(scanner.scanNumber(scanner));
|
||||
|
||||
if (scanner.isNameCharCode()) {
|
||||
max += scanner.scanWord();
|
||||
}
|
||||
}
|
||||
|
||||
scanner.eat(RIGHTSQUAREBRACKET);
|
||||
|
||||
return {
|
||||
type: 'Range',
|
||||
min,
|
||||
max
|
||||
};
|
||||
}
|
||||
|
||||
function readType(scanner) {
|
||||
let name;
|
||||
let opts = null;
|
||||
|
||||
scanner.eat(LESSTHANSIGN);
|
||||
name = scanner.scanWord();
|
||||
|
||||
// https://drafts.csswg.org/css-values-5/#boolean
|
||||
if (name === 'boolean-expr') {
|
||||
scanner.eat(LEFTSQUAREBRACKET);
|
||||
|
||||
const implicitGroup = readImplicitGroup(scanner, RIGHTSQUAREBRACKET);
|
||||
|
||||
scanner.eat(RIGHTSQUAREBRACKET);
|
||||
scanner.eat(GREATERTHANSIGN);
|
||||
|
||||
return maybeMultiplied(scanner, {
|
||||
type: 'Boolean',
|
||||
term: implicitGroup.terms.length === 1
|
||||
? implicitGroup.terms[0]
|
||||
: implicitGroup
|
||||
});
|
||||
}
|
||||
|
||||
if (scanner.charCode() === LEFTPARENTHESIS &&
|
||||
scanner.nextCharCode() === RIGHTPARENTHESIS) {
|
||||
scanner.pos += 2;
|
||||
name += '()';
|
||||
}
|
||||
|
||||
if (scanner.charCodeAt(scanner.findWsEnd(scanner.pos)) === LEFTSQUAREBRACKET) {
|
||||
scanner.skipWs();
|
||||
opts = readTypeRange(scanner);
|
||||
}
|
||||
|
||||
scanner.eat(GREATERTHANSIGN);
|
||||
|
||||
return maybeMultiplied(scanner, {
|
||||
type: 'Type',
|
||||
name,
|
||||
opts
|
||||
});
|
||||
}
|
||||
|
||||
function readKeywordOrFunction(scanner) {
|
||||
const name = scanner.scanWord();
|
||||
|
||||
if (scanner.charCode() === LEFTPARENTHESIS) {
|
||||
scanner.pos++;
|
||||
|
||||
return {
|
||||
type: 'Function',
|
||||
name
|
||||
};
|
||||
}
|
||||
|
||||
return maybeMultiplied(scanner, {
|
||||
type: 'Keyword',
|
||||
name
|
||||
});
|
||||
}
|
||||
|
||||
function regroupTerms(terms, combinators) {
|
||||
function createGroup(terms, combinator) {
|
||||
return {
|
||||
type: 'Group',
|
||||
terms,
|
||||
combinator,
|
||||
disallowEmpty: false,
|
||||
explicit: false
|
||||
};
|
||||
}
|
||||
|
||||
let combinator;
|
||||
|
||||
combinators = Object.keys(combinators)
|
||||
.sort((a, b) => COMBINATOR_PRECEDENCE[a] - COMBINATOR_PRECEDENCE[b]);
|
||||
|
||||
while (combinators.length > 0) {
|
||||
combinator = combinators.shift();
|
||||
|
||||
let i = 0;
|
||||
let subgroupStart = 0;
|
||||
|
||||
for (; i < terms.length; i++) {
|
||||
const term = terms[i];
|
||||
|
||||
if (term.type === 'Combinator') {
|
||||
if (term.value === combinator) {
|
||||
if (subgroupStart === -1) {
|
||||
subgroupStart = i - 1;
|
||||
}
|
||||
terms.splice(i, 1);
|
||||
i--;
|
||||
} else {
|
||||
if (subgroupStart !== -1 && i - subgroupStart > 1) {
|
||||
terms.splice(
|
||||
subgroupStart,
|
||||
i - subgroupStart,
|
||||
createGroup(terms.slice(subgroupStart, i), combinator)
|
||||
);
|
||||
i = subgroupStart + 1;
|
||||
}
|
||||
subgroupStart = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (subgroupStart !== -1 && combinators.length) {
|
||||
terms.splice(
|
||||
subgroupStart,
|
||||
i - subgroupStart,
|
||||
createGroup(terms.slice(subgroupStart, i), combinator)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return combinator;
|
||||
}
|
||||
|
||||
function readImplicitGroup(scanner, stopCharCode) {
|
||||
const combinators = Object.create(null);
|
||||
const terms = [];
|
||||
let token;
|
||||
let prevToken = null;
|
||||
let prevTokenPos = scanner.pos;
|
||||
|
||||
while (scanner.charCode() !== stopCharCode && (token = peek(scanner, stopCharCode))) {
|
||||
if (token.type !== 'Spaces') {
|
||||
if (token.type === 'Combinator') {
|
||||
// check for combinator in group beginning and double combinator sequence
|
||||
if (prevToken === null || prevToken.type === 'Combinator') {
|
||||
scanner.pos = prevTokenPos;
|
||||
scanner.error('Unexpected combinator');
|
||||
}
|
||||
|
||||
combinators[token.value] = true;
|
||||
} else if (prevToken !== null && prevToken.type !== 'Combinator') {
|
||||
combinators[' '] = true; // a b
|
||||
terms.push({
|
||||
type: 'Combinator',
|
||||
value: ' '
|
||||
});
|
||||
}
|
||||
|
||||
terms.push(token);
|
||||
prevToken = token;
|
||||
prevTokenPos = scanner.pos;
|
||||
}
|
||||
}
|
||||
|
||||
// check for combinator in group ending
|
||||
if (prevToken !== null && prevToken.type === 'Combinator') {
|
||||
scanner.pos -= prevTokenPos;
|
||||
scanner.error('Unexpected combinator');
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'Group',
|
||||
terms,
|
||||
combinator: regroupTerms(terms, combinators) || ' ',
|
||||
disallowEmpty: false,
|
||||
explicit: false
|
||||
};
|
||||
}
|
||||
|
||||
function readGroup(scanner, stopCharCode) {
|
||||
let result;
|
||||
|
||||
scanner.eat(LEFTSQUAREBRACKET);
|
||||
result = readImplicitGroup(scanner, stopCharCode);
|
||||
scanner.eat(RIGHTSQUAREBRACKET);
|
||||
|
||||
result.explicit = true;
|
||||
|
||||
if (scanner.charCode() === EXCLAMATIONMARK) {
|
||||
scanner.pos++;
|
||||
result.disallowEmpty = true;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function peek(scanner, stopCharCode) {
|
||||
let code = scanner.charCode();
|
||||
|
||||
switch (code) {
|
||||
case RIGHTSQUAREBRACKET:
|
||||
// don't eat, stop scan a group
|
||||
break;
|
||||
|
||||
case LEFTSQUAREBRACKET:
|
||||
return maybeMultiplied(scanner, readGroup(scanner, stopCharCode));
|
||||
|
||||
case LESSTHANSIGN:
|
||||
return scanner.nextCharCode() === APOSTROPHE
|
||||
? readProperty(scanner)
|
||||
: readType(scanner);
|
||||
|
||||
case VERTICALLINE:
|
||||
return {
|
||||
type: 'Combinator',
|
||||
value: scanner.substringToPos(
|
||||
scanner.pos + (scanner.nextCharCode() === VERTICALLINE ? 2 : 1)
|
||||
)
|
||||
};
|
||||
|
||||
case AMPERSAND:
|
||||
scanner.pos++;
|
||||
scanner.eat(AMPERSAND);
|
||||
|
||||
return {
|
||||
type: 'Combinator',
|
||||
value: '&&'
|
||||
};
|
||||
|
||||
case COMMA:
|
||||
scanner.pos++;
|
||||
return {
|
||||
type: 'Comma'
|
||||
};
|
||||
|
||||
case APOSTROPHE:
|
||||
return maybeMultiplied(scanner, {
|
||||
type: 'String',
|
||||
value: scanner.scanString()
|
||||
});
|
||||
|
||||
case SPACE:
|
||||
case TAB:
|
||||
case N:
|
||||
case R:
|
||||
case F:
|
||||
return {
|
||||
type: 'Spaces',
|
||||
value: scanner.scanSpaces()
|
||||
};
|
||||
|
||||
case COMMERCIALAT:
|
||||
code = scanner.nextCharCode();
|
||||
|
||||
if (scanner.isNameCharCode(code)) {
|
||||
scanner.pos++;
|
||||
return {
|
||||
type: 'AtKeyword',
|
||||
name: scanner.scanWord()
|
||||
};
|
||||
}
|
||||
|
||||
return maybeToken(scanner);
|
||||
|
||||
case ASTERISK:
|
||||
case PLUSSIGN:
|
||||
case QUESTIONMARK:
|
||||
case NUMBERSIGN:
|
||||
case EXCLAMATIONMARK:
|
||||
// prohibited tokens (used as a multiplier start)
|
||||
break;
|
||||
|
||||
case LEFTCURLYBRACKET:
|
||||
// LEFTCURLYBRACKET is allowed since mdn/data uses it w/o quoting
|
||||
// check next char isn't a number, because it's likely a disjoined multiplier
|
||||
code = scanner.nextCharCode();
|
||||
|
||||
if (code < 48 || code > 57) {
|
||||
return maybeToken(scanner);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
if (scanner.isNameCharCode(code)) {
|
||||
return readKeywordOrFunction(scanner);
|
||||
}
|
||||
|
||||
return maybeToken(scanner);
|
||||
}
|
||||
}
|
||||
|
||||
function parse(source) {
|
||||
const scanner$1 = new scanner.Scanner(source);
|
||||
const result = readImplicitGroup(scanner$1);
|
||||
|
||||
if (scanner$1.pos !== source.length) {
|
||||
scanner$1.error('Unexpected input');
|
||||
}
|
||||
|
||||
// reduce redundant groups with single group term
|
||||
if (result.terms.length === 1 && result.terms[0].type === 'Group') {
|
||||
return result.terms[0];
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
exports.parse = parse;
|
||||
-113
@@ -1,113 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const SyntaxError = require('./SyntaxError.cjs');
|
||||
|
||||
const TAB = 9;
|
||||
const N = 10;
|
||||
const F = 12;
|
||||
const R = 13;
|
||||
const SPACE = 32;
|
||||
const NAME_CHAR = new Uint8Array(128).map((_, idx) =>
|
||||
/[a-zA-Z0-9\-]/.test(String.fromCharCode(idx)) ? 1 : 0
|
||||
);
|
||||
|
||||
class Scanner {
|
||||
constructor(str) {
|
||||
this.str = str;
|
||||
this.pos = 0;
|
||||
}
|
||||
|
||||
charCodeAt(pos) {
|
||||
return pos < this.str.length ? this.str.charCodeAt(pos) : 0;
|
||||
}
|
||||
charCode() {
|
||||
return this.charCodeAt(this.pos);
|
||||
}
|
||||
isNameCharCode(code = this.charCode()) {
|
||||
return code < 128 && NAME_CHAR[code] === 1;
|
||||
}
|
||||
nextCharCode() {
|
||||
return this.charCodeAt(this.pos + 1);
|
||||
}
|
||||
nextNonWsCode(pos) {
|
||||
return this.charCodeAt(this.findWsEnd(pos));
|
||||
}
|
||||
skipWs() {
|
||||
this.pos = this.findWsEnd(this.pos);
|
||||
}
|
||||
findWsEnd(pos) {
|
||||
for (; pos < this.str.length; pos++) {
|
||||
const code = this.str.charCodeAt(pos);
|
||||
if (code !== R && code !== N && code !== F && code !== SPACE && code !== TAB) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return pos;
|
||||
}
|
||||
substringToPos(end) {
|
||||
return this.str.substring(this.pos, this.pos = end);
|
||||
}
|
||||
eat(code) {
|
||||
if (this.charCode() !== code) {
|
||||
this.error('Expect `' + String.fromCharCode(code) + '`');
|
||||
}
|
||||
|
||||
this.pos++;
|
||||
}
|
||||
peek() {
|
||||
return this.pos < this.str.length ? this.str.charAt(this.pos++) : '';
|
||||
}
|
||||
error(message) {
|
||||
throw new SyntaxError.SyntaxError(message, this.str, this.pos);
|
||||
}
|
||||
|
||||
scanSpaces() {
|
||||
return this.substringToPos(this.findWsEnd(this.pos));
|
||||
}
|
||||
scanWord() {
|
||||
let end = this.pos;
|
||||
|
||||
for (; end < this.str.length; end++) {
|
||||
const code = this.str.charCodeAt(end);
|
||||
if (code >= 128 || NAME_CHAR[code] === 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.pos === end) {
|
||||
this.error('Expect a keyword');
|
||||
}
|
||||
|
||||
return this.substringToPos(end);
|
||||
}
|
||||
scanNumber() {
|
||||
let end = this.pos;
|
||||
|
||||
for (; end < this.str.length; end++) {
|
||||
const code = this.str.charCodeAt(end);
|
||||
|
||||
if (code < 48 || code > 57) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.pos === end) {
|
||||
this.error('Expect a number');
|
||||
}
|
||||
|
||||
return this.substringToPos(end);
|
||||
}
|
||||
scanString() {
|
||||
const end = this.str.indexOf('\'', this.pos + 1);
|
||||
|
||||
if (end === -1) {
|
||||
this.pos = this.str.length;
|
||||
this.error('Expect an apostrophe');
|
||||
}
|
||||
|
||||
return this.substringToPos(end + 1);
|
||||
}
|
||||
}
|
||||
|
||||
exports.Scanner = Scanner;
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const noop = function() {};
|
||||
|
||||
function ensureFunction(value) {
|
||||
return typeof value === 'function' ? value : noop;
|
||||
}
|
||||
|
||||
function walk(node, options, context) {
|
||||
function walk(node) {
|
||||
enter.call(context, node);
|
||||
|
||||
switch (node.type) {
|
||||
case 'Group':
|
||||
node.terms.forEach(walk);
|
||||
break;
|
||||
|
||||
case 'Multiplier':
|
||||
case 'Boolean':
|
||||
walk(node.term);
|
||||
break;
|
||||
|
||||
case 'Type':
|
||||
case 'Property':
|
||||
case 'Keyword':
|
||||
case 'AtKeyword':
|
||||
case 'Function':
|
||||
case 'String':
|
||||
case 'Token':
|
||||
case 'Comma':
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error('Unknown type: ' + node.type);
|
||||
}
|
||||
|
||||
leave.call(context, node);
|
||||
}
|
||||
|
||||
let enter = noop;
|
||||
let leave = noop;
|
||||
|
||||
if (typeof options === 'function') {
|
||||
enter = options;
|
||||
} else if (options) {
|
||||
enter = ensureFunction(options.enter);
|
||||
leave = ensureFunction(options.leave);
|
||||
}
|
||||
|
||||
if (enter === noop && leave === noop) {
|
||||
throw new Error('Neither `enter` nor `leave` walker handler is set or both aren\'t a function');
|
||||
}
|
||||
|
||||
walk(node);
|
||||
}
|
||||
|
||||
exports.walk = walk;
|
||||
-102
@@ -1,102 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const getTokenizer = require('../utils/get-tokenizer.cjs');
|
||||
const sourceMap = require('./sourceMap.cjs');
|
||||
const tokenBefore = require('./token-before.cjs');
|
||||
const types = require('../tokenizer/types.cjs');
|
||||
|
||||
const REVERSESOLIDUS = 0x005c; // U+005C REVERSE SOLIDUS (\)
|
||||
|
||||
function processChildren(node, delimeter) {
|
||||
if (typeof delimeter === 'function') {
|
||||
let prev = null;
|
||||
|
||||
node.children.forEach(node => {
|
||||
if (prev !== null) {
|
||||
delimeter.call(this, prev);
|
||||
}
|
||||
|
||||
this.node(node);
|
||||
prev = node;
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
node.children.forEach(this.node, this);
|
||||
}
|
||||
|
||||
function createGenerator(config) {
|
||||
const types$1 = new Map();
|
||||
|
||||
for (let [name, item] of Object.entries(config.node)) {
|
||||
const fn = item.generate || item;
|
||||
|
||||
if (typeof fn === 'function') {
|
||||
types$1.set(name, item.generate || item);
|
||||
}
|
||||
}
|
||||
|
||||
return function(node, options) {
|
||||
let buffer = '';
|
||||
let prevCode = 0;
|
||||
let handlers = {
|
||||
node(node) {
|
||||
if (types$1.has(node.type)) {
|
||||
types$1.get(node.type).call(publicApi, node);
|
||||
} else {
|
||||
throw new Error('Unknown node type: ' + node.type);
|
||||
}
|
||||
},
|
||||
tokenBefore: tokenBefore.safe,
|
||||
token(type, value) {
|
||||
prevCode = this.tokenBefore(prevCode, type, value);
|
||||
|
||||
this.emit(value, type, false);
|
||||
|
||||
if (type === types.Delim && value.charCodeAt(0) === REVERSESOLIDUS) {
|
||||
this.emit('\n', types.WhiteSpace, true);
|
||||
}
|
||||
},
|
||||
emit(value) {
|
||||
buffer += value;
|
||||
},
|
||||
result() {
|
||||
return buffer;
|
||||
}
|
||||
};
|
||||
|
||||
if (options) {
|
||||
if (typeof options.decorator === 'function') {
|
||||
handlers = options.decorator(handlers);
|
||||
}
|
||||
|
||||
if (options.sourceMap) {
|
||||
handlers = sourceMap.generateSourceMap(handlers);
|
||||
}
|
||||
|
||||
if (options.mode in tokenBefore) {
|
||||
handlers.tokenBefore = tokenBefore[options.mode];
|
||||
}
|
||||
}
|
||||
|
||||
const publicApi = {
|
||||
node: (node) => handlers.node(node),
|
||||
children: processChildren,
|
||||
token: (type, value) => handlers.token(type, value),
|
||||
tokenize: function (chunk) {
|
||||
const tokenize = getTokenizer.getTokenizer(config);
|
||||
|
||||
return tokenize(chunk, (type, start, end) => {
|
||||
this.token(type, chunk.slice(start, end));
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
handlers.node(node);
|
||||
|
||||
return handlers.result();
|
||||
};
|
||||
}
|
||||
|
||||
exports.createGenerator = createGenerator;
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const create = require('./create.cjs');
|
||||
const generator = require('../syntax/config/generator.cjs');
|
||||
|
||||
const index = create.createGenerator(generator);
|
||||
|
||||
module.exports = index;
|
||||
-96
@@ -1,96 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const sourceMapGenerator_js = require('source-map-js/lib/source-map-generator.js');
|
||||
|
||||
const trackNodes = new Set(['Atrule', 'Selector', 'Declaration']);
|
||||
|
||||
function generateSourceMap(handlers) {
|
||||
const map = new sourceMapGenerator_js.SourceMapGenerator();
|
||||
const generated = {
|
||||
line: 1,
|
||||
column: 0
|
||||
};
|
||||
const original = {
|
||||
line: 0, // should be zero to add first mapping
|
||||
column: 0
|
||||
};
|
||||
const activatedGenerated = {
|
||||
line: 1,
|
||||
column: 0
|
||||
};
|
||||
const activatedMapping = {
|
||||
generated: activatedGenerated
|
||||
};
|
||||
let line = 1;
|
||||
let column = 0;
|
||||
let sourceMappingActive = false;
|
||||
|
||||
const origHandlersNode = handlers.node;
|
||||
handlers.node = function(node) {
|
||||
if (node.loc && node.loc.start && trackNodes.has(node.type)) {
|
||||
const nodeLine = node.loc.start.line;
|
||||
const nodeColumn = node.loc.start.column - 1;
|
||||
|
||||
if (original.line !== nodeLine ||
|
||||
original.column !== nodeColumn) {
|
||||
original.line = nodeLine;
|
||||
original.column = nodeColumn;
|
||||
|
||||
generated.line = line;
|
||||
generated.column = column;
|
||||
|
||||
if (sourceMappingActive) {
|
||||
sourceMappingActive = false;
|
||||
if (generated.line !== activatedGenerated.line ||
|
||||
generated.column !== activatedGenerated.column) {
|
||||
map.addMapping(activatedMapping);
|
||||
}
|
||||
}
|
||||
|
||||
sourceMappingActive = true;
|
||||
map.addMapping({
|
||||
source: node.loc.source,
|
||||
original,
|
||||
generated
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
origHandlersNode.call(this, node);
|
||||
|
||||
if (sourceMappingActive && trackNodes.has(node.type)) {
|
||||
activatedGenerated.line = line;
|
||||
activatedGenerated.column = column;
|
||||
}
|
||||
};
|
||||
|
||||
const origHandlersEmit = handlers.emit;
|
||||
handlers.emit = function(value, type, auto) {
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
if (value.charCodeAt(i) === 10) { // \n
|
||||
line++;
|
||||
column = 0;
|
||||
} else {
|
||||
column++;
|
||||
}
|
||||
}
|
||||
|
||||
origHandlersEmit(value, type, auto);
|
||||
};
|
||||
|
||||
const origHandlersResult = handlers.result;
|
||||
handlers.result = function() {
|
||||
if (sourceMappingActive) {
|
||||
map.addMapping(activatedMapping);
|
||||
}
|
||||
|
||||
return {
|
||||
css: origHandlersResult(),
|
||||
map
|
||||
};
|
||||
};
|
||||
|
||||
return handlers;
|
||||
}
|
||||
|
||||
exports.generateSourceMap = generateSourceMap;
|
||||
-170
@@ -1,170 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const types = require('../tokenizer/types.cjs');
|
||||
|
||||
const PLUSSIGN = 0x002B; // U+002B PLUS SIGN (+)
|
||||
const HYPHENMINUS = 0x002D; // U+002D HYPHEN-MINUS (-)
|
||||
|
||||
const code = (type, value) => {
|
||||
if (type === types.Delim) {
|
||||
type = value;
|
||||
}
|
||||
|
||||
if (typeof type === 'string') {
|
||||
const charCode = type.charCodeAt(0);
|
||||
return charCode > 0x7F ? 0x8000 : charCode << 8;
|
||||
}
|
||||
|
||||
return type;
|
||||
};
|
||||
|
||||
// https://www.w3.org/TR/css-syntax-3/#serialization
|
||||
// The only requirement for serialization is that it must "round-trip" with parsing,
|
||||
// that is, parsing the stylesheet must produce the same data structures as parsing,
|
||||
// serializing, and parsing again, except for consecutive <whitespace-token>s,
|
||||
// which may be collapsed into a single token.
|
||||
|
||||
const specPairs = [
|
||||
[types.Ident, types.Ident],
|
||||
[types.Ident, types.Function],
|
||||
[types.Ident, types.Url],
|
||||
[types.Ident, types.BadUrl],
|
||||
[types.Ident, '-'],
|
||||
[types.Ident, types.Number],
|
||||
[types.Ident, types.Percentage],
|
||||
[types.Ident, types.Dimension],
|
||||
[types.Ident, types.CDC],
|
||||
[types.Ident, types.LeftParenthesis],
|
||||
|
||||
[types.AtKeyword, types.Ident],
|
||||
[types.AtKeyword, types.Function],
|
||||
[types.AtKeyword, types.Url],
|
||||
[types.AtKeyword, types.BadUrl],
|
||||
[types.AtKeyword, '-'],
|
||||
[types.AtKeyword, types.Number],
|
||||
[types.AtKeyword, types.Percentage],
|
||||
[types.AtKeyword, types.Dimension],
|
||||
[types.AtKeyword, types.CDC],
|
||||
|
||||
[types.Hash, types.Ident],
|
||||
[types.Hash, types.Function],
|
||||
[types.Hash, types.Url],
|
||||
[types.Hash, types.BadUrl],
|
||||
[types.Hash, '-'],
|
||||
[types.Hash, types.Number],
|
||||
[types.Hash, types.Percentage],
|
||||
[types.Hash, types.Dimension],
|
||||
[types.Hash, types.CDC],
|
||||
|
||||
[types.Dimension, types.Ident],
|
||||
[types.Dimension, types.Function],
|
||||
[types.Dimension, types.Url],
|
||||
[types.Dimension, types.BadUrl],
|
||||
[types.Dimension, '-'],
|
||||
[types.Dimension, types.Number],
|
||||
[types.Dimension, types.Percentage],
|
||||
[types.Dimension, types.Dimension],
|
||||
[types.Dimension, types.CDC],
|
||||
|
||||
['#', types.Ident],
|
||||
['#', types.Function],
|
||||
['#', types.Url],
|
||||
['#', types.BadUrl],
|
||||
['#', '-'],
|
||||
['#', types.Number],
|
||||
['#', types.Percentage],
|
||||
['#', types.Dimension],
|
||||
['#', types.CDC], // https://github.com/w3c/csswg-drafts/pull/6874
|
||||
|
||||
['-', types.Ident],
|
||||
['-', types.Function],
|
||||
['-', types.Url],
|
||||
['-', types.BadUrl],
|
||||
['-', '-'],
|
||||
['-', types.Number],
|
||||
['-', types.Percentage],
|
||||
['-', types.Dimension],
|
||||
['-', types.CDC], // https://github.com/w3c/csswg-drafts/pull/6874
|
||||
|
||||
[types.Number, types.Ident],
|
||||
[types.Number, types.Function],
|
||||
[types.Number, types.Url],
|
||||
[types.Number, types.BadUrl],
|
||||
[types.Number, types.Number],
|
||||
[types.Number, types.Percentage],
|
||||
[types.Number, types.Dimension],
|
||||
[types.Number, '%'],
|
||||
[types.Number, types.CDC], // https://github.com/w3c/csswg-drafts/pull/6874
|
||||
|
||||
['@', types.Ident],
|
||||
['@', types.Function],
|
||||
['@', types.Url],
|
||||
['@', types.BadUrl],
|
||||
['@', '-'],
|
||||
['@', types.CDC], // https://github.com/w3c/csswg-drafts/pull/6874
|
||||
|
||||
['.', types.Number],
|
||||
['.', types.Percentage],
|
||||
['.', types.Dimension],
|
||||
|
||||
['+', types.Number],
|
||||
['+', types.Percentage],
|
||||
['+', types.Dimension],
|
||||
|
||||
['/', '*']
|
||||
];
|
||||
// validate with scripts/generate-safe
|
||||
const safePairs = specPairs.concat([
|
||||
[types.Ident, types.Hash],
|
||||
|
||||
[types.Dimension, types.Hash],
|
||||
|
||||
[types.Hash, types.Hash],
|
||||
|
||||
[types.AtKeyword, types.LeftParenthesis],
|
||||
[types.AtKeyword, types.String],
|
||||
[types.AtKeyword, types.Colon],
|
||||
|
||||
[types.Percentage, types.Percentage],
|
||||
[types.Percentage, types.Dimension],
|
||||
[types.Percentage, types.Function],
|
||||
[types.Percentage, '-'],
|
||||
|
||||
[types.RightParenthesis, types.Ident],
|
||||
[types.RightParenthesis, types.Function],
|
||||
[types.RightParenthesis, types.Percentage],
|
||||
[types.RightParenthesis, types.Dimension],
|
||||
[types.RightParenthesis, types.Hash],
|
||||
[types.RightParenthesis, '-']
|
||||
]);
|
||||
|
||||
function createMap(pairs) {
|
||||
const isWhiteSpaceRequired = new Set(
|
||||
pairs.map(([prev, next]) => (code(prev) << 16 | code(next)))
|
||||
);
|
||||
|
||||
return function(prevCode, type, value) {
|
||||
const nextCode = code(type, value);
|
||||
const nextCharCode = value.charCodeAt(0);
|
||||
const emitWs =
|
||||
(nextCharCode === HYPHENMINUS &&
|
||||
type !== types.Ident &&
|
||||
type !== types.Function &&
|
||||
type !== types.CDC) ||
|
||||
(nextCharCode === PLUSSIGN)
|
||||
? isWhiteSpaceRequired.has(prevCode << 16 | nextCharCode << 8)
|
||||
: isWhiteSpaceRequired.has(prevCode << 16 | nextCode);
|
||||
|
||||
if (emitWs) {
|
||||
this.emit(' ', types.WhiteSpace, true);
|
||||
}
|
||||
|
||||
return nextCode;
|
||||
};
|
||||
}
|
||||
|
||||
const spec = createMap(specPairs);
|
||||
const safe = createMap(safePairs);
|
||||
|
||||
exports.safe = safe;
|
||||
exports.spec = spec;
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const index$1 = require('./syntax/index.cjs');
|
||||
const version = require('./version.cjs');
|
||||
const create = require('./syntax/create.cjs');
|
||||
const List = require('./utils/List.cjs');
|
||||
const Lexer = require('./lexer/Lexer.cjs');
|
||||
const index = require('./definition-syntax/index.cjs');
|
||||
const clone = require('./utils/clone.cjs');
|
||||
const names$1 = require('./utils/names.cjs');
|
||||
const ident = require('./utils/ident.cjs');
|
||||
const string = require('./utils/string.cjs');
|
||||
const url = require('./utils/url.cjs');
|
||||
const types = require('./tokenizer/types.cjs');
|
||||
const names = require('./tokenizer/names.cjs');
|
||||
const TokenStream = require('./tokenizer/TokenStream.cjs');
|
||||
const OffsetToLocation = require('./tokenizer/OffsetToLocation.cjs');
|
||||
|
||||
const {
|
||||
tokenize,
|
||||
parse,
|
||||
generate,
|
||||
lexer,
|
||||
createLexer,
|
||||
|
||||
walk,
|
||||
find,
|
||||
findLast,
|
||||
findAll,
|
||||
|
||||
toPlainObject,
|
||||
fromPlainObject,
|
||||
|
||||
fork
|
||||
} = index$1;
|
||||
|
||||
exports.version = version.version;
|
||||
exports.createSyntax = create;
|
||||
exports.List = List.List;
|
||||
exports.Lexer = Lexer.Lexer;
|
||||
exports.definitionSyntax = index;
|
||||
exports.clone = clone.clone;
|
||||
exports.isCustomProperty = names$1.isCustomProperty;
|
||||
exports.keyword = names$1.keyword;
|
||||
exports.property = names$1.property;
|
||||
exports.vendorPrefix = names$1.vendorPrefix;
|
||||
exports.ident = ident;
|
||||
exports.string = string;
|
||||
exports.url = url;
|
||||
exports.tokenTypes = types;
|
||||
exports.tokenNames = names;
|
||||
exports.TokenStream = TokenStream.TokenStream;
|
||||
exports.OffsetToLocation = OffsetToLocation.OffsetToLocation;
|
||||
exports.createLexer = createLexer;
|
||||
exports.find = find;
|
||||
exports.findAll = findAll;
|
||||
exports.findLast = findLast;
|
||||
exports.fork = fork;
|
||||
exports.fromPlainObject = fromPlainObject;
|
||||
exports.generate = generate;
|
||||
exports.lexer = lexer;
|
||||
exports.parse = parse;
|
||||
exports.toPlainObject = toPlainObject;
|
||||
exports.tokenize = tokenize;
|
||||
exports.walk = walk;
|
||||
-533
@@ -1,533 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const error = require('./error.cjs');
|
||||
const names = require('../utils/names.cjs');
|
||||
const genericConst = require('./generic-const.cjs');
|
||||
const generic = require('./generic.cjs');
|
||||
const units = require('./units.cjs');
|
||||
const prepareTokens = require('./prepare-tokens.cjs');
|
||||
const matchGraph = require('./match-graph.cjs');
|
||||
const match = require('./match.cjs');
|
||||
const trace = require('./trace.cjs');
|
||||
const search = require('./search.cjs');
|
||||
const structure = require('./structure.cjs');
|
||||
const parse = require('../definition-syntax/parse.cjs');
|
||||
const generate = require('../definition-syntax/generate.cjs');
|
||||
const walk = require('../definition-syntax/walk.cjs');
|
||||
|
||||
function dumpMapSyntax(map, compact, syntaxAsAst) {
|
||||
const result = {};
|
||||
|
||||
for (const name in map) {
|
||||
if (map[name].syntax) {
|
||||
result[name] = syntaxAsAst
|
||||
? map[name].syntax
|
||||
: generate.generate(map[name].syntax, { compact });
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function dumpAtruleMapSyntax(map, compact, syntaxAsAst) {
|
||||
const result = {};
|
||||
|
||||
for (const [name, atrule] of Object.entries(map)) {
|
||||
result[name] = {
|
||||
prelude: atrule.prelude && (
|
||||
syntaxAsAst
|
||||
? atrule.prelude.syntax
|
||||
: generate.generate(atrule.prelude.syntax, { compact })
|
||||
),
|
||||
descriptors: atrule.descriptors && dumpMapSyntax(atrule.descriptors, compact, syntaxAsAst)
|
||||
};
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function valueHasVar(tokens) {
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
if (tokens[i].value.toLowerCase() === 'var(') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function syntaxHasTopLevelCommaMultiplier(syntax) {
|
||||
const singleTerm = syntax.terms[0];
|
||||
|
||||
return (
|
||||
syntax.explicit === false &&
|
||||
syntax.terms.length === 1 &&
|
||||
singleTerm.type === 'Multiplier' &&
|
||||
singleTerm.comma === true
|
||||
);
|
||||
}
|
||||
|
||||
function valueHasEnv(tokens) {
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
if (tokens[i].value.toLowerCase() === 'env(') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function buildMatchResult(matched, error, iterations) {
|
||||
return {
|
||||
matched,
|
||||
iterations,
|
||||
error,
|
||||
...trace
|
||||
};
|
||||
}
|
||||
|
||||
function matchSyntax(lexer, syntax, value, useCssWideKeywords) {
|
||||
const tokens = prepareTokens(value, lexer.syntax);
|
||||
let result;
|
||||
|
||||
if (valueHasVar(tokens)) {
|
||||
return buildMatchResult(null, new Error('Matching for a tree with var() is not supported'));
|
||||
}
|
||||
|
||||
if (valueHasEnv(tokens)) {
|
||||
return buildMatchResult(null, new Error('Matching for a tree with env() is not supported'));
|
||||
}
|
||||
|
||||
if (useCssWideKeywords) {
|
||||
result = match.matchAsTree(tokens, lexer.cssWideKeywordsSyntax, lexer);
|
||||
}
|
||||
|
||||
if (!useCssWideKeywords || !result.match) {
|
||||
result = match.matchAsTree(tokens, syntax.match, lexer);
|
||||
if (!result.match) {
|
||||
return buildMatchResult(
|
||||
null,
|
||||
new error.SyntaxMatchError(result.reason, syntax.syntax, value, result),
|
||||
result.iterations
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return buildMatchResult(result.match, null, result.iterations);
|
||||
}
|
||||
|
||||
class Lexer {
|
||||
constructor(config, syntax, structure$1) {
|
||||
this.cssWideKeywords = genericConst.cssWideKeywords;
|
||||
this.syntax = syntax;
|
||||
this.generic = false;
|
||||
this.units = { ...units };
|
||||
this.atrules = Object.create(null);
|
||||
this.properties = Object.create(null);
|
||||
this.types = Object.create(null);
|
||||
this.structure = structure$1 || structure.getStructureFromConfig(config);
|
||||
|
||||
if (config) {
|
||||
if (config.cssWideKeywords) {
|
||||
this.cssWideKeywords = config.cssWideKeywords;
|
||||
}
|
||||
|
||||
if (config.units) {
|
||||
for (const group of Object.keys(units)) {
|
||||
if (Array.isArray(config.units[group])) {
|
||||
this.units[group] = config.units[group];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (config.types) {
|
||||
for (const [name, type] of Object.entries(config.types)) {
|
||||
this.addType_(name, type);
|
||||
}
|
||||
}
|
||||
|
||||
if (config.generic) {
|
||||
this.generic = true;
|
||||
for (const [name, value] of Object.entries(generic.createGenericTypes(this.units))) {
|
||||
this.addType_(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
if (config.atrules) {
|
||||
for (const [name, atrule] of Object.entries(config.atrules)) {
|
||||
this.addAtrule_(name, atrule);
|
||||
}
|
||||
}
|
||||
|
||||
if (config.properties) {
|
||||
for (const [name, property] of Object.entries(config.properties)) {
|
||||
this.addProperty_(name, property);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.cssWideKeywordsSyntax = matchGraph.buildMatchGraph(this.cssWideKeywords.join(' | '));
|
||||
}
|
||||
|
||||
checkStructure(ast) {
|
||||
function collectWarning(node, message) {
|
||||
warns.push({ node, message });
|
||||
}
|
||||
|
||||
const structure = this.structure;
|
||||
const warns = [];
|
||||
|
||||
this.syntax.walk(ast, function(node) {
|
||||
if (structure.hasOwnProperty(node.type)) {
|
||||
structure[node.type].check(node, collectWarning);
|
||||
} else {
|
||||
collectWarning(node, 'Unknown node type `' + node.type + '`');
|
||||
}
|
||||
});
|
||||
|
||||
return warns.length ? warns : false;
|
||||
}
|
||||
|
||||
createDescriptor(syntax, type, name, parent = null) {
|
||||
const ref = {
|
||||
type,
|
||||
name
|
||||
};
|
||||
const descriptor = {
|
||||
type,
|
||||
name,
|
||||
parent,
|
||||
serializable: typeof syntax === 'string' || (syntax && typeof syntax.type === 'string'),
|
||||
syntax: null,
|
||||
match: null,
|
||||
matchRef: null // used for properties when a syntax referenced as <'property'> in other syntax definitions
|
||||
};
|
||||
|
||||
if (typeof syntax === 'function') {
|
||||
descriptor.match = matchGraph.buildMatchGraph(syntax, ref);
|
||||
} else {
|
||||
if (typeof syntax === 'string') {
|
||||
// lazy parsing on first access
|
||||
Object.defineProperty(descriptor, 'syntax', {
|
||||
get() {
|
||||
Object.defineProperty(descriptor, 'syntax', {
|
||||
value: parse.parse(syntax)
|
||||
});
|
||||
|
||||
return descriptor.syntax;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
descriptor.syntax = syntax;
|
||||
}
|
||||
|
||||
// lazy graph build on first access
|
||||
Object.defineProperty(descriptor, 'match', {
|
||||
get() {
|
||||
Object.defineProperty(descriptor, 'match', {
|
||||
value: matchGraph.buildMatchGraph(descriptor.syntax, ref)
|
||||
});
|
||||
|
||||
return descriptor.match;
|
||||
}
|
||||
});
|
||||
|
||||
if (type === 'Property') {
|
||||
Object.defineProperty(descriptor, 'matchRef', {
|
||||
get() {
|
||||
const syntax = descriptor.syntax;
|
||||
const value = syntaxHasTopLevelCommaMultiplier(syntax)
|
||||
? matchGraph.buildMatchGraph({
|
||||
...syntax,
|
||||
terms: [syntax.terms[0].term]
|
||||
}, ref)
|
||||
: null;
|
||||
|
||||
Object.defineProperty(descriptor, 'matchRef', {
|
||||
value
|
||||
});
|
||||
|
||||
return value;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return descriptor;
|
||||
}
|
||||
addAtrule_(name, syntax) {
|
||||
if (!syntax) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.atrules[name] = {
|
||||
type: 'Atrule',
|
||||
name: name,
|
||||
prelude: syntax.prelude ? this.createDescriptor(syntax.prelude, 'AtrulePrelude', name) : null,
|
||||
descriptors: syntax.descriptors
|
||||
? Object.keys(syntax.descriptors).reduce(
|
||||
(map, descName) => {
|
||||
map[descName] = this.createDescriptor(syntax.descriptors[descName], 'AtruleDescriptor', descName, name);
|
||||
return map;
|
||||
},
|
||||
Object.create(null)
|
||||
)
|
||||
: null
|
||||
};
|
||||
}
|
||||
addProperty_(name, syntax) {
|
||||
if (!syntax) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.properties[name] = this.createDescriptor(syntax, 'Property', name);
|
||||
}
|
||||
addType_(name, syntax) {
|
||||
if (!syntax) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.types[name] = this.createDescriptor(syntax, 'Type', name);
|
||||
}
|
||||
|
||||
checkAtruleName(atruleName) {
|
||||
if (!this.getAtrule(atruleName)) {
|
||||
return new error.SyntaxReferenceError('Unknown at-rule', '@' + atruleName);
|
||||
}
|
||||
}
|
||||
checkAtrulePrelude(atruleName, prelude) {
|
||||
const error = this.checkAtruleName(atruleName);
|
||||
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
const atrule = this.getAtrule(atruleName);
|
||||
|
||||
if (!atrule.prelude && prelude) {
|
||||
return new SyntaxError('At-rule `@' + atruleName + '` should not contain a prelude');
|
||||
}
|
||||
|
||||
if (atrule.prelude && !prelude) {
|
||||
if (!matchSyntax(this, atrule.prelude, '', false).matched) {
|
||||
return new SyntaxError('At-rule `@' + atruleName + '` should contain a prelude');
|
||||
}
|
||||
}
|
||||
}
|
||||
checkAtruleDescriptorName(atruleName, descriptorName) {
|
||||
const error$1 = this.checkAtruleName(atruleName);
|
||||
|
||||
if (error$1) {
|
||||
return error$1;
|
||||
}
|
||||
|
||||
const atrule = this.getAtrule(atruleName);
|
||||
const descriptor = names.keyword(descriptorName);
|
||||
|
||||
if (!atrule.descriptors) {
|
||||
return new SyntaxError('At-rule `@' + atruleName + '` has no known descriptors');
|
||||
}
|
||||
|
||||
if (!atrule.descriptors[descriptor.name] &&
|
||||
!atrule.descriptors[descriptor.basename]) {
|
||||
return new error.SyntaxReferenceError('Unknown at-rule descriptor', descriptorName);
|
||||
}
|
||||
}
|
||||
checkPropertyName(propertyName) {
|
||||
if (!this.getProperty(propertyName)) {
|
||||
return new error.SyntaxReferenceError('Unknown property', propertyName);
|
||||
}
|
||||
}
|
||||
|
||||
matchAtrulePrelude(atruleName, prelude) {
|
||||
const error = this.checkAtrulePrelude(atruleName, prelude);
|
||||
|
||||
if (error) {
|
||||
return buildMatchResult(null, error);
|
||||
}
|
||||
|
||||
const atrule = this.getAtrule(atruleName);
|
||||
|
||||
if (!atrule.prelude) {
|
||||
return buildMatchResult(null, null);
|
||||
}
|
||||
|
||||
return matchSyntax(this, atrule.prelude, prelude || '', false);
|
||||
}
|
||||
matchAtruleDescriptor(atruleName, descriptorName, value) {
|
||||
const error = this.checkAtruleDescriptorName(atruleName, descriptorName);
|
||||
|
||||
if (error) {
|
||||
return buildMatchResult(null, error);
|
||||
}
|
||||
|
||||
const atrule = this.getAtrule(atruleName);
|
||||
const descriptor = names.keyword(descriptorName);
|
||||
|
||||
return matchSyntax(this, atrule.descriptors[descriptor.name] || atrule.descriptors[descriptor.basename], value, false);
|
||||
}
|
||||
matchDeclaration(node) {
|
||||
if (node.type !== 'Declaration') {
|
||||
return buildMatchResult(null, new Error('Not a Declaration node'));
|
||||
}
|
||||
|
||||
return this.matchProperty(node.property, node.value);
|
||||
}
|
||||
matchProperty(propertyName, value) {
|
||||
if (
|
||||
!this.getProperty(propertyName) &&
|
||||
names.property(propertyName).custom
|
||||
) {
|
||||
return buildMatchResult(null, new Error('Lexer matching doesn\'t applicable for custom properties'));
|
||||
}
|
||||
|
||||
const error = this.checkPropertyName(propertyName);
|
||||
|
||||
if (error) {
|
||||
return buildMatchResult(null, error);
|
||||
}
|
||||
|
||||
return matchSyntax(this, this.getProperty(propertyName), value, true);
|
||||
}
|
||||
matchType(typeName, value) {
|
||||
const typeSyntax = this.getType(typeName);
|
||||
|
||||
if (!typeSyntax) {
|
||||
return buildMatchResult(null, new error.SyntaxReferenceError('Unknown type', typeName));
|
||||
}
|
||||
|
||||
return matchSyntax(this, typeSyntax, value, false);
|
||||
}
|
||||
match(syntax, value) {
|
||||
if (typeof syntax !== 'string' && (!syntax || !syntax.type)) {
|
||||
return buildMatchResult(null, new error.SyntaxReferenceError('Bad syntax'));
|
||||
}
|
||||
|
||||
if (typeof syntax === 'string' || !syntax.match) {
|
||||
syntax = this.createDescriptor(syntax, 'Type', 'anonymous');
|
||||
}
|
||||
|
||||
return matchSyntax(this, syntax, value, false);
|
||||
}
|
||||
|
||||
findValueFragments(propertyName, value, type, name) {
|
||||
return search.matchFragments(this, value, this.matchProperty(propertyName, value), type, name);
|
||||
}
|
||||
findDeclarationValueFragments(declaration, type, name) {
|
||||
return search.matchFragments(this, declaration.value, this.matchDeclaration(declaration), type, name);
|
||||
}
|
||||
findAllFragments(ast, type, name) {
|
||||
const result = [];
|
||||
|
||||
this.syntax.walk(ast, {
|
||||
visit: 'Declaration',
|
||||
enter: (declaration) => {
|
||||
result.push.apply(result, this.findDeclarationValueFragments(declaration, type, name));
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
getAtrule(atruleName, fallbackBasename = true) {
|
||||
const atrule = names.keyword(atruleName);
|
||||
const atruleEntry = atrule.vendor && fallbackBasename
|
||||
? this.atrules[atrule.name] || this.atrules[atrule.basename]
|
||||
: this.atrules[atrule.name];
|
||||
|
||||
return atruleEntry || null;
|
||||
}
|
||||
getAtrulePrelude(atruleName, fallbackBasename = true) {
|
||||
const atrule = this.getAtrule(atruleName, fallbackBasename);
|
||||
|
||||
return atrule && atrule.prelude || null;
|
||||
}
|
||||
getAtruleDescriptor(atruleName, name) {
|
||||
return this.atrules.hasOwnProperty(atruleName) && this.atrules.declarators
|
||||
? this.atrules[atruleName].declarators[name] || null
|
||||
: null;
|
||||
}
|
||||
getProperty(propertyName, fallbackBasename = true) {
|
||||
const property = names.property(propertyName);
|
||||
const propertyEntry = property.vendor && fallbackBasename
|
||||
? this.properties[property.name] || this.properties[property.basename]
|
||||
: this.properties[property.name];
|
||||
|
||||
return propertyEntry || null;
|
||||
}
|
||||
getType(name) {
|
||||
return hasOwnProperty.call(this.types, name) ? this.types[name] : null;
|
||||
}
|
||||
|
||||
validate() {
|
||||
function syntaxRef(name, isType) {
|
||||
return isType ? `<${name}>` : `<'${name}'>`;
|
||||
}
|
||||
|
||||
function validate(syntax, name, broken, descriptor) {
|
||||
if (broken.has(name)) {
|
||||
return broken.get(name);
|
||||
}
|
||||
|
||||
broken.set(name, false);
|
||||
if (descriptor.syntax !== null) {
|
||||
walk.walk(descriptor.syntax, function(node) {
|
||||
if (node.type !== 'Type' && node.type !== 'Property') {
|
||||
return;
|
||||
}
|
||||
|
||||
const map = node.type === 'Type' ? syntax.types : syntax.properties;
|
||||
const brokenMap = node.type === 'Type' ? brokenTypes : brokenProperties;
|
||||
|
||||
if (!hasOwnProperty.call(map, node.name)) {
|
||||
errors.push(`${syntaxRef(name, broken === brokenTypes)} used missed syntax definition ${syntaxRef(node.name, node.type === 'Type')}`);
|
||||
broken.set(name, true);
|
||||
} else if (validate(syntax, node.name, brokenMap, map[node.name])) {
|
||||
errors.push(`${syntaxRef(name, broken === brokenTypes)} used broken syntax definition ${syntaxRef(node.name, node.type === 'Type')}`);
|
||||
broken.set(name, true);
|
||||
}
|
||||
}, this);
|
||||
}
|
||||
}
|
||||
|
||||
const errors = [];
|
||||
let brokenTypes = new Map();
|
||||
let brokenProperties = new Map();
|
||||
|
||||
for (const key in this.types) {
|
||||
validate(this, key, brokenTypes, this.types[key]);
|
||||
}
|
||||
|
||||
for (const key in this.properties) {
|
||||
validate(this, key, brokenProperties, this.properties[key]);
|
||||
}
|
||||
|
||||
const brokenTypesArray = [...brokenTypes.keys()].filter(name => brokenTypes.get(name));
|
||||
const brokenPropertiesArray = [...brokenProperties.keys()].filter(name => brokenProperties.get(name));
|
||||
|
||||
if (brokenTypesArray.length || brokenPropertiesArray.length) {
|
||||
return {
|
||||
errors,
|
||||
types: brokenTypesArray,
|
||||
properties: brokenPropertiesArray
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
dump(syntaxAsAst, pretty) {
|
||||
return {
|
||||
generic: this.generic,
|
||||
cssWideKeywords: this.cssWideKeywords,
|
||||
units: this.units,
|
||||
types: dumpMapSyntax(this.types, !pretty, syntaxAsAst),
|
||||
properties: dumpMapSyntax(this.properties, !pretty, syntaxAsAst),
|
||||
atrules: dumpAtruleMapSyntax(this.atrules, !pretty, syntaxAsAst)
|
||||
};
|
||||
}
|
||||
toString() {
|
||||
return JSON.stringify(this.dump());
|
||||
}
|
||||
}
|
||||
|
||||
exports.Lexer = Lexer;
|
||||
-128
@@ -1,128 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const createCustomError = require('../utils/create-custom-error.cjs');
|
||||
const generate = require('../definition-syntax/generate.cjs');
|
||||
|
||||
const defaultLoc = { offset: 0, line: 1, column: 1 };
|
||||
|
||||
function locateMismatch(matchResult, node) {
|
||||
const tokens = matchResult.tokens;
|
||||
const longestMatch = matchResult.longestMatch;
|
||||
const mismatchNode = longestMatch < tokens.length ? tokens[longestMatch].node || null : null;
|
||||
const badNode = mismatchNode !== node ? mismatchNode : null;
|
||||
let mismatchOffset = 0;
|
||||
let mismatchLength = 0;
|
||||
let entries = 0;
|
||||
let css = '';
|
||||
let start;
|
||||
let end;
|
||||
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
const token = tokens[i].value;
|
||||
|
||||
if (i === longestMatch) {
|
||||
mismatchLength = token.length;
|
||||
mismatchOffset = css.length;
|
||||
}
|
||||
|
||||
if (badNode !== null && tokens[i].node === badNode) {
|
||||
if (i <= longestMatch) {
|
||||
entries++;
|
||||
} else {
|
||||
entries = 0;
|
||||
}
|
||||
}
|
||||
|
||||
css += token;
|
||||
}
|
||||
|
||||
if (longestMatch === tokens.length || entries > 1) { // last
|
||||
start = fromLoc(badNode || node, 'end') || buildLoc(defaultLoc, css);
|
||||
end = buildLoc(start);
|
||||
} else {
|
||||
start = fromLoc(badNode, 'start') ||
|
||||
buildLoc(fromLoc(node, 'start') || defaultLoc, css.slice(0, mismatchOffset));
|
||||
end = fromLoc(badNode, 'end') ||
|
||||
buildLoc(start, css.substr(mismatchOffset, mismatchLength));
|
||||
}
|
||||
|
||||
return {
|
||||
css,
|
||||
mismatchOffset,
|
||||
mismatchLength,
|
||||
start,
|
||||
end
|
||||
};
|
||||
}
|
||||
|
||||
function fromLoc(node, point) {
|
||||
const value = node && node.loc && node.loc[point];
|
||||
|
||||
if (value) {
|
||||
return 'line' in value ? buildLoc(value) : value;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildLoc({ offset, line, column }, extra) {
|
||||
const loc = {
|
||||
offset,
|
||||
line,
|
||||
column
|
||||
};
|
||||
|
||||
if (extra) {
|
||||
const lines = extra.split(/\n|\r\n?|\f/);
|
||||
|
||||
loc.offset += extra.length;
|
||||
loc.line += lines.length - 1;
|
||||
loc.column = lines.length === 1 ? loc.column + extra.length : lines.pop().length + 1;
|
||||
}
|
||||
|
||||
return loc;
|
||||
}
|
||||
|
||||
const SyntaxReferenceError = function(type, referenceName) {
|
||||
const error = createCustomError.createCustomError(
|
||||
'SyntaxReferenceError',
|
||||
type + (referenceName ? ' `' + referenceName + '`' : '')
|
||||
);
|
||||
|
||||
error.reference = referenceName;
|
||||
|
||||
return error;
|
||||
};
|
||||
|
||||
const SyntaxMatchError = function(message, syntax, node, matchResult) {
|
||||
const error = createCustomError.createCustomError('SyntaxMatchError', message);
|
||||
const {
|
||||
css,
|
||||
mismatchOffset,
|
||||
mismatchLength,
|
||||
start,
|
||||
end
|
||||
} = locateMismatch(matchResult, node);
|
||||
|
||||
error.rawMessage = message;
|
||||
error.syntax = syntax ? generate.generate(syntax) : '<generic>';
|
||||
error.css = css;
|
||||
error.mismatchOffset = mismatchOffset;
|
||||
error.mismatchLength = mismatchLength;
|
||||
error.message = message + '\n' +
|
||||
' syntax: ' + error.syntax + '\n' +
|
||||
' value: ' + (css || '<empty string>') + '\n' +
|
||||
' --------' + new Array(error.mismatchOffset + 1).join('-') + '^';
|
||||
|
||||
Object.assign(error, start);
|
||||
error.loc = {
|
||||
source: (node && node.loc && node.loc.source) || '<unknown>',
|
||||
start,
|
||||
end
|
||||
};
|
||||
|
||||
return error;
|
||||
};
|
||||
|
||||
exports.SyntaxMatchError = SyntaxMatchError;
|
||||
exports.SyntaxReferenceError = SyntaxReferenceError;
|
||||
-235
@@ -1,235 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const charCodeDefinitions = require('../tokenizer/char-code-definitions.cjs');
|
||||
const types = require('../tokenizer/types.cjs');
|
||||
const utils = require('../tokenizer/utils.cjs');
|
||||
|
||||
const PLUSSIGN = 0x002B; // U+002B PLUS SIGN (+)
|
||||
const HYPHENMINUS = 0x002D; // U+002D HYPHEN-MINUS (-)
|
||||
const N = 0x006E; // U+006E LATIN SMALL LETTER N (n)
|
||||
const DISALLOW_SIGN = true;
|
||||
const ALLOW_SIGN = false;
|
||||
|
||||
function isDelim(token, code) {
|
||||
return token !== null && token.type === types.Delim && token.value.charCodeAt(0) === code;
|
||||
}
|
||||
|
||||
function skipSC(token, offset, getNextToken) {
|
||||
while (token !== null && (token.type === types.WhiteSpace || token.type === types.Comment)) {
|
||||
token = getNextToken(++offset);
|
||||
}
|
||||
|
||||
return offset;
|
||||
}
|
||||
|
||||
function checkInteger(token, valueOffset, disallowSign, offset) {
|
||||
if (!token) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const code = token.value.charCodeAt(valueOffset);
|
||||
|
||||
if (code === PLUSSIGN || code === HYPHENMINUS) {
|
||||
if (disallowSign) {
|
||||
// Number sign is not allowed
|
||||
return 0;
|
||||
}
|
||||
valueOffset++;
|
||||
}
|
||||
|
||||
for (; valueOffset < token.value.length; valueOffset++) {
|
||||
if (!charCodeDefinitions.isDigit(token.value.charCodeAt(valueOffset))) {
|
||||
// Integer is expected
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return offset + 1;
|
||||
}
|
||||
|
||||
// ... <signed-integer>
|
||||
// ... ['+' | '-'] <signless-integer>
|
||||
function consumeB(token, offset_, getNextToken) {
|
||||
let sign = false;
|
||||
let offset = skipSC(token, offset_, getNextToken);
|
||||
|
||||
token = getNextToken(offset);
|
||||
|
||||
if (token === null) {
|
||||
return offset_;
|
||||
}
|
||||
|
||||
if (token.type !== types.Number) {
|
||||
if (isDelim(token, PLUSSIGN) || isDelim(token, HYPHENMINUS)) {
|
||||
sign = true;
|
||||
offset = skipSC(getNextToken(++offset), offset, getNextToken);
|
||||
token = getNextToken(offset);
|
||||
|
||||
if (token === null || token.type !== types.Number) {
|
||||
return 0;
|
||||
}
|
||||
} else {
|
||||
return offset_;
|
||||
}
|
||||
}
|
||||
|
||||
if (!sign) {
|
||||
const code = token.value.charCodeAt(0);
|
||||
if (code !== PLUSSIGN && code !== HYPHENMINUS) {
|
||||
// Number sign is expected
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return checkInteger(token, sign ? 0 : 1, sign, offset);
|
||||
}
|
||||
|
||||
// An+B microsyntax https://www.w3.org/TR/css-syntax-3/#anb
|
||||
function anPlusB(token, getNextToken) {
|
||||
/* eslint-disable brace-style*/
|
||||
let offset = 0;
|
||||
|
||||
if (!token) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// <integer>
|
||||
if (token.type === types.Number) {
|
||||
return checkInteger(token, 0, ALLOW_SIGN, offset); // b
|
||||
}
|
||||
|
||||
// -n
|
||||
// -n <signed-integer>
|
||||
// -n ['+' | '-'] <signless-integer>
|
||||
// -n- <signless-integer>
|
||||
// <dashndashdigit-ident>
|
||||
else if (token.type === types.Ident && token.value.charCodeAt(0) === HYPHENMINUS) {
|
||||
// expect 1st char is N
|
||||
if (!utils.cmpChar(token.value, 1, N)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
switch (token.value.length) {
|
||||
// -n
|
||||
// -n <signed-integer>
|
||||
// -n ['+' | '-'] <signless-integer>
|
||||
case 2:
|
||||
return consumeB(getNextToken(++offset), offset, getNextToken);
|
||||
|
||||
// -n- <signless-integer>
|
||||
case 3:
|
||||
if (token.value.charCodeAt(2) !== HYPHENMINUS) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
offset = skipSC(getNextToken(++offset), offset, getNextToken);
|
||||
token = getNextToken(offset);
|
||||
|
||||
return checkInteger(token, 0, DISALLOW_SIGN, offset);
|
||||
|
||||
// <dashndashdigit-ident>
|
||||
default:
|
||||
if (token.value.charCodeAt(2) !== HYPHENMINUS) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return checkInteger(token, 3, DISALLOW_SIGN, offset);
|
||||
}
|
||||
}
|
||||
|
||||
// '+'? n
|
||||
// '+'? n <signed-integer>
|
||||
// '+'? n ['+' | '-'] <signless-integer>
|
||||
// '+'? n- <signless-integer>
|
||||
// '+'? <ndashdigit-ident>
|
||||
else if (token.type === types.Ident || (isDelim(token, PLUSSIGN) && getNextToken(offset + 1).type === types.Ident)) {
|
||||
// just ignore a plus
|
||||
if (token.type !== types.Ident) {
|
||||
token = getNextToken(++offset);
|
||||
}
|
||||
|
||||
if (token === null || !utils.cmpChar(token.value, 0, N)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
switch (token.value.length) {
|
||||
// '+'? n
|
||||
// '+'? n <signed-integer>
|
||||
// '+'? n ['+' | '-'] <signless-integer>
|
||||
case 1:
|
||||
return consumeB(getNextToken(++offset), offset, getNextToken);
|
||||
|
||||
// '+'? n- <signless-integer>
|
||||
case 2:
|
||||
if (token.value.charCodeAt(1) !== HYPHENMINUS) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
offset = skipSC(getNextToken(++offset), offset, getNextToken);
|
||||
token = getNextToken(offset);
|
||||
|
||||
return checkInteger(token, 0, DISALLOW_SIGN, offset);
|
||||
|
||||
// '+'? <ndashdigit-ident>
|
||||
default:
|
||||
if (token.value.charCodeAt(1) !== HYPHENMINUS) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return checkInteger(token, 2, DISALLOW_SIGN, offset);
|
||||
}
|
||||
}
|
||||
|
||||
// <ndashdigit-dimension>
|
||||
// <ndash-dimension> <signless-integer>
|
||||
// <n-dimension>
|
||||
// <n-dimension> <signed-integer>
|
||||
// <n-dimension> ['+' | '-'] <signless-integer>
|
||||
else if (token.type === types.Dimension) {
|
||||
let code = token.value.charCodeAt(0);
|
||||
let sign = code === PLUSSIGN || code === HYPHENMINUS ? 1 : 0;
|
||||
let i = sign;
|
||||
|
||||
for (; i < token.value.length; i++) {
|
||||
if (!charCodeDefinitions.isDigit(token.value.charCodeAt(i))) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (i === sign) {
|
||||
// Integer is expected
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!utils.cmpChar(token.value, i, N)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// <n-dimension>
|
||||
// <n-dimension> <signed-integer>
|
||||
// <n-dimension> ['+' | '-'] <signless-integer>
|
||||
if (i + 1 === token.value.length) {
|
||||
return consumeB(getNextToken(++offset), offset, getNextToken);
|
||||
} else {
|
||||
if (token.value.charCodeAt(i + 1) !== HYPHENMINUS) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// <ndash-dimension> <signless-integer>
|
||||
if (i + 2 === token.value.length) {
|
||||
offset = skipSC(getNextToken(++offset), offset, getNextToken);
|
||||
token = getNextToken(offset);
|
||||
|
||||
return checkInteger(token, 0, DISALLOW_SIGN, offset);
|
||||
}
|
||||
// <ndashdigit-dimension>
|
||||
else {
|
||||
return checkInteger(token, i + 2, DISALLOW_SIGN, offset);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
module.exports = anPlusB;
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
// https://drafts.csswg.org/css-cascade-5/
|
||||
const cssWideKeywords = [
|
||||
'initial',
|
||||
'inherit',
|
||||
'unset',
|
||||
'revert',
|
||||
'revert-layer'
|
||||
];
|
||||
|
||||
exports.cssWideKeywords = cssWideKeywords;
|
||||
-149
@@ -1,149 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const charCodeDefinitions = require('../tokenizer/char-code-definitions.cjs');
|
||||
const types = require('../tokenizer/types.cjs');
|
||||
const utils = require('../tokenizer/utils.cjs');
|
||||
|
||||
const PLUSSIGN = 0x002B; // U+002B PLUS SIGN (+)
|
||||
const HYPHENMINUS = 0x002D; // U+002D HYPHEN-MINUS (-)
|
||||
const QUESTIONMARK = 0x003F; // U+003F QUESTION MARK (?)
|
||||
const U = 0x0075; // U+0075 LATIN SMALL LETTER U (u)
|
||||
|
||||
function isDelim(token, code) {
|
||||
return token !== null && token.type === types.Delim && token.value.charCodeAt(0) === code;
|
||||
}
|
||||
|
||||
function startsWith(token, code) {
|
||||
return token.value.charCodeAt(0) === code;
|
||||
}
|
||||
|
||||
function hexSequence(token, offset, allowDash) {
|
||||
let hexlen = 0;
|
||||
|
||||
for (let pos = offset; pos < token.value.length; pos++) {
|
||||
const code = token.value.charCodeAt(pos);
|
||||
|
||||
if (code === HYPHENMINUS && allowDash && hexlen !== 0) {
|
||||
hexSequence(token, offset + hexlen + 1, false);
|
||||
return 6; // dissallow following question marks
|
||||
}
|
||||
|
||||
if (!charCodeDefinitions.isHexDigit(code)) {
|
||||
return 0; // not a hex digit
|
||||
}
|
||||
|
||||
if (++hexlen > 6) {
|
||||
return 0; // too many hex digits
|
||||
} }
|
||||
|
||||
return hexlen;
|
||||
}
|
||||
|
||||
function withQuestionMarkSequence(consumed, length, getNextToken) {
|
||||
if (!consumed) {
|
||||
return 0; // nothing consumed
|
||||
}
|
||||
|
||||
while (isDelim(getNextToken(length), QUESTIONMARK)) {
|
||||
if (++consumed > 6) {
|
||||
return 0; // too many question marks
|
||||
}
|
||||
|
||||
length++;
|
||||
}
|
||||
|
||||
return length;
|
||||
}
|
||||
|
||||
// https://drafts.csswg.org/css-syntax/#urange
|
||||
// Informally, the <urange> production has three forms:
|
||||
// U+0001
|
||||
// Defines a range consisting of a single code point, in this case the code point "1".
|
||||
// U+0001-00ff
|
||||
// Defines a range of codepoints between the first and the second value, in this case
|
||||
// the range between "1" and "ff" (255 in decimal) inclusive.
|
||||
// U+00??
|
||||
// Defines a range of codepoints where the "?" characters range over all hex digits,
|
||||
// in this case defining the same as the value U+0000-00ff.
|
||||
// In each form, a maximum of 6 digits is allowed for each hexadecimal number (if you treat "?" as a hexadecimal digit).
|
||||
//
|
||||
// <urange> =
|
||||
// u '+' <ident-token> '?'* |
|
||||
// u <dimension-token> '?'* |
|
||||
// u <number-token> '?'* |
|
||||
// u <number-token> <dimension-token> |
|
||||
// u <number-token> <number-token> |
|
||||
// u '+' '?'+
|
||||
function urange(token, getNextToken) {
|
||||
let length = 0;
|
||||
|
||||
// should start with `u` or `U`
|
||||
if (token === null || token.type !== types.Ident || !utils.cmpChar(token.value, 0, U)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
token = getNextToken(++length);
|
||||
if (token === null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// u '+' <ident-token> '?'*
|
||||
// u '+' '?'+
|
||||
if (isDelim(token, PLUSSIGN)) {
|
||||
token = getNextToken(++length);
|
||||
if (token === null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (token.type === types.Ident) {
|
||||
// u '+' <ident-token> '?'*
|
||||
return withQuestionMarkSequence(hexSequence(token, 0, true), ++length, getNextToken);
|
||||
}
|
||||
|
||||
if (isDelim(token, QUESTIONMARK)) {
|
||||
// u '+' '?'+
|
||||
return withQuestionMarkSequence(1, ++length, getNextToken);
|
||||
}
|
||||
|
||||
// Hex digit or question mark is expected
|
||||
return 0;
|
||||
}
|
||||
|
||||
// u <number-token> '?'*
|
||||
// u <number-token> <dimension-token>
|
||||
// u <number-token> <number-token>
|
||||
if (token.type === types.Number) {
|
||||
const consumedHexLength = hexSequence(token, 1, true);
|
||||
if (consumedHexLength === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
token = getNextToken(++length);
|
||||
if (token === null) {
|
||||
// u <number-token> <eof>
|
||||
return length;
|
||||
}
|
||||
|
||||
if (token.type === types.Dimension || token.type === types.Number) {
|
||||
// u <number-token> <dimension-token>
|
||||
// u <number-token> <number-token>
|
||||
if (!startsWith(token, HYPHENMINUS) || !hexSequence(token, 1, false)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return length + 1;
|
||||
}
|
||||
|
||||
// u <number-token> '?'*
|
||||
return withQuestionMarkSequence(consumedHexLength, length, getNextToken);
|
||||
}
|
||||
|
||||
// u <dimension-token> '?'*
|
||||
if (token.type === types.Dimension) {
|
||||
return withQuestionMarkSequence(hexSequence(token, 1, true), ++length, getNextToken);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
module.exports = urange;
|
||||
-674
@@ -1,674 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const genericConst = require('./generic-const.cjs');
|
||||
const genericAnPlusB = require('./generic-an-plus-b.cjs');
|
||||
const genericUrange = require('./generic-urange.cjs');
|
||||
const charCodeDefinitions = require('../tokenizer/char-code-definitions.cjs');
|
||||
const types = require('../tokenizer/types.cjs');
|
||||
const utils = require('../tokenizer/utils.cjs');
|
||||
|
||||
// CSS mathematical functions categorized by return type behavior
|
||||
// See: https://www.w3.org/TR/css-values-4/#math
|
||||
|
||||
// Calculation functions that return different types depending on input
|
||||
const calcFunctionNames = [
|
||||
'calc(',
|
||||
'-moz-calc(',
|
||||
'-webkit-calc('
|
||||
];
|
||||
|
||||
// Comparison functions that return different types depending on input
|
||||
const comparisonFunctionNames = [
|
||||
'min(',
|
||||
'max(',
|
||||
'clamp('
|
||||
];
|
||||
|
||||
// Functions that return a stepped value, i.e. a value that is rounded to the nearest step
|
||||
const steppedValueFunctionNames = [
|
||||
'round(',
|
||||
'mod(',
|
||||
'rem('
|
||||
];
|
||||
|
||||
// Trigonometrical functions that return a <number>
|
||||
const trigNumberFunctionNames = [
|
||||
'sin(',
|
||||
'cos(',
|
||||
'tan('
|
||||
];
|
||||
|
||||
// Trigonometrical functions that return a <angle>
|
||||
const trigAngleFunctionNames = [
|
||||
'asin(',
|
||||
'acos(',
|
||||
'atan(',
|
||||
'atan2('
|
||||
];
|
||||
|
||||
// Other functions that return a <number>
|
||||
const otherNumberFunctionNames = [
|
||||
'pow(',
|
||||
'sqrt(',
|
||||
'log(',
|
||||
'exp(',
|
||||
'sign('
|
||||
];
|
||||
|
||||
// Exponential functions that return a <number> or <dimension> or <percentage>
|
||||
const expNumberDimensionPercentageFunctionNames = [
|
||||
'hypot('
|
||||
];
|
||||
|
||||
// Return the same type as the input
|
||||
const signFunctionNames = [
|
||||
'abs('
|
||||
];
|
||||
|
||||
const numberFunctionNames = [
|
||||
...calcFunctionNames,
|
||||
...comparisonFunctionNames,
|
||||
...steppedValueFunctionNames,
|
||||
...trigNumberFunctionNames,
|
||||
...otherNumberFunctionNames,
|
||||
...expNumberDimensionPercentageFunctionNames,
|
||||
...signFunctionNames
|
||||
];
|
||||
|
||||
const percentageFunctionNames = [
|
||||
...calcFunctionNames,
|
||||
...comparisonFunctionNames,
|
||||
...steppedValueFunctionNames,
|
||||
...expNumberDimensionPercentageFunctionNames,
|
||||
...signFunctionNames
|
||||
];
|
||||
|
||||
const dimensionFunctionNames = [
|
||||
...calcFunctionNames,
|
||||
...comparisonFunctionNames,
|
||||
...steppedValueFunctionNames,
|
||||
...trigAngleFunctionNames,
|
||||
...expNumberDimensionPercentageFunctionNames,
|
||||
...signFunctionNames
|
||||
];
|
||||
|
||||
const balancePair = new Map([
|
||||
[types.Function, types.RightParenthesis],
|
||||
[types.LeftParenthesis, types.RightParenthesis],
|
||||
[types.LeftSquareBracket, types.RightSquareBracket],
|
||||
[types.LeftCurlyBracket, types.RightCurlyBracket]
|
||||
]);
|
||||
|
||||
// safe char code getter
|
||||
function charCodeAt(str, index) {
|
||||
return index < str.length ? str.charCodeAt(index) : 0;
|
||||
}
|
||||
|
||||
function eqStr(actual, expected) {
|
||||
return utils.cmpStr(actual, 0, actual.length, expected);
|
||||
}
|
||||
|
||||
function eqStrAny(actual, expected) {
|
||||
for (let i = 0; i < expected.length; i++) {
|
||||
if (eqStr(actual, expected[i])) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// IE postfix hack, i.e. 123\0 or 123px\9
|
||||
function isPostfixIeHack(str, offset) {
|
||||
if (offset !== str.length - 2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
charCodeAt(str, offset) === 0x005C && // U+005C REVERSE SOLIDUS (\)
|
||||
charCodeDefinitions.isDigit(charCodeAt(str, offset + 1))
|
||||
);
|
||||
}
|
||||
|
||||
function outOfRange(opts, value, numEnd) {
|
||||
if (opts && opts.type === 'Range') {
|
||||
const num = Number(
|
||||
numEnd !== undefined && numEnd !== value.length
|
||||
? value.substr(0, numEnd)
|
||||
: value
|
||||
);
|
||||
|
||||
if (isNaN(num)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// FIXME: when opts.min is a string it's a dimension, skip a range validation
|
||||
// for now since it requires a type covertation which is not implmented yet
|
||||
if (opts.min !== null && num < opts.min && typeof opts.min !== 'string') {
|
||||
return true;
|
||||
}
|
||||
|
||||
// FIXME: when opts.max is a string it's a dimension, skip a range validation
|
||||
// for now since it requires a type covertation which is not implmented yet
|
||||
if (opts.max !== null && num > opts.max && typeof opts.max !== 'string') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function consumeFunction(token, getNextToken) {
|
||||
let balanceCloseType = 0;
|
||||
let balanceStash = [];
|
||||
let length = 0;
|
||||
|
||||
// balanced token consuming
|
||||
scan:
|
||||
do {
|
||||
switch (token.type) {
|
||||
case types.RightCurlyBracket:
|
||||
case types.RightParenthesis:
|
||||
case types.RightSquareBracket:
|
||||
if (token.type !== balanceCloseType) {
|
||||
break scan;
|
||||
}
|
||||
|
||||
balanceCloseType = balanceStash.pop();
|
||||
|
||||
if (balanceStash.length === 0) {
|
||||
length++;
|
||||
break scan;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case types.Function:
|
||||
case types.LeftParenthesis:
|
||||
case types.LeftSquareBracket:
|
||||
case types.LeftCurlyBracket:
|
||||
balanceStash.push(balanceCloseType);
|
||||
balanceCloseType = balancePair.get(token.type);
|
||||
break;
|
||||
}
|
||||
|
||||
length++;
|
||||
} while (token = getNextToken(length));
|
||||
|
||||
return length;
|
||||
}
|
||||
|
||||
|
||||
// TODO: implement
|
||||
// can be used wherever <length>, <frequency>, <angle>, <time>, <percentage>, <number>, or <integer> values are allowed
|
||||
// https://drafts.csswg.org/css-values/#calc-notation
|
||||
function math(next, functionNames) {
|
||||
return function(token, getNextToken, opts) {
|
||||
if (token === null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (token.type === types.Function && eqStrAny(token.value, functionNames)) {
|
||||
return consumeFunction(token, getNextToken);
|
||||
}
|
||||
|
||||
return next(token, getNextToken, opts);
|
||||
};
|
||||
}
|
||||
|
||||
function tokenType(expectedTokenType) {
|
||||
return function(token) {
|
||||
if (token === null || token.type !== expectedTokenType) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 1;
|
||||
};
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Complex types
|
||||
//
|
||||
|
||||
// https://drafts.csswg.org/css-values-4/#custom-idents
|
||||
// 4.2. Author-defined Identifiers: the <custom-ident> type
|
||||
// Some properties accept arbitrary author-defined identifiers as a component value.
|
||||
// This generic data type is denoted by <custom-ident>, and represents any valid CSS identifier
|
||||
// that would not be misinterpreted as a pre-defined keyword in that property’s value definition.
|
||||
//
|
||||
// See also: https://developer.mozilla.org/en-US/docs/Web/CSS/custom-ident
|
||||
function customIdent(token) {
|
||||
if (token === null || token.type !== types.Ident) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const name = token.value.toLowerCase();
|
||||
|
||||
// The CSS-wide keywords are not valid <custom-ident>s
|
||||
if (eqStrAny(name, genericConst.cssWideKeywords)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The default keyword is reserved and is also not a valid <custom-ident>
|
||||
if (eqStr(name, 'default')) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// TODO: ignore property specific keywords (as described https://developer.mozilla.org/en-US/docs/Web/CSS/custom-ident)
|
||||
// Specifications using <custom-ident> must specify clearly what other keywords
|
||||
// are excluded from <custom-ident>, if any—for example by saying that any pre-defined keywords
|
||||
// in that property’s value definition are excluded. Excluded keywords are excluded
|
||||
// in all ASCII case permutations.
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
// https://drafts.csswg.org/css-values-4/#dashed-idents
|
||||
// The <dashed-ident> production is a <custom-ident>, with all the case-sensitivity that implies,
|
||||
// with the additional restriction that it must start with two dashes (U+002D HYPHEN-MINUS).
|
||||
function dashedIdent(token) {
|
||||
if (token === null || token.type !== types.Ident) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ... must start with two dashes (U+002D HYPHEN-MINUS)
|
||||
if (charCodeAt(token.value, 0) !== 0x002D || charCodeAt(token.value, 1) !== 0x002D) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
// https://drafts.csswg.org/css-variables/#typedef-custom-property-name
|
||||
// A custom property is any property whose name starts with two dashes (U+002D HYPHEN-MINUS), like --foo.
|
||||
// The <custom-property-name> production corresponds to this: it’s defined as any <dashed-ident>
|
||||
// (a valid identifier that starts with two dashes), except -- itself, which is reserved for future use by CSS.
|
||||
function customPropertyName(token) {
|
||||
// ... it’s defined as any <dashed-ident>
|
||||
if (!dashedIdent(token)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ... except -- itself, which is reserved for future use by CSS
|
||||
if (token.value === '--') {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
// https://drafts.csswg.org/css-color-4/#hex-notation
|
||||
// The syntax of a <hex-color> is a <hash-token> token whose value consists of 3, 4, 6, or 8 hexadecimal digits.
|
||||
// In other words, a hex color is written as a hash character, "#", followed by some number of digits 0-9 or
|
||||
// letters a-f (the case of the letters doesn’t matter - #00ff00 is identical to #00FF00).
|
||||
function hexColor(token) {
|
||||
if (token === null || token.type !== types.Hash) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const length = token.value.length;
|
||||
|
||||
// valid values (length): #rgb (4), #rgba (5), #rrggbb (7), #rrggbbaa (9)
|
||||
if (length !== 4 && length !== 5 && length !== 7 && length !== 9) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
for (let i = 1; i < length; i++) {
|
||||
if (!charCodeDefinitions.isHexDigit(charCodeAt(token.value, i))) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
function idSelector(token) {
|
||||
if (token === null || token.type !== types.Hash) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!charCodeDefinitions.isIdentifierStart(charCodeAt(token.value, 1), charCodeAt(token.value, 2), charCodeAt(token.value, 3))) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
// https://drafts.csswg.org/css-syntax/#any-value
|
||||
// It represents the entirety of what a valid declaration can have as its value.
|
||||
function declarationValue(token, getNextToken) {
|
||||
if (!token) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let balanceCloseType = 0;
|
||||
let balanceStash = [];
|
||||
let length = 0;
|
||||
|
||||
// The <declaration-value> production matches any sequence of one or more tokens,
|
||||
// so long as the sequence does not contain ...
|
||||
scan:
|
||||
do {
|
||||
switch (token.type) {
|
||||
// ... <bad-string-token>, <bad-url-token>,
|
||||
case types.BadString:
|
||||
case types.BadUrl:
|
||||
break scan;
|
||||
|
||||
// ... unmatched <)-token>, <]-token>, or <}-token>,
|
||||
case types.RightCurlyBracket:
|
||||
case types.RightParenthesis:
|
||||
case types.RightSquareBracket:
|
||||
if (token.type !== balanceCloseType) {
|
||||
break scan;
|
||||
}
|
||||
|
||||
balanceCloseType = balanceStash.pop();
|
||||
break;
|
||||
|
||||
// ... or top-level <semicolon-token> tokens
|
||||
case types.Semicolon:
|
||||
if (balanceCloseType === 0) {
|
||||
break scan;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
// ... or <delim-token> tokens with a value of "!"
|
||||
case types.Delim:
|
||||
if (balanceCloseType === 0 && token.value === '!') {
|
||||
break scan;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case types.Function:
|
||||
case types.LeftParenthesis:
|
||||
case types.LeftSquareBracket:
|
||||
case types.LeftCurlyBracket:
|
||||
balanceStash.push(balanceCloseType);
|
||||
balanceCloseType = balancePair.get(token.type);
|
||||
break;
|
||||
}
|
||||
|
||||
length++;
|
||||
} while (token = getNextToken(length));
|
||||
|
||||
return length;
|
||||
}
|
||||
|
||||
// https://drafts.csswg.org/css-syntax/#any-value
|
||||
// The <any-value> production is identical to <declaration-value>, but also
|
||||
// allows top-level <semicolon-token> tokens and <delim-token> tokens
|
||||
// with a value of "!". It represents the entirety of what valid CSS can be in any context.
|
||||
function anyValue(token, getNextToken) {
|
||||
if (!token) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let balanceCloseType = 0;
|
||||
let balanceStash = [];
|
||||
let length = 0;
|
||||
|
||||
// The <any-value> production matches any sequence of one or more tokens,
|
||||
// so long as the sequence ...
|
||||
scan:
|
||||
do {
|
||||
switch (token.type) {
|
||||
// ... does not contain <bad-string-token>, <bad-url-token>,
|
||||
case types.BadString:
|
||||
case types.BadUrl:
|
||||
break scan;
|
||||
|
||||
// ... unmatched <)-token>, <]-token>, or <}-token>,
|
||||
case types.RightCurlyBracket:
|
||||
case types.RightParenthesis:
|
||||
case types.RightSquareBracket:
|
||||
if (token.type !== balanceCloseType) {
|
||||
break scan;
|
||||
}
|
||||
|
||||
balanceCloseType = balanceStash.pop();
|
||||
break;
|
||||
|
||||
case types.Function:
|
||||
case types.LeftParenthesis:
|
||||
case types.LeftSquareBracket:
|
||||
case types.LeftCurlyBracket:
|
||||
balanceStash.push(balanceCloseType);
|
||||
balanceCloseType = balancePair.get(token.type);
|
||||
break;
|
||||
}
|
||||
|
||||
length++;
|
||||
} while (token = getNextToken(length));
|
||||
|
||||
return length;
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Dimensions
|
||||
//
|
||||
|
||||
function dimension(type) {
|
||||
if (type) {
|
||||
type = new Set(type);
|
||||
}
|
||||
|
||||
return function(token, getNextToken, opts) {
|
||||
if (token === null || token.type !== types.Dimension) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const numberEnd = utils.consumeNumber(token.value, 0);
|
||||
|
||||
// check unit
|
||||
if (type !== null) {
|
||||
// check for IE postfix hack, i.e. 123px\0 or 123px\9
|
||||
const reverseSolidusOffset = token.value.indexOf('\\', numberEnd);
|
||||
const unit = reverseSolidusOffset === -1 || !isPostfixIeHack(token.value, reverseSolidusOffset)
|
||||
? token.value.substr(numberEnd)
|
||||
: token.value.substring(numberEnd, reverseSolidusOffset);
|
||||
|
||||
if (type.has(unit.toLowerCase()) === false) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// check range if specified
|
||||
if (outOfRange(opts, token.value, numberEnd)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 1;
|
||||
};
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Percentage
|
||||
//
|
||||
|
||||
// §5.5. Percentages: the <percentage> type
|
||||
// https://drafts.csswg.org/css-values-4/#percentages
|
||||
function percentage(token, getNextToken, opts) {
|
||||
// ... corresponds to the <percentage-token> production
|
||||
if (token === null || token.type !== types.Percentage) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// check range if specified
|
||||
if (outOfRange(opts, token.value, token.value.length - 1)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Numeric
|
||||
//
|
||||
|
||||
// https://drafts.csswg.org/css-values-4/#numbers
|
||||
// The value <zero> represents a literal number with the value 0. Expressions that merely
|
||||
// evaluate to a <number> with the value 0 (for example, calc(0)) do not match <zero>;
|
||||
// only literal <number-token>s do.
|
||||
function zero(next) {
|
||||
if (typeof next !== 'function') {
|
||||
next = function() {
|
||||
return 0;
|
||||
};
|
||||
}
|
||||
|
||||
return function(token, getNextToken, opts) {
|
||||
if (token !== null && token.type === types.Number) {
|
||||
if (Number(token.value) === 0) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
return next(token, getNextToken, opts);
|
||||
};
|
||||
}
|
||||
|
||||
// § 5.3. Real Numbers: the <number> type
|
||||
// https://drafts.csswg.org/css-values-4/#numbers
|
||||
// Number values are denoted by <number>, and represent real numbers, possibly with a fractional component.
|
||||
// ... It corresponds to the <number-token> production
|
||||
function number(token, getNextToken, opts) {
|
||||
if (token === null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const numberEnd = utils.consumeNumber(token.value, 0);
|
||||
const isNumber = numberEnd === token.value.length;
|
||||
if (!isNumber && !isPostfixIeHack(token.value, numberEnd)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// check range if specified
|
||||
if (outOfRange(opts, token.value, numberEnd)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
// §5.2. Integers: the <integer> type
|
||||
// https://drafts.csswg.org/css-values-4/#integers
|
||||
function integer(token, getNextToken, opts) {
|
||||
// ... corresponds to a subset of the <number-token> production
|
||||
if (token === null || token.type !== types.Number) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The first digit of an integer may be immediately preceded by `-` or `+` to indicate the integer’s sign.
|
||||
let i = charCodeAt(token.value, 0) === 0x002B || // U+002B PLUS SIGN (+)
|
||||
charCodeAt(token.value, 0) === 0x002D ? 1 : 0; // U+002D HYPHEN-MINUS (-)
|
||||
|
||||
// When written literally, an integer is one or more decimal digits 0 through 9 ...
|
||||
for (; i < token.value.length; i++) {
|
||||
if (!charCodeDefinitions.isDigit(charCodeAt(token.value, i))) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// check range if specified
|
||||
if (outOfRange(opts, token.value, i)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
// token types
|
||||
const tokenTypes = {
|
||||
'ident-token': tokenType(types.Ident),
|
||||
'function-token': tokenType(types.Function),
|
||||
'at-keyword-token': tokenType(types.AtKeyword),
|
||||
'hash-token': tokenType(types.Hash),
|
||||
'string-token': tokenType(types.String),
|
||||
'bad-string-token': tokenType(types.BadString),
|
||||
'url-token': tokenType(types.Url),
|
||||
'bad-url-token': tokenType(types.BadUrl),
|
||||
'delim-token': tokenType(types.Delim),
|
||||
'number-token': tokenType(types.Number),
|
||||
'percentage-token': tokenType(types.Percentage),
|
||||
'dimension-token': tokenType(types.Dimension),
|
||||
'whitespace-token': tokenType(types.WhiteSpace),
|
||||
'CDO-token': tokenType(types.CDO),
|
||||
'CDC-token': tokenType(types.CDC),
|
||||
'colon-token': tokenType(types.Colon),
|
||||
'semicolon-token': tokenType(types.Semicolon),
|
||||
'comma-token': tokenType(types.Comma),
|
||||
'[-token': tokenType(types.LeftSquareBracket),
|
||||
']-token': tokenType(types.RightSquareBracket),
|
||||
'(-token': tokenType(types.LeftParenthesis),
|
||||
')-token': tokenType(types.RightParenthesis),
|
||||
'{-token': tokenType(types.LeftCurlyBracket),
|
||||
'}-token': tokenType(types.RightCurlyBracket)
|
||||
};
|
||||
|
||||
// token production types
|
||||
const productionTypes = {
|
||||
// token type aliases
|
||||
'string': tokenType(types.String),
|
||||
'ident': tokenType(types.Ident),
|
||||
|
||||
// percentage
|
||||
'percentage': math(percentage, percentageFunctionNames),
|
||||
|
||||
// numeric
|
||||
'zero': zero(),
|
||||
'number': math(number, numberFunctionNames),
|
||||
'integer': math(integer, numberFunctionNames),
|
||||
|
||||
// complex types
|
||||
'custom-ident': customIdent,
|
||||
'dashed-ident': dashedIdent,
|
||||
'custom-property-name': customPropertyName,
|
||||
'hex-color': hexColor,
|
||||
'id-selector': idSelector, // element( <id-selector> )
|
||||
'an-plus-b': genericAnPlusB,
|
||||
'urange': genericUrange,
|
||||
'declaration-value': declarationValue,
|
||||
'any-value': anyValue
|
||||
};
|
||||
|
||||
// dimensions types depend on units set
|
||||
function createDemensionTypes(units) {
|
||||
const {
|
||||
angle,
|
||||
decibel,
|
||||
frequency,
|
||||
flex,
|
||||
length,
|
||||
resolution,
|
||||
semitones,
|
||||
time
|
||||
} = units || {};
|
||||
|
||||
return {
|
||||
'dimension': math(dimension(null), dimensionFunctionNames),
|
||||
'angle': math(dimension(angle), dimensionFunctionNames),
|
||||
'decibel': math(dimension(decibel), dimensionFunctionNames),
|
||||
'frequency': math(dimension(frequency), dimensionFunctionNames),
|
||||
'flex': math(dimension(flex), dimensionFunctionNames),
|
||||
'length': math(zero(dimension(length)), dimensionFunctionNames),
|
||||
'resolution': math(dimension(resolution), dimensionFunctionNames),
|
||||
'semitones': math(dimension(semitones), dimensionFunctionNames),
|
||||
'time': math(dimension(time), dimensionFunctionNames)
|
||||
};
|
||||
}
|
||||
|
||||
function createGenericTypes(units) {
|
||||
return {
|
||||
...tokenTypes,
|
||||
...productionTypes,
|
||||
...createDemensionTypes(units)
|
||||
};
|
||||
}
|
||||
|
||||
exports.createDemensionTypes = createDemensionTypes;
|
||||
exports.createGenericTypes = createGenericTypes;
|
||||
exports.productionTypes = productionTypes;
|
||||
exports.tokenTypes = tokenTypes;
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const Lexer = require('./Lexer.cjs');
|
||||
|
||||
|
||||
|
||||
exports.Lexer = Lexer.Lexer;
|
||||
-530
@@ -1,530 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const parse = require('../definition-syntax/parse.cjs');
|
||||
|
||||
const MATCH = { type: 'Match' };
|
||||
const MISMATCH = { type: 'Mismatch' };
|
||||
const DISALLOW_EMPTY = { type: 'DisallowEmpty' };
|
||||
|
||||
const LEFTPARENTHESIS = 40; // (
|
||||
const RIGHTPARENTHESIS = 41; // )
|
||||
|
||||
function createCondition(match, thenBranch, elseBranch) {
|
||||
// reduce node count
|
||||
if (thenBranch === MATCH && elseBranch === MISMATCH) {
|
||||
return match;
|
||||
}
|
||||
|
||||
if (match === MATCH && thenBranch === MATCH && elseBranch === MATCH) {
|
||||
return match;
|
||||
}
|
||||
|
||||
if (match.type === 'If' && match.else === MISMATCH && thenBranch === MATCH) {
|
||||
thenBranch = match.then;
|
||||
match = match.match;
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'If',
|
||||
match,
|
||||
then: thenBranch,
|
||||
else: elseBranch
|
||||
};
|
||||
}
|
||||
|
||||
function isFunctionType(name) {
|
||||
return (
|
||||
name.length > 2 &&
|
||||
name.charCodeAt(name.length - 2) === LEFTPARENTHESIS &&
|
||||
name.charCodeAt(name.length - 1) === RIGHTPARENTHESIS
|
||||
);
|
||||
}
|
||||
|
||||
function isEnumCapatible(term) {
|
||||
return (
|
||||
term.type === 'Keyword' ||
|
||||
term.type === 'AtKeyword' ||
|
||||
term.type === 'Function' ||
|
||||
term.type === 'Type' && isFunctionType(term.name)
|
||||
);
|
||||
}
|
||||
|
||||
function groupNode(terms, combinator = ' ', explicit = false) {
|
||||
return {
|
||||
type: 'Group',
|
||||
terms,
|
||||
combinator,
|
||||
disallowEmpty: false,
|
||||
explicit
|
||||
};
|
||||
}
|
||||
|
||||
function replaceTypeInGraph(node, replacements, visited = new Set()) {
|
||||
if (!visited.has(node)) {
|
||||
visited.add(node);
|
||||
|
||||
switch (node.type) {
|
||||
case 'If':
|
||||
node.match = replaceTypeInGraph(node.match, replacements, visited);
|
||||
node.then = replaceTypeInGraph(node.then, replacements, visited);
|
||||
node.else = replaceTypeInGraph(node.else, replacements, visited);
|
||||
break;
|
||||
|
||||
case 'Type':
|
||||
return replacements[node.name] || node;
|
||||
}
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
function buildGroupMatchGraph(combinator, terms, atLeastOneTermMatched) {
|
||||
switch (combinator) {
|
||||
case ' ': {
|
||||
// Juxtaposing components means that all of them must occur, in the given order.
|
||||
//
|
||||
// a b c
|
||||
// =
|
||||
// match a
|
||||
// then match b
|
||||
// then match c
|
||||
// then MATCH
|
||||
// else MISMATCH
|
||||
// else MISMATCH
|
||||
// else MISMATCH
|
||||
let result = MATCH;
|
||||
|
||||
for (let i = terms.length - 1; i >= 0; i--) {
|
||||
const term = terms[i];
|
||||
|
||||
result = createCondition(
|
||||
term,
|
||||
result,
|
||||
MISMATCH
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
case '|': {
|
||||
// A bar (|) separates two or more alternatives: exactly one of them must occur.
|
||||
//
|
||||
// a | b | c
|
||||
// =
|
||||
// match a
|
||||
// then MATCH
|
||||
// else match b
|
||||
// then MATCH
|
||||
// else match c
|
||||
// then MATCH
|
||||
// else MISMATCH
|
||||
|
||||
let result = MISMATCH;
|
||||
let map = null;
|
||||
|
||||
for (let i = terms.length - 1; i >= 0; i--) {
|
||||
let term = terms[i];
|
||||
|
||||
// reduce sequence of keywords into a Enum
|
||||
if (isEnumCapatible(term)) {
|
||||
if (map === null && i > 0 && isEnumCapatible(terms[i - 1])) {
|
||||
map = Object.create(null);
|
||||
result = createCondition(
|
||||
{
|
||||
type: 'Enum',
|
||||
map
|
||||
},
|
||||
MATCH,
|
||||
result
|
||||
);
|
||||
}
|
||||
|
||||
if (map !== null) {
|
||||
const key = (isFunctionType(term.name) ? term.name.slice(0, -1) : term.name).toLowerCase();
|
||||
if (key in map === false) {
|
||||
map[key] = term;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
map = null;
|
||||
|
||||
// create a new conditonal node
|
||||
result = createCondition(
|
||||
term,
|
||||
MATCH,
|
||||
result
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
case '&&': {
|
||||
// A double ampersand (&&) separates two or more components,
|
||||
// all of which must occur, in any order.
|
||||
|
||||
// Use MatchOnce for groups with a large number of terms,
|
||||
// since &&-groups produces at least N!-node trees
|
||||
if (terms.length > 5) {
|
||||
return {
|
||||
type: 'MatchOnce',
|
||||
terms,
|
||||
all: true
|
||||
};
|
||||
}
|
||||
|
||||
// Use a combination tree for groups with small number of terms
|
||||
//
|
||||
// a && b && c
|
||||
// =
|
||||
// match a
|
||||
// then [b && c]
|
||||
// else match b
|
||||
// then [a && c]
|
||||
// else match c
|
||||
// then [a && b]
|
||||
// else MISMATCH
|
||||
//
|
||||
// a && b
|
||||
// =
|
||||
// match a
|
||||
// then match b
|
||||
// then MATCH
|
||||
// else MISMATCH
|
||||
// else match b
|
||||
// then match a
|
||||
// then MATCH
|
||||
// else MISMATCH
|
||||
// else MISMATCH
|
||||
let result = MISMATCH;
|
||||
|
||||
for (let i = terms.length - 1; i >= 0; i--) {
|
||||
const term = terms[i];
|
||||
let thenClause;
|
||||
|
||||
if (terms.length > 1) {
|
||||
thenClause = buildGroupMatchGraph(
|
||||
combinator,
|
||||
terms.filter(function(newGroupTerm) {
|
||||
return newGroupTerm !== term;
|
||||
}),
|
||||
false
|
||||
);
|
||||
} else {
|
||||
thenClause = MATCH;
|
||||
}
|
||||
|
||||
result = createCondition(
|
||||
term,
|
||||
thenClause,
|
||||
result
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
case '||': {
|
||||
// A double bar (||) separates two or more options:
|
||||
// one or more of them must occur, in any order.
|
||||
|
||||
// Use MatchOnce for groups with a large number of terms,
|
||||
// since ||-groups produces at least N!-node trees
|
||||
if (terms.length > 5) {
|
||||
return {
|
||||
type: 'MatchOnce',
|
||||
terms,
|
||||
all: false
|
||||
};
|
||||
}
|
||||
|
||||
// Use a combination tree for groups with small number of terms
|
||||
//
|
||||
// a || b || c
|
||||
// =
|
||||
// match a
|
||||
// then [b || c]
|
||||
// else match b
|
||||
// then [a || c]
|
||||
// else match c
|
||||
// then [a || b]
|
||||
// else MISMATCH
|
||||
//
|
||||
// a || b
|
||||
// =
|
||||
// match a
|
||||
// then match b
|
||||
// then MATCH
|
||||
// else MATCH
|
||||
// else match b
|
||||
// then match a
|
||||
// then MATCH
|
||||
// else MATCH
|
||||
// else MISMATCH
|
||||
let result = atLeastOneTermMatched ? MATCH : MISMATCH;
|
||||
|
||||
for (let i = terms.length - 1; i >= 0; i--) {
|
||||
const term = terms[i];
|
||||
let thenClause;
|
||||
|
||||
if (terms.length > 1) {
|
||||
thenClause = buildGroupMatchGraph(
|
||||
combinator,
|
||||
terms.filter(function(newGroupTerm) {
|
||||
return newGroupTerm !== term;
|
||||
}),
|
||||
true
|
||||
);
|
||||
} else {
|
||||
thenClause = MATCH;
|
||||
}
|
||||
|
||||
result = createCondition(
|
||||
term,
|
||||
thenClause,
|
||||
result
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function buildMultiplierMatchGraph(node) {
|
||||
let result = MATCH;
|
||||
let matchTerm = buildMatchGraphInternal(node.term);
|
||||
|
||||
if (node.max === 0) {
|
||||
// disable repeating of empty match to prevent infinite loop
|
||||
matchTerm = createCondition(
|
||||
matchTerm,
|
||||
DISALLOW_EMPTY,
|
||||
MISMATCH
|
||||
);
|
||||
|
||||
// an occurrence count is not limited, make a cycle;
|
||||
// to collect more terms on each following matching mismatch
|
||||
result = createCondition(
|
||||
matchTerm,
|
||||
null, // will be a loop
|
||||
MISMATCH
|
||||
);
|
||||
|
||||
result.then = createCondition(
|
||||
MATCH,
|
||||
MATCH,
|
||||
result // make a loop
|
||||
);
|
||||
|
||||
if (node.comma) {
|
||||
result.then.else = createCondition(
|
||||
{ type: 'Comma', syntax: node },
|
||||
result,
|
||||
MISMATCH
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// create a match node chain for [min .. max] interval with optional matches
|
||||
for (let i = node.min || 1; i <= node.max; i++) {
|
||||
if (node.comma && result !== MATCH) {
|
||||
result = createCondition(
|
||||
{ type: 'Comma', syntax: node },
|
||||
result,
|
||||
MISMATCH
|
||||
);
|
||||
}
|
||||
|
||||
result = createCondition(
|
||||
matchTerm,
|
||||
createCondition(
|
||||
MATCH,
|
||||
MATCH,
|
||||
result
|
||||
),
|
||||
MISMATCH
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (node.min === 0) {
|
||||
// allow zero match
|
||||
result = createCondition(
|
||||
MATCH,
|
||||
MATCH,
|
||||
result
|
||||
);
|
||||
} else {
|
||||
// create a match node chain to collect [0 ... min - 1] required matches
|
||||
for (let i = 0; i < node.min - 1; i++) {
|
||||
if (node.comma && result !== MATCH) {
|
||||
result = createCondition(
|
||||
{ type: 'Comma', syntax: node },
|
||||
result,
|
||||
MISMATCH
|
||||
);
|
||||
}
|
||||
|
||||
result = createCondition(
|
||||
matchTerm,
|
||||
result,
|
||||
MISMATCH
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function buildMatchGraphInternal(node) {
|
||||
if (typeof node === 'function') {
|
||||
return {
|
||||
type: 'Generic',
|
||||
fn: node
|
||||
};
|
||||
}
|
||||
|
||||
switch (node.type) {
|
||||
case 'Group': {
|
||||
let result = buildGroupMatchGraph(
|
||||
node.combinator,
|
||||
node.terms.map(buildMatchGraphInternal),
|
||||
false
|
||||
);
|
||||
|
||||
if (node.disallowEmpty) {
|
||||
result = createCondition(
|
||||
result,
|
||||
DISALLOW_EMPTY,
|
||||
MISMATCH
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
case 'Multiplier':
|
||||
return buildMultiplierMatchGraph(node);
|
||||
|
||||
// https://drafts.csswg.org/css-values-5/#boolean
|
||||
case 'Boolean': {
|
||||
const term = buildMatchGraphInternal(node.term);
|
||||
// <boolean-expr[ <test> ]> = not <boolean-expr-group> | <boolean-expr-group> [ [ and <boolean-expr-group> ]* | [ or <boolean-expr-group> ]* ]
|
||||
const matchNode = buildMatchGraphInternal(groupNode([
|
||||
groupNode([
|
||||
{ type: 'Keyword', name: 'not' },
|
||||
{ type: 'Type', name: '!boolean-group' }
|
||||
]),
|
||||
groupNode([
|
||||
{ type: 'Type', name: '!boolean-group' },
|
||||
groupNode([
|
||||
{ type: 'Multiplier', comma: false, min: 0, max: 0, term: groupNode([
|
||||
{ type: 'Keyword', name: 'and' },
|
||||
{ type: 'Type', name: '!boolean-group' }
|
||||
]) },
|
||||
{ type: 'Multiplier', comma: false, min: 0, max: 0, term: groupNode([
|
||||
{ type: 'Keyword', name: 'or' },
|
||||
{ type: 'Type', name: '!boolean-group' }
|
||||
]) }
|
||||
], '|')
|
||||
])
|
||||
], '|'));
|
||||
// <boolean-expr-group> = <test> | ( <boolean-expr[ <test> ]> ) | <general-enclosed>
|
||||
const booleanGroup = buildMatchGraphInternal(
|
||||
groupNode([
|
||||
{ type: 'Type', name: '!term' },
|
||||
groupNode([
|
||||
{ type: 'Token', value: '(' },
|
||||
{ type: 'Type', name: '!self' },
|
||||
{ type: 'Token', value: ')' }
|
||||
]),
|
||||
{ type: 'Type', name: 'general-enclosed' }
|
||||
], '|')
|
||||
);
|
||||
|
||||
replaceTypeInGraph(booleanGroup, { '!term': term, '!self': matchNode });
|
||||
replaceTypeInGraph(matchNode, { '!boolean-group': booleanGroup });
|
||||
|
||||
return matchNode;
|
||||
}
|
||||
|
||||
case 'Type':
|
||||
case 'Property':
|
||||
return {
|
||||
type: node.type,
|
||||
name: node.name,
|
||||
syntax: node
|
||||
};
|
||||
|
||||
case 'Keyword':
|
||||
return {
|
||||
type: node.type,
|
||||
name: node.name.toLowerCase(),
|
||||
syntax: node
|
||||
};
|
||||
|
||||
case 'AtKeyword':
|
||||
return {
|
||||
type: node.type,
|
||||
name: '@' + node.name.toLowerCase(),
|
||||
syntax: node
|
||||
};
|
||||
|
||||
case 'Function':
|
||||
return {
|
||||
type: node.type,
|
||||
name: node.name.toLowerCase() + '(',
|
||||
syntax: node
|
||||
};
|
||||
|
||||
case 'String':
|
||||
// convert a one char length String to a Token
|
||||
if (node.value.length === 3) {
|
||||
return {
|
||||
type: 'Token',
|
||||
value: node.value.charAt(1),
|
||||
syntax: node
|
||||
};
|
||||
}
|
||||
|
||||
// otherwise use it as is
|
||||
return {
|
||||
type: node.type,
|
||||
value: node.value.substr(1, node.value.length - 2).replace(/\\'/g, '\''),
|
||||
syntax: node
|
||||
};
|
||||
|
||||
case 'Token':
|
||||
return {
|
||||
type: node.type,
|
||||
value: node.value,
|
||||
syntax: node
|
||||
};
|
||||
|
||||
case 'Comma':
|
||||
return {
|
||||
type: node.type,
|
||||
syntax: node
|
||||
};
|
||||
|
||||
default:
|
||||
throw new Error('Unknown node type:', node.type);
|
||||
}
|
||||
}
|
||||
|
||||
function buildMatchGraph(syntaxTree, ref) {
|
||||
if (typeof syntaxTree === 'string') {
|
||||
syntaxTree = parse.parse(syntaxTree);
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'MatchGraph',
|
||||
match: buildMatchGraphInternal(syntaxTree),
|
||||
syntax: ref || null,
|
||||
source: syntaxTree
|
||||
};
|
||||
}
|
||||
|
||||
exports.DISALLOW_EMPTY = DISALLOW_EMPTY;
|
||||
exports.MATCH = MATCH;
|
||||
exports.MISMATCH = MISMATCH;
|
||||
exports.buildMatchGraph = buildMatchGraph;
|
||||
-632
@@ -1,632 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const matchGraph = require('./match-graph.cjs');
|
||||
const types = require('../tokenizer/types.cjs');
|
||||
|
||||
const { hasOwnProperty } = Object.prototype;
|
||||
const STUB = 0;
|
||||
const TOKEN = 1;
|
||||
const OPEN_SYNTAX = 2;
|
||||
const CLOSE_SYNTAX = 3;
|
||||
|
||||
const EXIT_REASON_MATCH = 'Match';
|
||||
const EXIT_REASON_MISMATCH = 'Mismatch';
|
||||
const EXIT_REASON_ITERATION_LIMIT = 'Maximum iteration number exceeded (please fill an issue on https://github.com/csstree/csstree/issues)';
|
||||
|
||||
const ITERATION_LIMIT = 15000;
|
||||
|
||||
function reverseList(list) {
|
||||
let prev = null;
|
||||
let next = null;
|
||||
let item = list;
|
||||
|
||||
while (item !== null) {
|
||||
next = item.prev;
|
||||
item.prev = prev;
|
||||
prev = item;
|
||||
item = next;
|
||||
}
|
||||
|
||||
return prev;
|
||||
}
|
||||
|
||||
function areStringsEqualCaseInsensitive(testStr, referenceStr) {
|
||||
if (testStr.length !== referenceStr.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (let i = 0; i < testStr.length; i++) {
|
||||
const referenceCode = referenceStr.charCodeAt(i);
|
||||
let testCode = testStr.charCodeAt(i);
|
||||
|
||||
// testCode.toLowerCase() for U+0041 LATIN CAPITAL LETTER A (A) .. U+005A LATIN CAPITAL LETTER Z (Z).
|
||||
if (testCode >= 0x0041 && testCode <= 0x005A) {
|
||||
testCode = testCode | 32;
|
||||
}
|
||||
|
||||
if (testCode !== referenceCode) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function isContextEdgeDelim(token) {
|
||||
if (token.type !== types.Delim) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Fix matching for unicode-range: U+30??, U+FF00-FF9F
|
||||
// Probably we need to check out previous match instead
|
||||
return token.value !== '?';
|
||||
}
|
||||
|
||||
function isCommaContextStart(token) {
|
||||
if (token === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
token.type === types.Comma ||
|
||||
token.type === types.Function ||
|
||||
token.type === types.LeftParenthesis ||
|
||||
token.type === types.LeftSquareBracket ||
|
||||
token.type === types.LeftCurlyBracket ||
|
||||
isContextEdgeDelim(token)
|
||||
);
|
||||
}
|
||||
|
||||
function isCommaContextEnd(token) {
|
||||
if (token === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
token.type === types.RightParenthesis ||
|
||||
token.type === types.RightSquareBracket ||
|
||||
token.type === types.RightCurlyBracket ||
|
||||
(token.type === types.Delim && token.value === '/')
|
||||
);
|
||||
}
|
||||
|
||||
function internalMatch(tokens, state, syntaxes) {
|
||||
function moveToNextToken() {
|
||||
do {
|
||||
tokenIndex++;
|
||||
token = tokenIndex < tokens.length ? tokens[tokenIndex] : null;
|
||||
} while (token !== null && (token.type === types.WhiteSpace || token.type === types.Comment));
|
||||
}
|
||||
|
||||
function getNextToken(offset) {
|
||||
const nextIndex = tokenIndex + offset;
|
||||
|
||||
return nextIndex < tokens.length ? tokens[nextIndex] : null;
|
||||
}
|
||||
|
||||
function stateSnapshotFromSyntax(nextState, prev) {
|
||||
return {
|
||||
nextState,
|
||||
matchStack,
|
||||
syntaxStack,
|
||||
thenStack,
|
||||
tokenIndex,
|
||||
prev
|
||||
};
|
||||
}
|
||||
|
||||
function pushThenStack(nextState) {
|
||||
thenStack = {
|
||||
nextState,
|
||||
matchStack,
|
||||
syntaxStack,
|
||||
prev: thenStack
|
||||
};
|
||||
}
|
||||
|
||||
function pushElseStack(nextState) {
|
||||
elseStack = stateSnapshotFromSyntax(nextState, elseStack);
|
||||
}
|
||||
|
||||
function addTokenToMatch() {
|
||||
matchStack = {
|
||||
type: TOKEN,
|
||||
syntax: state.syntax,
|
||||
token,
|
||||
prev: matchStack
|
||||
};
|
||||
|
||||
moveToNextToken();
|
||||
syntaxStash = null;
|
||||
|
||||
if (tokenIndex > longestMatch) {
|
||||
longestMatch = tokenIndex;
|
||||
}
|
||||
}
|
||||
|
||||
function openSyntax() {
|
||||
syntaxStack = {
|
||||
syntax: state.syntax,
|
||||
opts: state.syntax.opts || (syntaxStack !== null && syntaxStack.opts) || null,
|
||||
prev: syntaxStack
|
||||
};
|
||||
|
||||
matchStack = {
|
||||
type: OPEN_SYNTAX,
|
||||
syntax: state.syntax,
|
||||
token: matchStack.token,
|
||||
prev: matchStack
|
||||
};
|
||||
}
|
||||
|
||||
function closeSyntax() {
|
||||
if (matchStack.type === OPEN_SYNTAX) {
|
||||
matchStack = matchStack.prev;
|
||||
} else {
|
||||
matchStack = {
|
||||
type: CLOSE_SYNTAX,
|
||||
syntax: syntaxStack.syntax,
|
||||
token: matchStack.token,
|
||||
prev: matchStack
|
||||
};
|
||||
}
|
||||
|
||||
syntaxStack = syntaxStack.prev;
|
||||
}
|
||||
|
||||
let syntaxStack = null;
|
||||
let thenStack = null;
|
||||
let elseStack = null;
|
||||
|
||||
// null – stashing allowed, nothing stashed
|
||||
// false – stashing disabled, nothing stashed
|
||||
// anithing else – fail stashable syntaxes, some syntax stashed
|
||||
let syntaxStash = null;
|
||||
|
||||
let iterationCount = 0; // count iterations and prevent infinite loop
|
||||
let exitReason = null;
|
||||
|
||||
let token = null;
|
||||
let tokenIndex = -1;
|
||||
let longestMatch = 0;
|
||||
let matchStack = {
|
||||
type: STUB,
|
||||
syntax: null,
|
||||
token: null,
|
||||
prev: null
|
||||
};
|
||||
|
||||
moveToNextToken();
|
||||
|
||||
while (exitReason === null && ++iterationCount < ITERATION_LIMIT) {
|
||||
// function mapList(list, fn) {
|
||||
// const result = [];
|
||||
// while (list) {
|
||||
// result.unshift(fn(list));
|
||||
// list = list.prev;
|
||||
// }
|
||||
// return result;
|
||||
// }
|
||||
// console.log('--\n',
|
||||
// '#' + iterationCount,
|
||||
// require('util').inspect({
|
||||
// match: mapList(matchStack, x => x.type === TOKEN ? x.token && x.token.value : x.syntax ? ({ [OPEN_SYNTAX]: '<', [CLOSE_SYNTAX]: '</' }[x.type] || x.type) + '!' + x.syntax.name : null),
|
||||
// token: token && token.value,
|
||||
// tokenIndex,
|
||||
// syntax: syntax.type + (syntax.id ? ' #' + syntax.id : '')
|
||||
// }, { depth: null })
|
||||
// );
|
||||
switch (state.type) {
|
||||
case 'Match':
|
||||
if (thenStack === null) {
|
||||
// turn to MISMATCH when some tokens left unmatched
|
||||
if (token !== null) {
|
||||
// doesn't mismatch if just one token left and it's an IE hack
|
||||
if (tokenIndex !== tokens.length - 1 || (token.value !== '\\0' && token.value !== '\\9')) {
|
||||
state = matchGraph.MISMATCH;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// break the main loop, return a result - MATCH
|
||||
exitReason = EXIT_REASON_MATCH;
|
||||
break;
|
||||
}
|
||||
|
||||
// go to next syntax (`then` branch)
|
||||
state = thenStack.nextState;
|
||||
|
||||
// check match is not empty
|
||||
if (state === matchGraph.DISALLOW_EMPTY) {
|
||||
if (thenStack.matchStack === matchStack) {
|
||||
state = matchGraph.MISMATCH;
|
||||
break;
|
||||
} else {
|
||||
state = matchGraph.MATCH;
|
||||
}
|
||||
}
|
||||
|
||||
// close syntax if needed
|
||||
while (thenStack.syntaxStack !== syntaxStack) {
|
||||
closeSyntax();
|
||||
}
|
||||
|
||||
// pop stack
|
||||
thenStack = thenStack.prev;
|
||||
break;
|
||||
|
||||
case 'Mismatch':
|
||||
// when some syntax is stashed
|
||||
if (syntaxStash !== null && syntaxStash !== false) {
|
||||
// there is no else branches or a branch reduce match stack
|
||||
if (elseStack === null || tokenIndex > elseStack.tokenIndex) {
|
||||
// restore state from the stash
|
||||
elseStack = syntaxStash;
|
||||
syntaxStash = false; // disable stashing
|
||||
}
|
||||
} else if (elseStack === null) {
|
||||
// no else branches -> break the main loop
|
||||
// return a result - MISMATCH
|
||||
exitReason = EXIT_REASON_MISMATCH;
|
||||
break;
|
||||
}
|
||||
|
||||
// go to next syntax (`else` branch)
|
||||
state = elseStack.nextState;
|
||||
|
||||
// restore all the rest stack states
|
||||
thenStack = elseStack.thenStack;
|
||||
syntaxStack = elseStack.syntaxStack;
|
||||
matchStack = elseStack.matchStack;
|
||||
tokenIndex = elseStack.tokenIndex;
|
||||
token = tokenIndex < tokens.length ? tokens[tokenIndex] : null;
|
||||
|
||||
// pop stack
|
||||
elseStack = elseStack.prev;
|
||||
break;
|
||||
|
||||
case 'MatchGraph':
|
||||
state = state.match;
|
||||
break;
|
||||
|
||||
case 'If':
|
||||
// IMPORTANT: else stack push must go first,
|
||||
// since it stores the state of thenStack before changes
|
||||
if (state.else !== matchGraph.MISMATCH) {
|
||||
pushElseStack(state.else);
|
||||
}
|
||||
|
||||
if (state.then !== matchGraph.MATCH) {
|
||||
pushThenStack(state.then);
|
||||
}
|
||||
|
||||
state = state.match;
|
||||
break;
|
||||
|
||||
case 'MatchOnce':
|
||||
state = {
|
||||
type: 'MatchOnceBuffer',
|
||||
syntax: state,
|
||||
index: 0,
|
||||
mask: 0
|
||||
};
|
||||
break;
|
||||
|
||||
case 'MatchOnceBuffer': {
|
||||
const terms = state.syntax.terms;
|
||||
|
||||
if (state.index === terms.length) {
|
||||
// no matches at all or it's required all terms to be matched
|
||||
if (state.mask === 0 || state.syntax.all) {
|
||||
state = matchGraph.MISMATCH;
|
||||
break;
|
||||
}
|
||||
|
||||
// a partial match is ok
|
||||
state = matchGraph.MATCH;
|
||||
break;
|
||||
}
|
||||
|
||||
// all terms are matched
|
||||
if (state.mask === (1 << terms.length) - 1) {
|
||||
state = matchGraph.MATCH;
|
||||
break;
|
||||
}
|
||||
|
||||
for (; state.index < terms.length; state.index++) {
|
||||
const matchFlag = 1 << state.index;
|
||||
|
||||
if ((state.mask & matchFlag) === 0) {
|
||||
// IMPORTANT: else stack push must go first,
|
||||
// since it stores the state of thenStack before changes
|
||||
pushElseStack(state);
|
||||
pushThenStack({
|
||||
type: 'AddMatchOnce',
|
||||
syntax: state.syntax,
|
||||
mask: state.mask | matchFlag
|
||||
});
|
||||
|
||||
// match
|
||||
state = terms[state.index++];
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'AddMatchOnce':
|
||||
state = {
|
||||
type: 'MatchOnceBuffer',
|
||||
syntax: state.syntax,
|
||||
index: 0,
|
||||
mask: state.mask
|
||||
};
|
||||
break;
|
||||
|
||||
case 'Enum':
|
||||
if (token !== null) {
|
||||
let name = token.value.toLowerCase();
|
||||
|
||||
// drop \0 and \9 hack from keyword name
|
||||
if (name.indexOf('\\') !== -1) {
|
||||
name = name.replace(/\\[09].*$/, '');
|
||||
}
|
||||
|
||||
if (hasOwnProperty.call(state.map, name)) {
|
||||
state = state.map[name];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
state = matchGraph.MISMATCH;
|
||||
break;
|
||||
|
||||
case 'Generic': {
|
||||
const opts = syntaxStack !== null ? syntaxStack.opts : null;
|
||||
const lastTokenIndex = tokenIndex + Math.floor(state.fn(token, getNextToken, opts));
|
||||
|
||||
if (!isNaN(lastTokenIndex) && lastTokenIndex > tokenIndex) {
|
||||
while (tokenIndex < lastTokenIndex) {
|
||||
addTokenToMatch();
|
||||
}
|
||||
|
||||
state = matchGraph.MATCH;
|
||||
} else {
|
||||
state = matchGraph.MISMATCH;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case 'Type':
|
||||
case 'Property': {
|
||||
const syntaxDict = state.type === 'Type' ? 'types' : 'properties';
|
||||
const dictSyntax = hasOwnProperty.call(syntaxes, syntaxDict) ? syntaxes[syntaxDict][state.name] : null;
|
||||
|
||||
if (!dictSyntax || !dictSyntax.match) {
|
||||
throw new Error(
|
||||
'Bad syntax reference: ' +
|
||||
(state.type === 'Type'
|
||||
? '<' + state.name + '>'
|
||||
: '<\'' + state.name + '\'>')
|
||||
);
|
||||
}
|
||||
|
||||
// stash a syntax for types with low priority
|
||||
if (syntaxStash !== false && token !== null && state.type === 'Type') {
|
||||
const lowPriorityMatching =
|
||||
// https://drafts.csswg.org/css-values-4/#custom-idents
|
||||
// When parsing positionally-ambiguous keywords in a property value, a <custom-ident> production
|
||||
// can only claim the keyword if no other unfulfilled production can claim it.
|
||||
(state.name === 'custom-ident' && token.type === types.Ident) ||
|
||||
|
||||
// https://drafts.csswg.org/css-values-4/#lengths
|
||||
// ... if a `0` could be parsed as either a <number> or a <length> in a property (such as line-height),
|
||||
// it must parse as a <number>
|
||||
(state.name === 'length' && token.value === '0');
|
||||
|
||||
if (lowPriorityMatching) {
|
||||
if (syntaxStash === null) {
|
||||
syntaxStash = stateSnapshotFromSyntax(state, elseStack);
|
||||
}
|
||||
|
||||
state = matchGraph.MISMATCH;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
openSyntax();
|
||||
state = dictSyntax.matchRef || dictSyntax.match;
|
||||
break;
|
||||
}
|
||||
|
||||
case 'Keyword': {
|
||||
const name = state.name;
|
||||
|
||||
if (token !== null) {
|
||||
let keywordName = token.value;
|
||||
|
||||
// drop \0 and \9 hack from keyword name
|
||||
if (keywordName.indexOf('\\') !== -1) {
|
||||
keywordName = keywordName.replace(/\\[09].*$/, '');
|
||||
}
|
||||
|
||||
if (areStringsEqualCaseInsensitive(keywordName, name)) {
|
||||
addTokenToMatch();
|
||||
state = matchGraph.MATCH;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
state = matchGraph.MISMATCH;
|
||||
break;
|
||||
}
|
||||
|
||||
case 'AtKeyword':
|
||||
case 'Function':
|
||||
if (token !== null && areStringsEqualCaseInsensitive(token.value, state.name)) {
|
||||
addTokenToMatch();
|
||||
state = matchGraph.MATCH;
|
||||
break;
|
||||
}
|
||||
|
||||
state = matchGraph.MISMATCH;
|
||||
break;
|
||||
|
||||
case 'Token':
|
||||
if (token !== null && token.value === state.value) {
|
||||
addTokenToMatch();
|
||||
state = matchGraph.MATCH;
|
||||
break;
|
||||
}
|
||||
|
||||
state = matchGraph.MISMATCH;
|
||||
break;
|
||||
|
||||
case 'Comma':
|
||||
if (token !== null && token.type === types.Comma) {
|
||||
if (isCommaContextStart(matchStack.token)) {
|
||||
state = matchGraph.MISMATCH;
|
||||
} else {
|
||||
addTokenToMatch();
|
||||
state = isCommaContextEnd(token) ? matchGraph.MISMATCH : matchGraph.MATCH;
|
||||
}
|
||||
} else {
|
||||
state = isCommaContextStart(matchStack.token) || isCommaContextEnd(token) ? matchGraph.MATCH : matchGraph.MISMATCH;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 'String':
|
||||
let string = '';
|
||||
let lastTokenIndex = tokenIndex;
|
||||
|
||||
for (; lastTokenIndex < tokens.length && string.length < state.value.length; lastTokenIndex++) {
|
||||
string += tokens[lastTokenIndex].value;
|
||||
}
|
||||
|
||||
if (areStringsEqualCaseInsensitive(string, state.value)) {
|
||||
while (tokenIndex < lastTokenIndex) {
|
||||
addTokenToMatch();
|
||||
}
|
||||
|
||||
state = matchGraph.MATCH;
|
||||
} else {
|
||||
state = matchGraph.MISMATCH;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error('Unknown node type: ' + state.type);
|
||||
}
|
||||
}
|
||||
|
||||
switch (exitReason) {
|
||||
case null:
|
||||
console.warn('[csstree-match] BREAK after ' + ITERATION_LIMIT + ' iterations');
|
||||
exitReason = EXIT_REASON_ITERATION_LIMIT;
|
||||
matchStack = null;
|
||||
break;
|
||||
|
||||
case EXIT_REASON_MATCH:
|
||||
while (syntaxStack !== null) {
|
||||
closeSyntax();
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
matchStack = null;
|
||||
}
|
||||
|
||||
return {
|
||||
tokens,
|
||||
reason: exitReason,
|
||||
iterations: iterationCount,
|
||||
match: matchStack,
|
||||
longestMatch
|
||||
};
|
||||
}
|
||||
|
||||
function matchAsList(tokens, matchGraph, syntaxes) {
|
||||
const matchResult = internalMatch(tokens, matchGraph, syntaxes || {});
|
||||
|
||||
if (matchResult.match !== null) {
|
||||
let item = reverseList(matchResult.match).prev;
|
||||
|
||||
matchResult.match = [];
|
||||
|
||||
while (item !== null) {
|
||||
switch (item.type) {
|
||||
case OPEN_SYNTAX:
|
||||
case CLOSE_SYNTAX:
|
||||
matchResult.match.push({
|
||||
type: item.type,
|
||||
syntax: item.syntax
|
||||
});
|
||||
break;
|
||||
|
||||
default:
|
||||
matchResult.match.push({
|
||||
token: item.token.value,
|
||||
node: item.token.node
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
item = item.prev;
|
||||
}
|
||||
}
|
||||
|
||||
return matchResult;
|
||||
}
|
||||
|
||||
function matchAsTree(tokens, matchGraph, syntaxes) {
|
||||
const matchResult = internalMatch(tokens, matchGraph, syntaxes || {});
|
||||
|
||||
if (matchResult.match === null) {
|
||||
return matchResult;
|
||||
}
|
||||
|
||||
let item = matchResult.match;
|
||||
let host = matchResult.match = {
|
||||
syntax: matchGraph.syntax || null,
|
||||
match: []
|
||||
};
|
||||
const hostStack = [host];
|
||||
|
||||
// revert a list and start with 2nd item since 1st is a stub item
|
||||
item = reverseList(item).prev;
|
||||
|
||||
// build a tree
|
||||
while (item !== null) {
|
||||
switch (item.type) {
|
||||
case OPEN_SYNTAX:
|
||||
host.match.push(host = {
|
||||
syntax: item.syntax,
|
||||
match: []
|
||||
});
|
||||
hostStack.push(host);
|
||||
break;
|
||||
|
||||
case CLOSE_SYNTAX:
|
||||
hostStack.pop();
|
||||
host = hostStack[hostStack.length - 1];
|
||||
break;
|
||||
|
||||
default:
|
||||
host.match.push({
|
||||
syntax: item.syntax || null,
|
||||
token: item.token.value,
|
||||
node: item.token.node
|
||||
});
|
||||
}
|
||||
|
||||
item = item.prev;
|
||||
}
|
||||
|
||||
return matchResult;
|
||||
}
|
||||
|
||||
exports.matchAsList = matchAsList;
|
||||
exports.matchAsTree = matchAsTree;
|
||||
-55
@@ -1,55 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const getTokenizer = require('../utils/get-tokenizer.cjs');
|
||||
|
||||
const astToTokens = {
|
||||
decorator(handlers) {
|
||||
const tokens = [];
|
||||
let curNode = null;
|
||||
|
||||
return {
|
||||
...handlers,
|
||||
node(node) {
|
||||
const tmp = curNode;
|
||||
curNode = node;
|
||||
handlers.node.call(this, node);
|
||||
curNode = tmp;
|
||||
},
|
||||
emit(value, type, auto) {
|
||||
tokens.push({
|
||||
type,
|
||||
value,
|
||||
node: auto ? null : curNode
|
||||
});
|
||||
},
|
||||
result() {
|
||||
return tokens;
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
function stringToTokens(str, syntax) {
|
||||
const tokens = [];
|
||||
const tokenize = getTokenizer.getTokenizer(syntax);
|
||||
|
||||
tokenize(str, (type, start, end) =>
|
||||
tokens.push({
|
||||
type,
|
||||
value: str.slice(start, end),
|
||||
node: null
|
||||
})
|
||||
);
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
function prepareTokens(value, syntax) {
|
||||
if (typeof value === 'string') {
|
||||
return stringToTokens(value, syntax);
|
||||
}
|
||||
|
||||
return syntax.generate(value, astToTokens);
|
||||
}
|
||||
|
||||
module.exports = prepareTokens;
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const List = require('../utils/List.cjs');
|
||||
|
||||
function getFirstMatchNode(matchNode) {
|
||||
if ('node' in matchNode) {
|
||||
return matchNode.node;
|
||||
}
|
||||
|
||||
return getFirstMatchNode(matchNode.match[0]);
|
||||
}
|
||||
|
||||
function getLastMatchNode(matchNode) {
|
||||
if ('node' in matchNode) {
|
||||
return matchNode.node;
|
||||
}
|
||||
|
||||
return getLastMatchNode(matchNode.match[matchNode.match.length - 1]);
|
||||
}
|
||||
|
||||
function matchFragments(lexer, ast, match, type, name) {
|
||||
function findFragments(matchNode) {
|
||||
if (matchNode.syntax !== null &&
|
||||
matchNode.syntax.type === type &&
|
||||
matchNode.syntax.name === name) {
|
||||
const start = getFirstMatchNode(matchNode);
|
||||
const end = getLastMatchNode(matchNode);
|
||||
|
||||
lexer.syntax.walk(ast, function(node, item, list) {
|
||||
if (node === start) {
|
||||
const nodes = new List.List();
|
||||
|
||||
do {
|
||||
nodes.appendData(item.data);
|
||||
|
||||
if (item.data === end) {
|
||||
break;
|
||||
}
|
||||
|
||||
item = item.next;
|
||||
} while (item !== null);
|
||||
|
||||
fragments.push({
|
||||
parent: list,
|
||||
nodes
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (Array.isArray(matchNode.match)) {
|
||||
matchNode.match.forEach(findFragments);
|
||||
}
|
||||
}
|
||||
|
||||
const fragments = [];
|
||||
|
||||
if (match.matched !== null) {
|
||||
findFragments(match.matched);
|
||||
}
|
||||
|
||||
return fragments;
|
||||
}
|
||||
|
||||
exports.matchFragments = matchFragments;
|
||||
-173
@@ -1,173 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const List = require('../utils/List.cjs');
|
||||
|
||||
const { hasOwnProperty } = Object.prototype;
|
||||
|
||||
function isValidNumber(value) {
|
||||
// Number.isInteger(value) && value >= 0
|
||||
return (
|
||||
typeof value === 'number' &&
|
||||
isFinite(value) &&
|
||||
Math.floor(value) === value &&
|
||||
value >= 0
|
||||
);
|
||||
}
|
||||
|
||||
function isValidLocation(loc) {
|
||||
return (
|
||||
Boolean(loc) &&
|
||||
isValidNumber(loc.offset) &&
|
||||
isValidNumber(loc.line) &&
|
||||
isValidNumber(loc.column)
|
||||
);
|
||||
}
|
||||
|
||||
function createNodeStructureChecker(type, fields) {
|
||||
return function checkNode(node, warn) {
|
||||
if (!node || node.constructor !== Object) {
|
||||
return warn(node, 'Type of node should be an Object');
|
||||
}
|
||||
|
||||
for (let key in node) {
|
||||
let valid = true;
|
||||
|
||||
if (hasOwnProperty.call(node, key) === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (key === 'type') {
|
||||
if (node.type !== type) {
|
||||
warn(node, 'Wrong node type `' + node.type + '`, expected `' + type + '`');
|
||||
}
|
||||
} else if (key === 'loc') {
|
||||
if (node.loc === null) {
|
||||
continue;
|
||||
} else if (node.loc && node.loc.constructor === Object) {
|
||||
if (typeof node.loc.source !== 'string') {
|
||||
key += '.source';
|
||||
} else if (!isValidLocation(node.loc.start)) {
|
||||
key += '.start';
|
||||
} else if (!isValidLocation(node.loc.end)) {
|
||||
key += '.end';
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
valid = false;
|
||||
} else if (fields.hasOwnProperty(key)) {
|
||||
valid = false;
|
||||
|
||||
for (let i = 0; !valid && i < fields[key].length; i++) {
|
||||
const fieldType = fields[key][i];
|
||||
|
||||
switch (fieldType) {
|
||||
case String:
|
||||
valid = typeof node[key] === 'string';
|
||||
break;
|
||||
|
||||
case Boolean:
|
||||
valid = typeof node[key] === 'boolean';
|
||||
break;
|
||||
|
||||
case null:
|
||||
valid = node[key] === null;
|
||||
break;
|
||||
|
||||
default:
|
||||
if (typeof fieldType === 'string') {
|
||||
valid = node[key] && node[key].type === fieldType;
|
||||
} else if (Array.isArray(fieldType)) {
|
||||
valid = node[key] instanceof List.List;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
warn(node, 'Unknown field `' + key + '` for ' + type + ' node type');
|
||||
}
|
||||
|
||||
if (!valid) {
|
||||
warn(node, 'Bad value for `' + type + '.' + key + '`');
|
||||
}
|
||||
}
|
||||
|
||||
for (const key in fields) {
|
||||
if (hasOwnProperty.call(fields, key) &&
|
||||
hasOwnProperty.call(node, key) === false) {
|
||||
warn(node, 'Field `' + type + '.' + key + '` is missed');
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function genTypesList(fieldTypes, path) {
|
||||
const docsTypes = [];
|
||||
|
||||
for (let i = 0; i < fieldTypes.length; i++) {
|
||||
const fieldType = fieldTypes[i];
|
||||
if (fieldType === String || fieldType === Boolean) {
|
||||
docsTypes.push(fieldType.name.toLowerCase());
|
||||
} else if (fieldType === null) {
|
||||
docsTypes.push('null');
|
||||
} else if (typeof fieldType === 'string') {
|
||||
docsTypes.push(fieldType);
|
||||
} else if (Array.isArray(fieldType)) {
|
||||
docsTypes.push('List<' + (genTypesList(fieldType, path) || 'any') + '>'); // TODO: use type enum
|
||||
} else {
|
||||
throw new Error('Wrong value `' + fieldType + '` in `' + path + '` structure definition');
|
||||
}
|
||||
}
|
||||
|
||||
return docsTypes.join(' | ');
|
||||
}
|
||||
|
||||
function processStructure(name, nodeType) {
|
||||
const structure = nodeType.structure;
|
||||
const fields = {
|
||||
type: String,
|
||||
loc: true
|
||||
};
|
||||
const docs = {
|
||||
type: '"' + name + '"'
|
||||
};
|
||||
|
||||
for (const key in structure) {
|
||||
if (hasOwnProperty.call(structure, key) === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const fieldTypes = fields[key] = Array.isArray(structure[key])
|
||||
? structure[key].slice()
|
||||
: [structure[key]];
|
||||
|
||||
docs[key] = genTypesList(fieldTypes, name + '.' + key);
|
||||
}
|
||||
|
||||
return {
|
||||
docs,
|
||||
check: createNodeStructureChecker(name, fields)
|
||||
};
|
||||
}
|
||||
|
||||
function getStructureFromConfig(config) {
|
||||
const structure = {};
|
||||
|
||||
if (config.node) {
|
||||
for (const name in config.node) {
|
||||
if (hasOwnProperty.call(config.node, name)) {
|
||||
const nodeType = config.node[name];
|
||||
|
||||
if (nodeType.structure) {
|
||||
structure[name] = processStructure(name, nodeType);
|
||||
} else {
|
||||
throw new Error('Missed `structure` field in `' + name + '` node type definition');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return structure;
|
||||
}
|
||||
|
||||
exports.getStructureFromConfig = getStructureFromConfig;
|
||||
-73
@@ -1,73 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
function getTrace(node) {
|
||||
function shouldPutToTrace(syntax) {
|
||||
if (syntax === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
syntax.type === 'Type' ||
|
||||
syntax.type === 'Property' ||
|
||||
syntax.type === 'Keyword'
|
||||
);
|
||||
}
|
||||
|
||||
function hasMatch(matchNode) {
|
||||
if (Array.isArray(matchNode.match)) {
|
||||
// use for-loop for better perfomance
|
||||
for (let i = 0; i < matchNode.match.length; i++) {
|
||||
if (hasMatch(matchNode.match[i])) {
|
||||
if (shouldPutToTrace(matchNode.syntax)) {
|
||||
result.unshift(matchNode.syntax);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else if (matchNode.node === node) {
|
||||
result = shouldPutToTrace(matchNode.syntax)
|
||||
? [matchNode.syntax]
|
||||
: [];
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
let result = null;
|
||||
|
||||
if (this.matched !== null) {
|
||||
hasMatch(this.matched);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function isType(node, type) {
|
||||
return testNode(this, node, match => match.type === 'Type' && match.name === type);
|
||||
}
|
||||
|
||||
function isProperty(node, property) {
|
||||
return testNode(this, node, match => match.type === 'Property' && match.name === property);
|
||||
}
|
||||
|
||||
function isKeyword(node) {
|
||||
return testNode(this, node, match => match.type === 'Keyword');
|
||||
}
|
||||
|
||||
function testNode(match, node, fn) {
|
||||
const trace = getTrace.call(match, node);
|
||||
|
||||
if (trace === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return trace.some(fn);
|
||||
}
|
||||
|
||||
exports.getTrace = getTrace;
|
||||
exports.isKeyword = isKeyword;
|
||||
exports.isProperty = isProperty;
|
||||
exports.isType = isType;
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const length = [
|
||||
// absolute length units https://www.w3.org/TR/css-values-3/#lengths
|
||||
'cm', 'mm', 'q', 'in', 'pt', 'pc', 'px',
|
||||
// font-relative length units https://drafts.csswg.org/css-values-4/#font-relative-lengths
|
||||
'em', 'rem',
|
||||
'ex', 'rex',
|
||||
'cap', 'rcap',
|
||||
'ch', 'rch',
|
||||
'ic', 'ric',
|
||||
'lh', 'rlh',
|
||||
// viewport-percentage lengths https://drafts.csswg.org/css-values-4/#viewport-relative-lengths
|
||||
'vw', 'svw', 'lvw', 'dvw',
|
||||
'vh', 'svh', 'lvh', 'dvh',
|
||||
'vi', 'svi', 'lvi', 'dvi',
|
||||
'vb', 'svb', 'lvb', 'dvb',
|
||||
'vmin', 'svmin', 'lvmin', 'dvmin',
|
||||
'vmax', 'svmax', 'lvmax', 'dvmax',
|
||||
// container relative lengths https://drafts.csswg.org/css-contain-3/#container-lengths
|
||||
'cqw', 'cqh', 'cqi', 'cqb', 'cqmin', 'cqmax'
|
||||
];
|
||||
const angle = ['deg', 'grad', 'rad', 'turn']; // https://www.w3.org/TR/css-values-3/#angles
|
||||
const time = ['s', 'ms']; // https://www.w3.org/TR/css-values-3/#time
|
||||
const frequency = ['hz', 'khz']; // https://www.w3.org/TR/css-values-3/#frequency
|
||||
const resolution = ['dpi', 'dpcm', 'dppx', 'x']; // https://www.w3.org/TR/css-values-3/#resolution
|
||||
const flex = ['fr']; // https://drafts.csswg.org/css-grid/#fr-unit
|
||||
const decibel = ['db']; // https://www.w3.org/TR/css3-speech/#mixing-props-voice-volume
|
||||
const semitones = ['st']; // https://www.w3.org/TR/css3-speech/#voice-props-voice-pitch
|
||||
|
||||
exports.angle = angle;
|
||||
exports.decibel = decibel;
|
||||
exports.flex = flex;
|
||||
exports.frequency = frequency;
|
||||
exports.length = length;
|
||||
exports.resolution = resolution;
|
||||
exports.semitones = semitones;
|
||||
exports.time = time;
|
||||
-74
@@ -1,74 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const createCustomError = require('../utils/create-custom-error.cjs');
|
||||
|
||||
const MAX_LINE_LENGTH = 100;
|
||||
const OFFSET_CORRECTION = 60;
|
||||
const TAB_REPLACEMENT = ' ';
|
||||
|
||||
function sourceFragment({ source, line, column, baseLine, baseColumn }, extraLines) {
|
||||
function processLines(start, end) {
|
||||
return lines
|
||||
.slice(start, end)
|
||||
.map((line, idx) =>
|
||||
String(start + idx + 1).padStart(maxNumLength) + ' |' + line
|
||||
).join('\n');
|
||||
}
|
||||
|
||||
const prelines = '\n'.repeat(Math.max(baseLine - 1, 0));
|
||||
const precolumns = ' '.repeat(Math.max(baseColumn - 1, 0));
|
||||
const lines = (prelines + precolumns + source).split(/\r\n?|\n|\f/);
|
||||
const startLine = Math.max(1, line - extraLines) - 1;
|
||||
const endLine = Math.min(line + extraLines, lines.length + 1);
|
||||
const maxNumLength = Math.max(4, String(endLine).length) + 1;
|
||||
let cutLeft = 0;
|
||||
|
||||
// column correction according to replaced tab before column
|
||||
column += (TAB_REPLACEMENT.length - 1) * (lines[line - 1].substr(0, column - 1).match(/\t/g) || []).length;
|
||||
|
||||
if (column > MAX_LINE_LENGTH) {
|
||||
cutLeft = column - OFFSET_CORRECTION + 3;
|
||||
column = OFFSET_CORRECTION - 2;
|
||||
}
|
||||
|
||||
for (let i = startLine; i <= endLine; i++) {
|
||||
if (i >= 0 && i < lines.length) {
|
||||
lines[i] = lines[i].replace(/\t/g, TAB_REPLACEMENT);
|
||||
lines[i] =
|
||||
(cutLeft > 0 && lines[i].length > cutLeft ? '\u2026' : '') +
|
||||
lines[i].substr(cutLeft, MAX_LINE_LENGTH - 2) +
|
||||
(lines[i].length > cutLeft + MAX_LINE_LENGTH - 1 ? '\u2026' : '');
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
processLines(startLine, line),
|
||||
new Array(column + maxNumLength + 2).join('-') + '^',
|
||||
processLines(line, endLine)
|
||||
].filter(Boolean)
|
||||
.join('\n')
|
||||
.replace(/^(\s+\d+\s+\|\n)+/, '')
|
||||
.replace(/\n(\s+\d+\s+\|)+$/, '');
|
||||
}
|
||||
|
||||
function SyntaxError(message, source, offset, line, column, baseLine = 1, baseColumn = 1) {
|
||||
const error = Object.assign(createCustomError.createCustomError('SyntaxError', message), {
|
||||
source,
|
||||
offset,
|
||||
line,
|
||||
column,
|
||||
sourceFragment(extraLines) {
|
||||
return sourceFragment({ source, line, column, baseLine, baseColumn }, isNaN(extraLines) ? 0 : extraLines);
|
||||
},
|
||||
get formattedMessage() {
|
||||
return (
|
||||
`Parse error: ${message}\n` +
|
||||
sourceFragment({ source, line, column, baseLine, baseColumn }, 2)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return error;
|
||||
}
|
||||
|
||||
exports.SyntaxError = SyntaxError;
|
||||
-379
@@ -1,379 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const List = require('../utils/List.cjs');
|
||||
const SyntaxError = require('./SyntaxError.cjs');
|
||||
const sequence = require('./sequence.cjs');
|
||||
const getTokenizer = require('../utils/get-tokenizer.cjs');
|
||||
const OffsetToLocation = require('../tokenizer/OffsetToLocation.cjs');
|
||||
const TokenStream = require('../tokenizer/TokenStream.cjs');
|
||||
const utils = require('../tokenizer/utils.cjs');
|
||||
const types = require('../tokenizer/types.cjs');
|
||||
const names = require('../tokenizer/names.cjs');
|
||||
|
||||
const NOOP = () => {};
|
||||
const EXCLAMATIONMARK = 0x0021; // U+0021 EXCLAMATION MARK (!)
|
||||
const NUMBERSIGN = 0x0023; // U+0023 NUMBER SIGN (#)
|
||||
const SEMICOLON = 0x003B; // U+003B SEMICOLON (;)
|
||||
const LEFTCURLYBRACKET = 0x007B; // U+007B LEFT CURLY BRACKET ({)
|
||||
const NULL = 0;
|
||||
|
||||
function createParseContext(name) {
|
||||
return function() {
|
||||
return this[name]();
|
||||
};
|
||||
}
|
||||
|
||||
function fetchParseValues(dict) {
|
||||
const result = Object.create(null);
|
||||
|
||||
for (const name of Object.keys(dict)) {
|
||||
const item = dict[name];
|
||||
const fn = item.parse || item;
|
||||
|
||||
if (fn) {
|
||||
result[name] = fn;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function processConfig(config) {
|
||||
const parseConfig = {
|
||||
context: Object.create(null),
|
||||
features: Object.assign(Object.create(null), config.features),
|
||||
scope: Object.assign(Object.create(null), config.scope),
|
||||
atrule: fetchParseValues(config.atrule),
|
||||
pseudo: fetchParseValues(config.pseudo),
|
||||
node: fetchParseValues(config.node),
|
||||
tokenize: getTokenizer.getTokenizer(config)
|
||||
};
|
||||
|
||||
for (const [name, context] of Object.entries(config.parseContext)) {
|
||||
switch (typeof context) {
|
||||
case 'function':
|
||||
parseConfig.context[name] = context;
|
||||
break;
|
||||
|
||||
case 'string':
|
||||
parseConfig.context[name] = createParseContext(context);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
config: parseConfig,
|
||||
...parseConfig,
|
||||
...parseConfig.node
|
||||
};
|
||||
}
|
||||
|
||||
function createParser(config) {
|
||||
let source = '';
|
||||
let filename = '<unknown>';
|
||||
let needPositions = false;
|
||||
let onParseError = NOOP;
|
||||
let onParseErrorThrow = false;
|
||||
|
||||
const locationMap = new OffsetToLocation.OffsetToLocation();
|
||||
const parser = Object.assign(new TokenStream.TokenStream(), processConfig(config || {}), {
|
||||
parseAtrulePrelude: true,
|
||||
parseRulePrelude: true,
|
||||
parseValue: true,
|
||||
parseCustomProperty: false,
|
||||
|
||||
readSequence: sequence.readSequence,
|
||||
|
||||
consumeUntilBalanceEnd: () => 0,
|
||||
consumeUntilLeftCurlyBracket(code) {
|
||||
return code === LEFTCURLYBRACKET ? 1 : 0;
|
||||
},
|
||||
consumeUntilLeftCurlyBracketOrSemicolon(code) {
|
||||
return code === LEFTCURLYBRACKET || code === SEMICOLON ? 1 : 0;
|
||||
},
|
||||
consumeUntilExclamationMarkOrSemicolon(code) {
|
||||
return code === EXCLAMATIONMARK || code === SEMICOLON ? 1 : 0;
|
||||
},
|
||||
consumeUntilSemicolonIncluded(code) {
|
||||
return code === SEMICOLON ? 2 : 0;
|
||||
},
|
||||
|
||||
createList() {
|
||||
return new List.List();
|
||||
},
|
||||
createSingleNodeList(node) {
|
||||
return new List.List().appendData(node);
|
||||
},
|
||||
getFirstListNode(list) {
|
||||
return list && list.first;
|
||||
},
|
||||
getLastListNode(list) {
|
||||
return list && list.last;
|
||||
},
|
||||
|
||||
parseWithFallback(consumer, fallback) {
|
||||
const startIndex = this.tokenIndex;
|
||||
|
||||
try {
|
||||
return consumer.call(this);
|
||||
} catch (e) {
|
||||
if (onParseErrorThrow) {
|
||||
throw e;
|
||||
}
|
||||
|
||||
this.skip(startIndex - this.tokenIndex);
|
||||
const fallbackNode = fallback.call(this);
|
||||
|
||||
onParseErrorThrow = true;
|
||||
onParseError(e, fallbackNode);
|
||||
onParseErrorThrow = false;
|
||||
|
||||
return fallbackNode;
|
||||
}
|
||||
},
|
||||
|
||||
lookupNonWSType(offset) {
|
||||
let type;
|
||||
|
||||
do {
|
||||
type = this.lookupType(offset++);
|
||||
if (type !== types.WhiteSpace && type !== types.Comment) {
|
||||
return type;
|
||||
}
|
||||
} while (type !== NULL);
|
||||
|
||||
return NULL;
|
||||
},
|
||||
|
||||
charCodeAt(offset) {
|
||||
return offset >= 0 && offset < source.length ? source.charCodeAt(offset) : 0;
|
||||
},
|
||||
substring(offsetStart, offsetEnd) {
|
||||
return source.substring(offsetStart, offsetEnd);
|
||||
},
|
||||
substrToCursor(start) {
|
||||
return this.source.substring(start, this.tokenStart);
|
||||
},
|
||||
|
||||
cmpChar(offset, charCode) {
|
||||
return utils.cmpChar(source, offset, charCode);
|
||||
},
|
||||
cmpStr(offsetStart, offsetEnd, str) {
|
||||
return utils.cmpStr(source, offsetStart, offsetEnd, str);
|
||||
},
|
||||
|
||||
consume(tokenType) {
|
||||
const start = this.tokenStart;
|
||||
|
||||
this.eat(tokenType);
|
||||
|
||||
return this.substrToCursor(start);
|
||||
},
|
||||
consumeFunctionName() {
|
||||
const name = source.substring(this.tokenStart, this.tokenEnd - 1);
|
||||
|
||||
this.eat(types.Function);
|
||||
|
||||
return name;
|
||||
},
|
||||
consumeNumber(type) {
|
||||
const number = source.substring(this.tokenStart, utils.consumeNumber(source, this.tokenStart));
|
||||
|
||||
this.eat(type);
|
||||
|
||||
return number;
|
||||
},
|
||||
|
||||
eat(tokenType) {
|
||||
if (this.tokenType !== tokenType) {
|
||||
const tokenName = names[tokenType].slice(0, -6).replace(/-/g, ' ').replace(/^./, m => m.toUpperCase());
|
||||
let message = `${/[[\](){}]/.test(tokenName) ? `"${tokenName}"` : tokenName} is expected`;
|
||||
let offset = this.tokenStart;
|
||||
|
||||
// tweak message and offset
|
||||
switch (tokenType) {
|
||||
case types.Ident:
|
||||
// when identifier is expected but there is a function or url
|
||||
if (this.tokenType === types.Function || this.tokenType === types.Url) {
|
||||
offset = this.tokenEnd - 1;
|
||||
message = 'Identifier is expected but function found';
|
||||
} else {
|
||||
message = 'Identifier is expected';
|
||||
}
|
||||
break;
|
||||
|
||||
case types.Hash:
|
||||
if (this.isDelim(NUMBERSIGN)) {
|
||||
this.next();
|
||||
offset++;
|
||||
message = 'Name is expected';
|
||||
}
|
||||
break;
|
||||
|
||||
case types.Percentage:
|
||||
if (this.tokenType === types.Number) {
|
||||
offset = this.tokenEnd;
|
||||
message = 'Percent sign is expected';
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
this.error(message, offset);
|
||||
}
|
||||
|
||||
this.next();
|
||||
},
|
||||
eatIdent(name) {
|
||||
if (this.tokenType !== types.Ident || this.lookupValue(0, name) === false) {
|
||||
this.error(`Identifier "${name}" is expected`);
|
||||
}
|
||||
|
||||
this.next();
|
||||
},
|
||||
eatDelim(code) {
|
||||
if (!this.isDelim(code)) {
|
||||
this.error(`Delim "${String.fromCharCode(code)}" is expected`);
|
||||
}
|
||||
|
||||
this.next();
|
||||
},
|
||||
|
||||
getLocation(start, end) {
|
||||
if (needPositions) {
|
||||
return locationMap.getLocationRange(
|
||||
start,
|
||||
end,
|
||||
filename
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
getLocationFromList(list) {
|
||||
if (needPositions) {
|
||||
const head = this.getFirstListNode(list);
|
||||
const tail = this.getLastListNode(list);
|
||||
return locationMap.getLocationRange(
|
||||
head !== null ? head.loc.start.offset - locationMap.startOffset : this.tokenStart,
|
||||
tail !== null ? tail.loc.end.offset - locationMap.startOffset : this.tokenStart,
|
||||
filename
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
|
||||
error(message, offset) {
|
||||
const location = typeof offset !== 'undefined' && offset < source.length
|
||||
? locationMap.getLocation(offset)
|
||||
: this.eof
|
||||
? locationMap.getLocation(utils.findWhiteSpaceStart(source, source.length - 1))
|
||||
: locationMap.getLocation(this.tokenStart);
|
||||
|
||||
throw new SyntaxError.SyntaxError(
|
||||
message || 'Unexpected input',
|
||||
source,
|
||||
location.offset,
|
||||
location.line,
|
||||
location.column,
|
||||
locationMap.startLine,
|
||||
locationMap.startColumn
|
||||
);
|
||||
}
|
||||
});
|
||||
const createTokenIterateAPI = () => ({
|
||||
filename,
|
||||
source,
|
||||
tokenCount: parser.tokenCount,
|
||||
|
||||
getTokenType: (index) =>
|
||||
parser.getTokenType(index),
|
||||
getTokenTypeName: (index) =>
|
||||
names[parser.getTokenType(index)],
|
||||
getTokenStart: (index) =>
|
||||
parser.getTokenStart(index),
|
||||
getTokenEnd: (index) =>
|
||||
parser.getTokenEnd(index),
|
||||
getTokenValue: (index) =>
|
||||
parser.source.substring(parser.getTokenStart(index), parser.getTokenEnd(index)),
|
||||
|
||||
substring: (start, end) =>
|
||||
parser.source.substring(start, end),
|
||||
|
||||
balance: parser.balance.subarray(0, parser.tokenCount + 1),
|
||||
isBlockOpenerTokenType: parser.isBlockOpenerTokenType,
|
||||
isBlockCloserTokenType: parser.isBlockCloserTokenType,
|
||||
getBlockTokenPairIndex: (index) =>
|
||||
parser.getBlockTokenPairIndex(index),
|
||||
|
||||
getLocation: (offset) =>
|
||||
locationMap.getLocation(offset, filename),
|
||||
getRangeLocation: (start, end) =>
|
||||
locationMap.getLocationRange(start, end, filename)
|
||||
});
|
||||
|
||||
const parse = function(source_, options) {
|
||||
source = source_;
|
||||
options = options || {};
|
||||
|
||||
parser.setSource(source, parser.tokenize);
|
||||
locationMap.setSource(
|
||||
source,
|
||||
options.offset,
|
||||
options.line,
|
||||
options.column
|
||||
);
|
||||
|
||||
filename = options.filename || '<unknown>';
|
||||
needPositions = Boolean(options.positions);
|
||||
onParseError = typeof options.onParseError === 'function' ? options.onParseError : NOOP;
|
||||
onParseErrorThrow = false;
|
||||
|
||||
parser.parseAtrulePrelude = 'parseAtrulePrelude' in options ? Boolean(options.parseAtrulePrelude) : true;
|
||||
parser.parseRulePrelude = 'parseRulePrelude' in options ? Boolean(options.parseRulePrelude) : true;
|
||||
parser.parseValue = 'parseValue' in options ? Boolean(options.parseValue) : true;
|
||||
parser.parseCustomProperty = 'parseCustomProperty' in options ? Boolean(options.parseCustomProperty) : false;
|
||||
|
||||
const { context = 'default', onComment, onToken } = options;
|
||||
|
||||
if (context in parser.context === false) {
|
||||
throw new Error('Unknown context `' + context + '`');
|
||||
}
|
||||
|
||||
if (Array.isArray(onToken)) {
|
||||
parser.forEachToken((type, start, end) => {
|
||||
onToken.push({ type, start, end });
|
||||
});
|
||||
} else if (typeof onToken === 'function') {
|
||||
parser.forEachToken(onToken.bind(createTokenIterateAPI()));
|
||||
}
|
||||
|
||||
if (typeof onComment === 'function') {
|
||||
parser.forEachToken((type, start, end) => {
|
||||
if (type === types.Comment) {
|
||||
const loc = parser.getLocation(start, end);
|
||||
const value = utils.cmpStr(source, end - 2, end, '*/')
|
||||
? source.slice(start + 2, end - 2)
|
||||
: source.slice(start + 2, end);
|
||||
|
||||
onComment(value, loc);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const ast = parser.context[context].call(parser, options);
|
||||
|
||||
if (!parser.eof) {
|
||||
parser.error();
|
||||
}
|
||||
|
||||
return ast;
|
||||
};
|
||||
|
||||
return Object.assign(parse, {
|
||||
SyntaxError: SyntaxError.SyntaxError,
|
||||
config: parser.config
|
||||
});
|
||||
}
|
||||
|
||||
exports.createParser = createParser;
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const create = require('./create.cjs');
|
||||
const parser = require('../syntax/config/parser.cjs');
|
||||
|
||||
const index = create.createParser(parser);
|
||||
|
||||
module.exports = index;
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const create = require('./create.cjs');
|
||||
const parserSelector = require('../syntax/config/parser-selector.cjs');
|
||||
|
||||
const parseSelector = create.createParser(parserSelector);
|
||||
|
||||
module.exports = parseSelector;
|
||||
-47
@@ -1,47 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const types = require('../tokenizer/types.cjs');
|
||||
|
||||
function readSequence(recognizer) {
|
||||
const children = this.createList();
|
||||
let space = false;
|
||||
const context = {
|
||||
recognizer
|
||||
};
|
||||
|
||||
while (!this.eof) {
|
||||
switch (this.tokenType) {
|
||||
case types.Comment:
|
||||
this.next();
|
||||
continue;
|
||||
|
||||
case types.WhiteSpace:
|
||||
space = true;
|
||||
this.next();
|
||||
continue;
|
||||
}
|
||||
|
||||
let child = recognizer.getNode.call(this, context);
|
||||
|
||||
if (child === undefined) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (space) {
|
||||
if (recognizer.onWhiteSpace) {
|
||||
recognizer.onWhiteSpace.call(this, child, children, context);
|
||||
}
|
||||
space = false;
|
||||
}
|
||||
|
||||
children.push(child);
|
||||
}
|
||||
|
||||
if (space && recognizer.onWhiteSpace) {
|
||||
recognizer.onWhiteSpace.call(this, null, children, context);
|
||||
}
|
||||
|
||||
return children;
|
||||
}
|
||||
|
||||
exports.readSequence = readSequence;
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const types = require('../../tokenizer/types.cjs');
|
||||
|
||||
// https://drafts.csswg.org/css-contain-3/#container-rule
|
||||
// The keywords `none`, `and`, `not`, and `or` are excluded from the <custom-ident> above.
|
||||
const nonContainerNameKeywords = new Set(['none', 'and', 'not', 'or']);
|
||||
|
||||
const container = {
|
||||
parse: {
|
||||
prelude() {
|
||||
const children = this.createList();
|
||||
|
||||
if (this.tokenType === types.Ident) {
|
||||
const name = this.substring(this.tokenStart, this.tokenEnd);
|
||||
|
||||
if (!nonContainerNameKeywords.has(name.toLowerCase())) {
|
||||
children.push(this.Identifier());
|
||||
}
|
||||
}
|
||||
|
||||
children.push(this.Condition('container'));
|
||||
|
||||
return children;
|
||||
},
|
||||
block(nested = false) {
|
||||
return this.Block(nested);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = container;
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const fontFace = {
|
||||
parse: {
|
||||
prelude: null,
|
||||
block() {
|
||||
return this.Block(true);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = fontFace;
|
||||
-101
@@ -1,101 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const types = require('../../tokenizer/types.cjs');
|
||||
|
||||
function parseWithFallback(parse, fallback) {
|
||||
return this.parseWithFallback(
|
||||
() => {
|
||||
try {
|
||||
return parse.call(this);
|
||||
} finally {
|
||||
this.skipSC();
|
||||
if (this.lookupNonWSType(0) !== types.RightParenthesis) {
|
||||
this.error();
|
||||
}
|
||||
}
|
||||
},
|
||||
fallback || (() => this.Raw(null, true))
|
||||
);
|
||||
}
|
||||
|
||||
const parseFunctions = {
|
||||
layer() {
|
||||
this.skipSC();
|
||||
|
||||
const children = this.createList();
|
||||
const node = parseWithFallback.call(this, this.Layer);
|
||||
|
||||
if (node.type !== 'Raw' || node.value !== '') {
|
||||
children.push(node);
|
||||
}
|
||||
|
||||
return children;
|
||||
},
|
||||
supports() {
|
||||
this.skipSC();
|
||||
|
||||
const children = this.createList();
|
||||
const node = parseWithFallback.call(
|
||||
this,
|
||||
this.Declaration,
|
||||
() => parseWithFallback.call(this, () => this.Condition('supports'))
|
||||
);
|
||||
|
||||
if (node.type !== 'Raw' || node.value !== '') {
|
||||
children.push(node);
|
||||
}
|
||||
|
||||
return children;
|
||||
}
|
||||
};
|
||||
|
||||
const importAtrule = {
|
||||
parse: {
|
||||
prelude() {
|
||||
const children = this.createList();
|
||||
|
||||
switch (this.tokenType) {
|
||||
case types.String:
|
||||
children.push(this.String());
|
||||
break;
|
||||
|
||||
case types.Url:
|
||||
case types.Function:
|
||||
children.push(this.Url());
|
||||
break;
|
||||
|
||||
default:
|
||||
this.error('String or url() is expected');
|
||||
}
|
||||
|
||||
this.skipSC();
|
||||
|
||||
if (this.tokenType === types.Ident &&
|
||||
this.cmpStr(this.tokenStart, this.tokenEnd, 'layer')) {
|
||||
children.push(this.Identifier());
|
||||
} else if (
|
||||
this.tokenType === types.Function &&
|
||||
this.cmpStr(this.tokenStart, this.tokenEnd, 'layer(')
|
||||
) {
|
||||
children.push(this.Function(null, parseFunctions));
|
||||
}
|
||||
|
||||
this.skipSC();
|
||||
|
||||
if (this.tokenType === types.Function &&
|
||||
this.cmpStr(this.tokenStart, this.tokenEnd, 'supports(')) {
|
||||
children.push(this.Function(null, parseFunctions));
|
||||
}
|
||||
|
||||
if (this.lookupNonWSType(0) === types.Ident ||
|
||||
this.lookupNonWSType(0) === types.LeftParenthesis) {
|
||||
children.push(this.MediaQueryList());
|
||||
}
|
||||
|
||||
return children;
|
||||
},
|
||||
block: null
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = importAtrule;
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const container = require('./container.cjs');
|
||||
const fontFace = require('./font-face.cjs');
|
||||
const _import = require('./import.cjs');
|
||||
const layer = require('./layer.cjs');
|
||||
const media = require('./media.cjs');
|
||||
const nest = require('./nest.cjs');
|
||||
const page = require('./page.cjs');
|
||||
const scope = require('./scope.cjs');
|
||||
const startingStyle = require('./starting-style.cjs');
|
||||
const supports = require('./supports.cjs');
|
||||
|
||||
const atrule = {
|
||||
container,
|
||||
'font-face': fontFace,
|
||||
import: _import,
|
||||
layer,
|
||||
media,
|
||||
nest,
|
||||
page,
|
||||
scope,
|
||||
'starting-style': startingStyle,
|
||||
supports
|
||||
};
|
||||
|
||||
module.exports = atrule;
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const layer = {
|
||||
parse: {
|
||||
prelude() {
|
||||
return this.createSingleNodeList(
|
||||
this.LayerList()
|
||||
);
|
||||
},
|
||||
block() {
|
||||
return this.Block(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = layer;
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const media = {
|
||||
parse: {
|
||||
prelude() {
|
||||
return this.createSingleNodeList(
|
||||
this.MediaQueryList()
|
||||
);
|
||||
},
|
||||
block(nested = false) {
|
||||
return this.Block(nested);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = media;
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const nest = {
|
||||
parse: {
|
||||
prelude() {
|
||||
return this.createSingleNodeList(
|
||||
this.SelectorList()
|
||||
);
|
||||
},
|
||||
block() {
|
||||
return this.Block(true);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = nest;
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const page = {
|
||||
parse: {
|
||||
prelude() {
|
||||
return this.createSingleNodeList(
|
||||
this.SelectorList()
|
||||
);
|
||||
},
|
||||
block() {
|
||||
return this.Block(true);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = page;
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const scope = {
|
||||
parse: {
|
||||
prelude() {
|
||||
return this.createSingleNodeList(
|
||||
this.Scope()
|
||||
);
|
||||
},
|
||||
block(nested = false) {
|
||||
return this.Block(nested);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = scope;
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const startingStyle = {
|
||||
parse: {
|
||||
prelude: null,
|
||||
block(nested = false) {
|
||||
return this.Block(nested);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = startingStyle;
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const supports = {
|
||||
parse: {
|
||||
prelude() {
|
||||
return this.createSingleNodeList(
|
||||
this.Condition('supports')
|
||||
);
|
||||
},
|
||||
block(nested = false) {
|
||||
return this.Block(nested);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = supports;
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const indexGenerate = require('../node/index-generate.cjs');
|
||||
|
||||
const config = {
|
||||
node: indexGenerate
|
||||
};
|
||||
|
||||
module.exports = config;
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const genericConst = require('../../lexer/generic-const.cjs');
|
||||
const data = require('../../data.cjs');
|
||||
const index = require('../node/index.cjs');
|
||||
|
||||
const lexerConfig = {
|
||||
generic: true,
|
||||
cssWideKeywords: genericConst.cssWideKeywords,
|
||||
...data,
|
||||
node: index
|
||||
};
|
||||
|
||||
module.exports = lexerConfig;
|
||||
-132
@@ -1,132 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
function appendOrSet(a, b) {
|
||||
if (typeof b === 'string' && /^\s*\|/.test(b)) {
|
||||
return typeof a === 'string'
|
||||
? a + b
|
||||
: b.replace(/^\s*\|\s*/, '');
|
||||
}
|
||||
|
||||
return b || null;
|
||||
}
|
||||
|
||||
function extractProps(obj, props) {
|
||||
const result = Object.create(null);
|
||||
|
||||
for (const prop of Object.keys(obj)) {
|
||||
if (props.includes(prop)) {
|
||||
result[prop] = obj[prop];
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function mergeDicts(base, ext, fields) {
|
||||
const result = { ...base };
|
||||
|
||||
for (const [key, props] of Object.entries(ext)) {
|
||||
result[key] = {
|
||||
...result[key],
|
||||
...fields ? extractProps(props, fields) : props
|
||||
};
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function mix(dest, src) {
|
||||
const result = { ...dest };
|
||||
|
||||
for (const [prop, value] of Object.entries(src)) {
|
||||
switch (prop) {
|
||||
case 'generic':
|
||||
result[prop] = Boolean(value);
|
||||
break;
|
||||
|
||||
case 'cssWideKeywords':
|
||||
result[prop] = dest[prop]
|
||||
? [...dest[prop], ...value]
|
||||
: value || [];
|
||||
break;
|
||||
|
||||
case 'units':
|
||||
result[prop] = { ...dest[prop] };
|
||||
for (const [name, patch] of Object.entries(value)) {
|
||||
result[prop][name] = Array.isArray(patch) ? patch : [];
|
||||
}
|
||||
break;
|
||||
|
||||
case 'atrules':
|
||||
result[prop] = { ...dest[prop] };
|
||||
|
||||
for (const [name, atrule] of Object.entries(value)) {
|
||||
const exists = result[prop][name] || {};
|
||||
const current = result[prop][name] = {
|
||||
prelude: exists.prelude || null,
|
||||
descriptors: {
|
||||
...exists.descriptors
|
||||
}
|
||||
};
|
||||
|
||||
if (!atrule) {
|
||||
continue;
|
||||
}
|
||||
|
||||
current.prelude = atrule.prelude
|
||||
? appendOrSet(current.prelude, atrule.prelude)
|
||||
: current.prelude || null;
|
||||
|
||||
for (const [descriptorName, descriptorValue] of Object.entries(atrule.descriptors || {})) {
|
||||
current.descriptors[descriptorName] = descriptorValue
|
||||
? appendOrSet(current.descriptors[descriptorName], descriptorValue)
|
||||
: null;
|
||||
}
|
||||
|
||||
if (!Object.keys(current.descriptors).length) {
|
||||
current.descriptors = null;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'types':
|
||||
case 'properties':
|
||||
result[prop] = { ...dest[prop] };
|
||||
for (const [name, syntax] of Object.entries(value)) {
|
||||
result[prop][name] = appendOrSet(result[prop][name], syntax);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'parseContext':
|
||||
result[prop] = {
|
||||
...dest[prop],
|
||||
...value
|
||||
};
|
||||
break;
|
||||
|
||||
case 'scope':
|
||||
case 'features':
|
||||
result[prop] = mergeDicts(dest[prop], value);
|
||||
break;
|
||||
|
||||
case 'atrule':
|
||||
case 'pseudo':
|
||||
result[prop] = mergeDicts(dest[prop], value, ['parse']);
|
||||
break;
|
||||
|
||||
case 'node':
|
||||
result[prop] = mergeDicts(dest[prop], value, ['name', 'structure', 'parse', 'generate', 'walkContext']);
|
||||
break;
|
||||
|
||||
case 'tokenize':
|
||||
if (typeof value === 'function') {
|
||||
result[prop] = value;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
module.exports = mix;
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const index = require('../pseudo/index.cjs');
|
||||
const indexParseSelector = require('../node/index-parse-selector.cjs');
|
||||
const selector = require('../scope/selector.cjs');
|
||||
|
||||
const config = {
|
||||
parseContext: {
|
||||
default: 'SelectorList',
|
||||
selectorList: 'SelectorList',
|
||||
selector: 'Selector'
|
||||
},
|
||||
scope: { Selector: selector },
|
||||
atrule: {},
|
||||
pseudo: index,
|
||||
node: indexParseSelector
|
||||
};
|
||||
|
||||
module.exports = config;
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const index = require('../scope/index.cjs');
|
||||
const index$1 = require('../atrule/index.cjs');
|
||||
const index$2 = require('../pseudo/index.cjs');
|
||||
const indexParse = require('../node/index-parse.cjs');
|
||||
const index$3 = require('../../tokenizer/index.cjs');
|
||||
|
||||
const config = {
|
||||
parseContext: {
|
||||
default: 'StyleSheet',
|
||||
stylesheet: 'StyleSheet',
|
||||
atrule: 'Atrule',
|
||||
atrulePrelude(options) {
|
||||
return this.AtrulePrelude(options.atrule ? String(options.atrule) : null);
|
||||
},
|
||||
mediaQueryList: 'MediaQueryList',
|
||||
mediaQuery: 'MediaQuery',
|
||||
condition(options) {
|
||||
return this.Condition(options.kind);
|
||||
},
|
||||
rule: 'Rule',
|
||||
selectorList: 'SelectorList',
|
||||
selector: 'Selector',
|
||||
block() {
|
||||
return this.Block(true);
|
||||
},
|
||||
declarationList: 'DeclarationList',
|
||||
declaration: 'Declaration',
|
||||
value: 'Value'
|
||||
},
|
||||
features: {
|
||||
supports: {
|
||||
selector() {
|
||||
return this.Selector();
|
||||
}
|
||||
},
|
||||
container: {
|
||||
style() {
|
||||
return this.Declaration();
|
||||
}
|
||||
}
|
||||
},
|
||||
scope: index,
|
||||
atrule: index$1,
|
||||
pseudo: index$2,
|
||||
node: indexParse,
|
||||
tokenize: index$3.tokenize
|
||||
};
|
||||
|
||||
module.exports = config;
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const index = require('../node/index.cjs');
|
||||
|
||||
const config = {
|
||||
node: index
|
||||
};
|
||||
|
||||
module.exports = config;
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const create = require('../parser/create.cjs');
|
||||
const create$2 = require('../generator/create.cjs');
|
||||
const create$3 = require('../convertor/create.cjs');
|
||||
const create$1 = require('../walker/create.cjs');
|
||||
const Lexer = require('../lexer/Lexer.cjs');
|
||||
const mix = require('./config/mix.cjs');
|
||||
const getTokenizer = require('../utils/get-tokenizer.cjs');
|
||||
|
||||
function createSyntax(config) {
|
||||
const parse = create.createParser(config);
|
||||
const walk = create$1.createWalker(config);
|
||||
const generate = create$2.createGenerator(config);
|
||||
const { fromPlainObject, toPlainObject } = create$3.createConvertor(walk);
|
||||
|
||||
const syntax = {
|
||||
lexer: null,
|
||||
createLexer: config => new Lexer.Lexer(config, syntax, syntax.lexer.structure),
|
||||
|
||||
tokenize: getTokenizer.getTokenizer(config),
|
||||
parse,
|
||||
generate,
|
||||
|
||||
walk,
|
||||
find: walk.find,
|
||||
findLast: walk.findLast,
|
||||
findAll: walk.findAll,
|
||||
|
||||
fromPlainObject,
|
||||
toPlainObject,
|
||||
|
||||
fork(extension) {
|
||||
const base = mix({}, config); // copy of config
|
||||
|
||||
return createSyntax(
|
||||
typeof extension === 'function'
|
||||
? extension(base) // TODO: remove Object.assign as second parameter
|
||||
: mix(base, extension)
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
syntax.lexer = new Lexer.Lexer({
|
||||
generic: config.generic,
|
||||
cssWideKeywords: config.cssWideKeywords,
|
||||
units: config.units,
|
||||
types: config.types,
|
||||
atrules: config.atrules,
|
||||
properties: config.properties,
|
||||
node: config.node
|
||||
}, syntax);
|
||||
|
||||
return syntax;
|
||||
}
|
||||
const createSyntax$1 = config => createSyntax(mix({}, config));
|
||||
|
||||
module.exports = createSyntax$1;
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
// legacy IE function
|
||||
// expression( <any-value> )
|
||||
function expressionFn() {
|
||||
return this.createSingleNodeList(
|
||||
this.Raw(null, false)
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = expressionFn;
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const types = require('../../tokenizer/types.cjs');
|
||||
|
||||
// var( <ident> , <value>? )
|
||||
function varFn() {
|
||||
const children = this.createList();
|
||||
|
||||
this.skipSC();
|
||||
|
||||
// NOTE: Don't check more than a first argument is an ident, rest checks are for lexer
|
||||
children.push(this.Identifier());
|
||||
|
||||
this.skipSC();
|
||||
|
||||
if (this.tokenType === types.Comma) {
|
||||
children.push(this.Operator());
|
||||
|
||||
const startIndex = this.tokenIndex;
|
||||
const value = this.parseCustomProperty
|
||||
? this.Value(null)
|
||||
: this.Raw(this.consumeUntilExclamationMarkOrSemicolon, false);
|
||||
|
||||
if (value.type === 'Value' && value.children.isEmpty) {
|
||||
for (let offset = startIndex - this.tokenIndex; offset <= 0; offset++) {
|
||||
if (this.lookupType(offset) === types.WhiteSpace) {
|
||||
value.children.appendData({
|
||||
type: 'WhiteSpace',
|
||||
loc: null,
|
||||
value: ' '
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
children.push(value);
|
||||
}
|
||||
|
||||
return children;
|
||||
}
|
||||
|
||||
module.exports = varFn;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user