tools: update eslint to 8.47.0

PR-URL: https://github.com/nodejs/node/pull/49124
Backport-PR-URL: https://github.com/nodejs/node/pull/50669
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Moshe Atlow <moshe@atlow.co.il>
This commit is contained in:
Node.js GitHub Bot authored and Michaël Zasso committed 2023-11-23 10:52:20 +01:00
1 parent 4880a05fa2
commit 0940de36ee
702 files changed
+4520 -1674

No files matched your search

+18 -6
View File
@@ -5,6 +5,12 @@
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const { getVariableByName } = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
@@ -28,18 +34,24 @@ module.exports = {
},
create(context) {
const { sourceCode } = context;
return {
NewExpression(node) {
const wrapperObjects = ["String", "Number", "Boolean"];
const { name } = node.callee;
if (wrapperObjects.includes(node.callee.name)) {
context.report({
node,
messageId: "noConstructor",
data: { fn: node.callee.name }
});
if (wrapperObjects.includes(name)) {
const variable = getVariableByName(sourceCode.getScope(node), name);
if (variable && variable.identifiers.length === 0) {
context.report({
node,
messageId: "noConstructor",
data: { fn: name }
});
}
}
}
};
+4 -4
View File
@@ -26,8 +26,8 @@ const {
const anyFunctionPattern = /^(?:Function(?:Declaration|Expression)|ArrowFunctionExpression)$/u;
const anyLoopPattern = /^(?:DoWhile|For|ForIn|ForOf|While)Statement$/u;
const arrayMethodWithThisArgPattern = /^(?:every|filter|find(?:Last)?(?:Index)?|flatMap|forEach|map|some)$/u;
const arrayOrTypedArrayPattern = /Array$/u;
const arrayMethodPattern = /^(?:every|filter|find|findIndex|forEach|map|some)$/u;
const bindOrCallOrApplyPattern = /^(?:bind|call|apply)$/u;
const thisTagPattern = /^[\s*]*@this/mu;
@@ -467,12 +467,12 @@ function isArrayFromMethod(node) {
}
/**
* Checks whether or not a node is a method which has `thisArg`.
* Checks whether or not a node is a method which expects a function as a first argument, and `thisArg` as a second argument.
* @param {ASTNode} node A node to check.
* @returns {boolean} Whether or not the node is a method which has `thisArg`.
* @returns {boolean} Whether or not the node is a method which expects a function as a first argument, and `thisArg` as a second argument.
*/
function isMethodWhichHasThisArg(node) {
return isSpecificMemberAccess(node, null, arrayMethodPattern);
return isSpecificMemberAccess(node, null, arrayMethodWithThisArgPattern);
}
/**
+15 -1
View File
@@ -6,6 +6,20 @@ Object.defineProperty(exports, "__esModule", {
exports.codeFrameColumns = codeFrameColumns;
exports.default = _default;
var _highlight = require("@babel/highlight");
var _chalk2 = require("chalk");
const chalk = _chalk2;
let chalkWithForcedColor = undefined;
function getChalk(forceColor) {
if (forceColor) {
var _chalkWithForcedColor;
(_chalkWithForcedColor = chalkWithForcedColor) != null ? _chalkWithForcedColor : chalkWithForcedColor = new chalk.constructor({
enabled: true,
level: 1
});
return chalkWithForcedColor;
}
return chalk;
}
let deprecationWarningShown = false;
function getDefs(chalk) {
return {
@@ -73,7 +87,7 @@ function getMarkerLines(loc, source, opts) {
}
function codeFrameColumns(rawLines, loc, opts = {}) {
const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts);
const chalk = (0, _highlight.getChalk)(opts);
const chalk = getChalk(opts.forceColor);
const defs = getDefs(chalk);
const maybeHighlight = (chalkFn, string) => {
return highlighted ? chalkFn(string) : string;
@@ -0,0 +1,165 @@
'use strict';
const colorConvert = require('color-convert');
const wrapAnsi16 = (fn, offset) => function () {
const code = fn.apply(colorConvert, arguments);
return `\u001B[${code + offset}m`;
};
const wrapAnsi256 = (fn, offset) => function () {
const code = fn.apply(colorConvert, arguments);
return `\u001B[${38 + offset};5;${code}m`;
};
const wrapAnsi16m = (fn, offset) => function () {
const rgb = fn.apply(colorConvert, arguments);
return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
};
function assembleStyles() {
const codes = new Map();
const styles = {
modifier: {
reset: [0, 0],
// 21 isn't widely supported and 22 does the same thing
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
color: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39],
// Bright color
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39]
},
bgColor: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
// Bright color
bgBlackBright: [100, 49],
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49]
}
};
// Fix humans
styles.color.grey = styles.color.gray;
for (const groupName of Object.keys(styles)) {
const group = styles[groupName];
for (const styleName of Object.keys(group)) {
const style = group[styleName];
styles[styleName] = {
open: `\u001B[${style[0]}m`,
close: `\u001B[${style[1]}m`
};
group[styleName] = styles[styleName];
codes.set(style[0], style[1]);
}
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false
});
Object.defineProperty(styles, 'codes', {
value: codes,
enumerable: false
});
}
const ansi2ansi = n => n;
const rgb2rgb = (r, g, b) => [r, g, b];
styles.color.close = '\u001B[39m';
styles.bgColor.close = '\u001B[49m';
styles.color.ansi = {
ansi: wrapAnsi16(ansi2ansi, 0)
};
styles.color.ansi256 = {
ansi256: wrapAnsi256(ansi2ansi, 0)
};
styles.color.ansi16m = {
rgb: wrapAnsi16m(rgb2rgb, 0)
};
styles.bgColor.ansi = {
ansi: wrapAnsi16(ansi2ansi, 10)
};
styles.bgColor.ansi256 = {
ansi256: wrapAnsi256(ansi2ansi, 10)
};
styles.bgColor.ansi16m = {
rgb: wrapAnsi16m(rgb2rgb, 10)
};
for (let key of Object.keys(colorConvert)) {
if (typeof colorConvert[key] !== 'object') {
continue;
}
const suite = colorConvert[key];
if (key === 'ansi16') {
key = 'ansi';
}
if ('ansi16' in suite) {
styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
}
if ('ansi256' in suite) {
styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
}
if ('rgb' in suite) {
styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
}
}
return styles;
}
// Make the export immutable
Object.defineProperty(module, 'exports', {
enumerable: true,
get: assembleStyles
});
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,56 @@
{
"name": "ansi-styles",
"version": "3.2.1",
"description": "ANSI escape codes for styling strings in the terminal",
"license": "MIT",
"repository": "chalk/ansi-styles",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=4"
},
"scripts": {
"test": "xo && ava",
"screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor"
},
"files": [
"index.js"
],
"keywords": [
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"dependencies": {
"color-convert": "^1.9.0"
},
"devDependencies": {
"ava": "*",
"babel-polyfill": "^6.23.0",
"svg-term-cli": "^2.1.1",
"xo": "*"
},
"ava": {
"require": "babel-polyfill"
}
}
@@ -0,0 +1,147 @@
# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles)
> [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal
You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings.
<img src="https://cdn.rawgit.com/chalk/ansi-styles/8261697c95bf34b6c7767e2cbe9941a851d59385/screenshot.svg" width="900">
## Install
```
$ npm install ansi-styles
```
## Usage
```js
const style = require('ansi-styles');
console.log(`${style.green.open}Hello world!${style.green.close}`);
// Color conversion between 16/256/truecolor
// NOTE: If conversion goes to 16 colors or 256 colors, the original color
// may be degraded to fit that color palette. This means terminals
// that do not support 16 million colors will best-match the
// original color.
console.log(style.bgColor.ansi.hsl(120, 80, 72) + 'Hello world!' + style.bgColor.close);
console.log(style.color.ansi256.rgb(199, 20, 250) + 'Hello world!' + style.color.close);
console.log(style.color.ansi16m.hex('#ABCDEF') + 'Hello world!' + style.color.close);
```
## API
Each style has an `open` and `close` property.
## Styles
### Modifiers
- `reset`
- `bold`
- `dim`
- `italic` *(Not widely supported)*
- `underline`
- `inverse`
- `hidden`
- `strikethrough` *(Not widely supported)*
### Colors
- `black`
- `red`
- `green`
- `yellow`
- `blue`
- `magenta`
- `cyan`
- `white`
- `gray` ("bright black")
- `redBright`
- `greenBright`
- `yellowBright`
- `blueBright`
- `magentaBright`
- `cyanBright`
- `whiteBright`
### Background colors
- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
- `bgBlackBright`
- `bgRedBright`
- `bgGreenBright`
- `bgYellowBright`
- `bgBlueBright`
- `bgMagentaBright`
- `bgCyanBright`
- `bgWhiteBright`
## Advanced usage
By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module.
- `style.modifier`
- `style.color`
- `style.bgColor`
###### Example
```js
console.log(style.color.green.open);
```
Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `style.codes`, which returns a `Map` with the open codes as keys and close codes as values.
###### Example
```js
console.log(style.codes.get(36));
//=> 39
```
## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728)
`ansi-styles` uses the [`color-convert`](https://github.com/Qix-/color-convert) package to allow for converting between various colors and ANSI escapes, with support for 256 and 16 million colors.
To use these, call the associated conversion function with the intended output, for example:
```js
style.color.ansi.rgb(100, 200, 15); // RGB to 16 color ansi foreground code
style.bgColor.ansi.rgb(100, 200, 15); // RGB to 16 color ansi background code
style.color.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code
style.bgColor.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code
style.color.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color foreground code
style.bgColor.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color background code
```
## Related
- [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)
## License
MIT
@@ -0,0 +1,228 @@
'use strict';
const escapeStringRegexp = require('escape-string-regexp');
const ansiStyles = require('ansi-styles');
const stdoutColor = require('supports-color').stdout;
const template = require('./templates.js');
const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm');
// `supportsColor.level` → `ansiStyles.color[name]` mapping
const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
// `color-convert` models to exclude from the Chalk API due to conflicts and such
const skipModels = new Set(['gray']);
const styles = Object.create(null);
function applyOptions(obj, options) {
options = options || {};
// Detect level if not set manually
const scLevel = stdoutColor ? stdoutColor.level : 0;
obj.level = options.level === undefined ? scLevel : options.level;
obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
}
function Chalk(options) {
// We check for this.template here since calling `chalk.constructor()`
// by itself will have a `this` of a previously constructed chalk object
if (!this || !(this instanceof Chalk) || this.template) {
const chalk = {};
applyOptions(chalk, options);
chalk.template = function () {
const args = [].slice.call(arguments);
return chalkTag.apply(null, [chalk.template].concat(args));
};
Object.setPrototypeOf(chalk, Chalk.prototype);
Object.setPrototypeOf(chalk.template, chalk);
chalk.template.constructor = Chalk;
return chalk.template;
}
applyOptions(this, options);
}
// Use bright blue on Windows as the normal blue color is illegible
if (isSimpleWindowsTerm) {
ansiStyles.blue.open = '\u001B[94m';
}
for (const key of Object.keys(ansiStyles)) {
ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
styles[key] = {
get() {
const codes = ansiStyles[key];
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
}
};
}
styles.visible = {
get() {
return build.call(this, this._styles || [], true, 'visible');
}
};
ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
for (const model of Object.keys(ansiStyles.color.ansi)) {
if (skipModels.has(model)) {
continue;
}
styles[model] = {
get() {
const level = this.level;
return function () {
const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
const codes = {
open,
close: ansiStyles.color.close,
closeRe: ansiStyles.color.closeRe
};
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
};
}
};
}
ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
if (skipModels.has(model)) {
continue;
}
const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
styles[bgModel] = {
get() {
const level = this.level;
return function () {
const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
const codes = {
open,
close: ansiStyles.bgColor.close,
closeRe: ansiStyles.bgColor.closeRe
};
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
};
}
};
}
const proto = Object.defineProperties(() => {}, styles);
function build(_styles, _empty, key) {
const builder = function () {
return applyStyle.apply(builder, arguments);
};
builder._styles = _styles;
builder._empty = _empty;
const self = this;
Object.defineProperty(builder, 'level', {
enumerable: true,
get() {
return self.level;
},
set(level) {
self.level = level;
}
});
Object.defineProperty(builder, 'enabled', {
enumerable: true,
get() {
return self.enabled;
},
set(enabled) {
self.enabled = enabled;
}
});
// See below for fix regarding invisible grey/dim combination on Windows
builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey';
// `__proto__` is used because we must return a function, but there is
// no way to create a function with a different prototype
builder.__proto__ = proto; // eslint-disable-line no-proto
return builder;
}
function applyStyle() {
// Support varags, but simply cast to string in case there's only one arg
const args = arguments;
const argsLen = args.length;
let str = String(arguments[0]);
if (argsLen === 0) {
return '';
}
if (argsLen > 1) {
// Don't slice `arguments`, it prevents V8 optimizations
for (let a = 1; a < argsLen; a++) {
str += ' ' + args[a];
}
}
if (!this.enabled || this.level <= 0 || !str) {
return this._empty ? '' : str;
}
// Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
// see https://github.com/chalk/chalk/issues/58
// If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
const originalDim = ansiStyles.dim.open;
if (isSimpleWindowsTerm && this.hasGrey) {
ansiStyles.dim.open = '';
}
for (const code of this._styles.slice().reverse()) {
// Replace any instances already present with a re-opening code
// otherwise only the part of the string until said closing code
// will be colored, and the rest will simply be 'plain'.
str = code.open + str.replace(code.closeRe, code.open) + code.close;
// Close the styling before a linebreak and reopen
// after next line to fix a bleed issue on macOS
// https://github.com/chalk/chalk/pull/92
str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
}
// Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
ansiStyles.dim.open = originalDim;
return str;
}
function chalkTag(chalk, strings) {
if (!Array.isArray(strings)) {
// If chalk() was called by itself or with a string,
// return the string itself as a string.
return [].slice.call(arguments, 1).join(' ');
}
const args = [].slice.call(arguments, 2);
const parts = [strings.raw[0]];
for (let i = 1; i < strings.length; i++) {
parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
parts.push(String(strings.raw[i]));
}
return template(chalk, parts.join(''));
}
Object.defineProperties(Chalk.prototype, styles);
module.exports = Chalk(); // eslint-disable-line new-cap
module.exports.supportsColor = stdoutColor;
module.exports.default = module.exports; // For TypeScript
@@ -0,0 +1,93 @@
// @flow strict
type TemplateStringsArray = $ReadOnlyArray<string>;
export type Level = $Values<{
None: 0,
Basic: 1,
Ansi256: 2,
TrueColor: 3
}>;
export type ChalkOptions = {|
enabled?: boolean,
level?: Level
|};
export type ColorSupport = {|
level: Level,
hasBasic: boolean,
has256: boolean,
has16m: boolean
|};
export interface Chalk {
(...text: string[]): string,
(text: TemplateStringsArray, ...placeholders: string[]): string,
constructor(options?: ChalkOptions): Chalk,
enabled: boolean,
level: Level,
rgb(r: number, g: number, b: number): Chalk,
hsl(h: number, s: number, l: number): Chalk,
hsv(h: number, s: number, v: number): Chalk,
hwb(h: number, w: number, b: number): Chalk,
bgHex(color: string): Chalk,
bgKeyword(color: string): Chalk,
bgRgb(r: number, g: number, b: number): Chalk,
bgHsl(h: number, s: number, l: number): Chalk,
bgHsv(h: number, s: number, v: number): Chalk,
bgHwb(h: number, w: number, b: number): Chalk,
hex(color: string): Chalk,
keyword(color: string): Chalk,
+reset: Chalk,
+bold: Chalk,
+dim: Chalk,
+italic: Chalk,
+underline: Chalk,
+inverse: Chalk,
+hidden: Chalk,
+strikethrough: Chalk,
+visible: Chalk,
+black: Chalk,
+red: Chalk,
+green: Chalk,
+yellow: Chalk,
+blue: Chalk,
+magenta: Chalk,
+cyan: Chalk,
+white: Chalk,
+gray: Chalk,
+grey: Chalk,
+blackBright: Chalk,
+redBright: Chalk,
+greenBright: Chalk,
+yellowBright: Chalk,
+blueBright: Chalk,
+magentaBright: Chalk,
+cyanBright: Chalk,
+whiteBright: Chalk,
+bgBlack: Chalk,
+bgRed: Chalk,
+bgGreen: Chalk,
+bgYellow: Chalk,
+bgBlue: Chalk,
+bgMagenta: Chalk,
+bgCyan: Chalk,
+bgWhite: Chalk,
+bgBlackBright: Chalk,
+bgRedBright: Chalk,
+bgGreenBright: Chalk,
+bgYellowBright: Chalk,
+bgBlueBright: Chalk,
+bgMagentaBright: Chalk,
+bgCyanBright: Chalk,
+bgWhiteBrigh: Chalk,
supportsColor: ColorSupport
};
declare module.exports: Chalk;
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,71 @@
{
"name": "chalk",
"version": "2.4.2",
"description": "Terminal string styling done right",
"license": "MIT",
"repository": "chalk/chalk",
"engines": {
"node": ">=4"
},
"scripts": {
"test": "xo && tsc --project types && flow --max-warnings=0 && nyc ava",
"bench": "matcha benchmark.js",
"coveralls": "nyc report --reporter=text-lcov | coveralls"
},
"files": [
"index.js",
"templates.js",
"types/index.d.ts",
"index.js.flow"
],
"keywords": [
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"str",
"ansi",
"style",
"styles",
"tty",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"dependencies": {
"ansi-styles": "^3.2.1",
"escape-string-regexp": "^1.0.5",
"supports-color": "^5.3.0"
},
"devDependencies": {
"ava": "*",
"coveralls": "^3.0.0",
"execa": "^0.9.0",
"flow-bin": "^0.68.0",
"import-fresh": "^2.0.0",
"matcha": "^0.7.0",
"nyc": "^11.0.2",
"resolve-from": "^4.0.0",
"typescript": "^2.5.3",
"xo": "*"
},
"types": "types/index.d.ts",
"xo": {
"envs": [
"node",
"mocha"
],
"ignores": [
"test/_flow.js"
]
}
}
@@ -0,0 +1,314 @@
<h1 align="center">
<br>
<br>
<img width="320" src="media/logo.svg" alt="Chalk">
<br>
<br>
<br>
</h1>
> Terminal string styling done right
[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) [![Mentioned in Awesome Node.js](https://awesome.re/mentioned-badge.svg)](https://github.com/sindresorhus/awesome-nodejs)
### [See what's new in Chalk 2](https://github.com/chalk/chalk/releases/tag/v2.0.0)
<img src="https://cdn.rawgit.com/chalk/ansi-styles/8261697c95bf34b6c7767e2cbe9941a851d59385/screenshot.svg" alt="" width="900">
## Highlights
- Expressive API
- Highly performant
- Ability to nest styles
- [256/Truecolor color support](#256-and-truecolor-color-support)
- Auto-detects color support
- Doesn't extend `String.prototype`
- Clean and focused
- Actively maintained
- [Used by ~23,000 packages](https://www.npmjs.com/browse/depended/chalk) as of December 31, 2017
## Install
```console
$ npm install chalk
```
<a href="https://www.patreon.com/sindresorhus">
<img src="https://c5.patreon.com/external/logo/become_a_patron_button@2x.png" width="160">
</a>
## Usage
```js
const chalk = require('chalk');
console.log(chalk.blue('Hello world!'));
```
Chalk comes with an easy to use composable API where you just chain and nest the styles you want.
```js
const chalk = require('chalk');
const log = console.log;
// Combine styled and normal strings
log(chalk.blue('Hello') + ' World' + chalk.red('!'));
// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold('Hello world!'));
// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
// Nest styles of the same type even (color, underline, background)
log(chalk.green(
'I am a green line ' +
chalk.blue.underline.bold('with a blue substring') +
' that becomes green again!'
));
// ES2015 template literal
log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);
// ES2015 tagged template literal
log(chalk`
CPU: {red ${cpu.totalPercent}%}
RAM: {green ${ram.used / ram.total * 100}%}
DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
`);
// Use RGB colors in terminal emulators that support it.
log(chalk.keyword('orange')('Yay for orange colored text!'));
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
log(chalk.hex('#DEADED').bold('Bold gray!'));
```
Easily define your own themes:
```js
const chalk = require('chalk');
const error = chalk.bold.red;
const warning = chalk.keyword('orange');
console.log(error('Error!'));
console.log(warning('Warning!'));
```
Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args):
```js
const name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
//=> 'Hello Sindre'
```
## API
### chalk.`<style>[.<style>...](string, [string...])`
Example: `chalk.red.bold.underline('Hello', 'world');`
Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
Multiple arguments will be separated by space.
### chalk.enabled
Color support is automatically detected, as is the level (see `chalk.level`). However, if you'd like to simply enable/disable Chalk, you can do so via the `.enabled` property.
Chalk is enabled by default unless explicitly disabled via the constructor or `chalk.level` is `0`.
If you need to change this in a reusable module, create a new instance:
```js
const ctx = new chalk.constructor({enabled: false});
```
### chalk.level
Color support is automatically detected, but you can override it by setting the `level` property. You should however only do this in your own code as it applies globally to all Chalk consumers.
If you need to change this in a reusable module, create a new instance:
```js
const ctx = new chalk.constructor({level: 0});
```
Levels are as follows:
0. All colors disabled
1. Basic color support (16 colors)
2. 256 color support
3. Truecolor support (16 million colors)
### chalk.supportsColor
Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, add the environment variable `FORCE_COLOR=1` to forcefully enable color or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.
Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
## Styles
### Modifiers
- `reset`
- `bold`
- `dim`
- `italic` *(Not widely supported)*
- `underline`
- `inverse`
- `hidden`
- `strikethrough` *(Not widely supported)*
- `visible` (Text is emitted only if enabled)
### Colors
- `black`
- `red`
- `green`
- `yellow`
- `blue` *(On Windows the bright version is used since normal blue is illegible)*
- `magenta`
- `cyan`
- `white`
- `gray` ("bright black")
- `redBright`
- `greenBright`
- `yellowBright`
- `blueBright`
- `magentaBright`
- `cyanBright`
- `whiteBright`
### Background colors
- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
- `bgBlackBright`
- `bgRedBright`
- `bgGreenBright`
- `bgYellowBright`
- `bgBlueBright`
- `bgMagentaBright`
- `bgCyanBright`
- `bgWhiteBright`
## Tagged template literal
Chalk can be used as a [tagged template literal](http://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals).
```js
const chalk = require('chalk');
const miles = 18;
const calculateFeet = miles => miles * 5280;
console.log(chalk`
There are {bold 5280 feet} in a mile.
In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}.
`);
```
Blocks are delimited by an opening curly brace (`{`), a style, some content, and a closing curly brace (`}`).
Template styles are chained exactly like normal Chalk styles. The following two statements are equivalent:
```js
console.log(chalk.bold.rgb(10, 100, 200)('Hello!'));
console.log(chalk`{bold.rgb(10,100,200) Hello!}`);
```
Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain spaces between parameters.
All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped.
## 256 and Truecolor color support
Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728) (16 million colors) on supported terminal apps.
Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying `{level: n}` as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red).
Examples:
- `chalk.hex('#DEADED').underline('Hello, world!')`
- `chalk.keyword('orange')('Some orange text')`
- `chalk.rgb(15, 100, 204).inverse('Hello!')`
Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `keyword` for foreground colors and `bgKeyword` for background colors).
- `chalk.bgHex('#DEADED').underline('Hello, world!')`
- `chalk.bgKeyword('orange')('Some orange text')`
- `chalk.bgRgb(15, 100, 204).inverse('Hello!')`
The following color models can be used:
- [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')`
- [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')`
- [`keyword`](https://www.w3.org/wiki/CSS/Properties/color/keywords) (CSS keywords) - Example: `chalk.keyword('orange').bold('Orange!')`
- [`hsl`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 100, 50).bold('Orange!')`
- [`hsv`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsv(32, 100, 100).bold('Orange!')`
- [`hwb`](https://en.wikipedia.org/wiki/HWB_color_model) - Example: `chalk.hwb(32, 0, 50).bold('Orange!')`
- `ansi16`
- `ansi256`
## Windows
If you're on Windows, do yourself a favor and use [`cmder`](http://cmder.net/) instead of `cmd.exe`.
## Origin story
[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68) and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative.
## Related
- [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
- [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal
- [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color
- [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Strip ANSI escape codes from a stream
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
- [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes
- [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models
- [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal
- [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to strings
- [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings
- [terminal-link](https://github.com/sindresorhus/terminal-link) - Create clickable links in the terminal
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)
## License
MIT
@@ -0,0 +1,128 @@
'use strict';
const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
const ESCAPES = new Map([
['n', '\n'],
['r', '\r'],
['t', '\t'],
['b', '\b'],
['f', '\f'],
['v', '\v'],
['0', '\0'],
['\\', '\\'],
['e', '\u001B'],
['a', '\u0007']
]);
function unescape(c) {
if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
return String.fromCharCode(parseInt(c.slice(1), 16));
}
return ESCAPES.get(c) || c;
}
function parseArguments(name, args) {
const results = [];
const chunks = args.trim().split(/\s*,\s*/g);
let matches;
for (const chunk of chunks) {
if (!isNaN(chunk)) {
results.push(Number(chunk));
} else if ((matches = chunk.match(STRING_REGEX))) {
results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));
} else {
throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
}
}
return results;
}
function parseStyle(style) {
STYLE_REGEX.lastIndex = 0;
const results = [];
let matches;
while ((matches = STYLE_REGEX.exec(style)) !== null) {
const name = matches[1];
if (matches[2]) {
const args = parseArguments(name, matches[2]);
results.push([name].concat(args));
} else {
results.push([name]);
}
}
return results;
}
function buildStyle(chalk, styles) {
const enabled = {};
for (const layer of styles) {
for (const style of layer.styles) {
enabled[style[0]] = layer.inverse ? null : style.slice(1);
}
}
let current = chalk;
for (const styleName of Object.keys(enabled)) {
if (Array.isArray(enabled[styleName])) {
if (!(styleName in current)) {
throw new Error(`Unknown Chalk style: ${styleName}`);
}
if (enabled[styleName].length > 0) {
current = current[styleName].apply(current, enabled[styleName]);
} else {
current = current[styleName];
}
}
}
return current;
}
module.exports = (chalk, tmp) => {
const styles = [];
const chunks = [];
let chunk = [];
// eslint-disable-next-line max-params
tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
if (escapeChar) {
chunk.push(unescape(escapeChar));
} else if (style) {
const str = chunk.join('');
chunk = [];
chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
styles.push({inverse, styles: parseStyle(style)});
} else if (close) {
if (styles.length === 0) {
throw new Error('Found extraneous } in Chalk template literal');
}
chunks.push(buildStyle(chalk, styles)(chunk.join('')));
chunk = [];
styles.pop();
} else {
chunk.push(chr);
}
});
chunks.push(chunk.join(''));
if (styles.length > 0) {
const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
throw new Error(errMsg);
}
return chunks.join('');
};
@@ -0,0 +1,21 @@
Copyright (c) 2011-2016 Heather Arthur <fayearthur@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,868 @@
/* MIT license */
var cssKeywords = require('color-name');
// NOTE: conversions should only return primitive values (i.e. arrays, or
// values that give correct `typeof` results).
// do not use box values types (i.e. Number(), String(), etc.)
var reverseKeywords = {};
for (var key in cssKeywords) {
if (cssKeywords.hasOwnProperty(key)) {
reverseKeywords[cssKeywords[key]] = key;
}
}
var convert = module.exports = {
rgb: {channels: 3, labels: 'rgb'},
hsl: {channels: 3, labels: 'hsl'},
hsv: {channels: 3, labels: 'hsv'},
hwb: {channels: 3, labels: 'hwb'},
cmyk: {channels: 4, labels: 'cmyk'},
xyz: {channels: 3, labels: 'xyz'},
lab: {channels: 3, labels: 'lab'},
lch: {channels: 3, labels: 'lch'},
hex: {channels: 1, labels: ['hex']},
keyword: {channels: 1, labels: ['keyword']},
ansi16: {channels: 1, labels: ['ansi16']},
ansi256: {channels: 1, labels: ['ansi256']},
hcg: {channels: 3, labels: ['h', 'c', 'g']},
apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
gray: {channels: 1, labels: ['gray']}
};
// hide .channels and .labels properties
for (var model in convert) {
if (convert.hasOwnProperty(model)) {
if (!('channels' in convert[model])) {
throw new Error('missing channels property: ' + model);
}
if (!('labels' in convert[model])) {
throw new Error('missing channel labels property: ' + model);
}
if (convert[model].labels.length !== convert[model].channels) {
throw new Error('channel and label counts mismatch: ' + model);
}
var channels = convert[model].channels;
var labels = convert[model].labels;
delete convert[model].channels;
delete convert[model].labels;
Object.defineProperty(convert[model], 'channels', {value: channels});
Object.defineProperty(convert[model], 'labels', {value: labels});
}
}
convert.rgb.hsl = function (rgb) {
var r = rgb[0] / 255;
var g = rgb[1] / 255;
var b = rgb[2] / 255;
var min = Math.min(r, g, b);
var max = Math.max(r, g, b);
var delta = max - min;
var h;
var s;
var l;
if (max === min) {
h = 0;
} else if (r === max) {
h = (g - b) / delta;
} else if (g === max) {
h = 2 + (b - r) / delta;
} else if (b === max) {
h = 4 + (r - g) / delta;
}
h = Math.min(h * 60, 360);
if (h < 0) {
h += 360;
}
l = (min + max) / 2;
if (max === min) {
s = 0;
} else if (l <= 0.5) {
s = delta / (max + min);
} else {
s = delta / (2 - max - min);
}
return [h, s * 100, l * 100];
};
convert.rgb.hsv = function (rgb) {
var rdif;
var gdif;
var bdif;
var h;
var s;
var r = rgb[0] / 255;
var g = rgb[1] / 255;
var b = rgb[2] / 255;
var v = Math.max(r, g, b);
var diff = v - Math.min(r, g, b);
var diffc = function (c) {
return (v - c) / 6 / diff + 1 / 2;
};
if (diff === 0) {
h = s = 0;
} else {
s = diff / v;
rdif = diffc(r);
gdif = diffc(g);
bdif = diffc(b);
if (r === v) {
h = bdif - gdif;
} else if (g === v) {
h = (1 / 3) + rdif - bdif;
} else if (b === v) {
h = (2 / 3) + gdif - rdif;
}
if (h < 0) {
h += 1;
} else if (h > 1) {
h -= 1;
}
}
return [
h * 360,
s * 100,
v * 100
];
};
convert.rgb.hwb = function (rgb) {
var r = rgb[0];
var g = rgb[1];
var b = rgb[2];
var h = convert.rgb.hsl(rgb)[0];
var w = 1 / 255 * Math.min(r, Math.min(g, b));
b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
return [h, w * 100, b * 100];
};
convert.rgb.cmyk = function (rgb) {
var r = rgb[0] / 255;
var g = rgb[1] / 255;
var b = rgb[2] / 255;
var c;
var m;
var y;
var k;
k = Math.min(1 - r, 1 - g, 1 - b);
c = (1 - r - k) / (1 - k) || 0;
m = (1 - g - k) / (1 - k) || 0;
y = (1 - b - k) / (1 - k) || 0;
return [c * 100, m * 100, y * 100, k * 100];
};
/**
* See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
* */
function comparativeDistance(x, y) {
return (
Math.pow(x[0] - y[0], 2) +
Math.pow(x[1] - y[1], 2) +
Math.pow(x[2] - y[2], 2)
);
}
convert.rgb.keyword = function (rgb) {
var reversed = reverseKeywords[rgb];
if (reversed) {
return reversed;
}
var currentClosestDistance = Infinity;
var currentClosestKeyword;
for (var keyword in cssKeywords) {
if (cssKeywords.hasOwnProperty(keyword)) {
var value = cssKeywords[keyword];
// Compute comparative distance
var distance = comparativeDistance(rgb, value);
// Check if its less, if so set as closest
if (distance < currentClosestDistance) {
currentClosestDistance = distance;
currentClosestKeyword = keyword;
}
}
}
return currentClosestKeyword;
};
convert.keyword.rgb = function (keyword) {
return cssKeywords[keyword];
};
convert.rgb.xyz = function (rgb) {
var r = rgb[0] / 255;
var g = rgb[1] / 255;
var b = rgb[2] / 255;
// assume sRGB
r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
return [x * 100, y * 100, z * 100];
};
convert.rgb.lab = function (rgb) {
var xyz = convert.rgb.xyz(rgb);
var x = xyz[0];
var y = xyz[1];
var z = xyz[2];
var l;
var a;
var b;
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
l = (116 * y) - 16;
a = 500 * (x - y);
b = 200 * (y - z);
return [l, a, b];
};
convert.hsl.rgb = function (hsl) {
var h = hsl[0] / 360;
var s = hsl[1] / 100;
var l = hsl[2] / 100;
var t1;
var t2;
var t3;
var rgb;
var val;
if (s === 0) {
val = l * 255;
return [val, val, val];
}
if (l < 0.5) {
t2 = l * (1 + s);
} else {
t2 = l + s - l * s;
}
t1 = 2 * l - t2;
rgb = [0, 0, 0];
for (var i = 0; i < 3; i++) {
t3 = h + 1 / 3 * -(i - 1);
if (t3 < 0) {
t3++;
}
if (t3 > 1) {
t3--;
}
if (6 * t3 < 1) {
val = t1 + (t2 - t1) * 6 * t3;
} else if (2 * t3 < 1) {
val = t2;
} else if (3 * t3 < 2) {
val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
} else {
val = t1;
}
rgb[i] = val * 255;
}
return rgb;
};
convert.hsl.hsv = function (hsl) {
var h = hsl[0];
var s = hsl[1] / 100;
var l = hsl[2] / 100;
var smin = s;
var lmin = Math.max(l, 0.01);
var sv;
var v;
l *= 2;
s *= (l <= 1) ? l : 2 - l;
smin *= lmin <= 1 ? lmin : 2 - lmin;
v = (l + s) / 2;
sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
return [h, sv * 100, v * 100];
};
convert.hsv.rgb = function (hsv) {
var h = hsv[0] / 60;
var s = hsv[1] / 100;
var v = hsv[2] / 100;
var hi = Math.floor(h) % 6;
var f = h - Math.floor(h);
var p = 255 * v * (1 - s);
var q = 255 * v * (1 - (s * f));
var t = 255 * v * (1 - (s * (1 - f)));
v *= 255;
switch (hi) {
case 0:
return [v, t, p];
case 1:
return [q, v, p];
case 2:
return [p, v, t];
case 3:
return [p, q, v];
case 4:
return [t, p, v];
case 5:
return [v, p, q];
}
};
convert.hsv.hsl = function (hsv) {
var h = hsv[0];
var s = hsv[1] / 100;
var v = hsv[2] / 100;
var vmin = Math.max(v, 0.01);
var lmin;
var sl;
var l;
l = (2 - s) * v;
lmin = (2 - s) * vmin;
sl = s * vmin;
sl /= (lmin <= 1) ? lmin : 2 - lmin;
sl = sl || 0;
l /= 2;
return [h, sl * 100, l * 100];
};
// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
convert.hwb.rgb = function (hwb) {
var h = hwb[0] / 360;
var wh = hwb[1] / 100;
var bl = hwb[2] / 100;
var ratio = wh + bl;
var i;
var v;
var f;
var n;
// wh + bl cant be > 1
if (ratio > 1) {
wh /= ratio;
bl /= ratio;
}
i = Math.floor(6 * h);
v = 1 - bl;
f = 6 * h - i;
if ((i & 0x01) !== 0) {
f = 1 - f;
}
n = wh + f * (v - wh); // linear interpolation
var r;
var g;
var b;
switch (i) {
default:
case 6:
case 0: r = v; g = n; b = wh; break;
case 1: r = n; g = v; b = wh; break;
case 2: r = wh; g = v; b = n; break;
case 3: r = wh; g = n; b = v; break;
case 4: r = n; g = wh; b = v; break;
case 5: r = v; g = wh; b = n; break;
}
return [r * 255, g * 255, b * 255];
};
convert.cmyk.rgb = function (cmyk) {
var c = cmyk[0] / 100;
var m = cmyk[1] / 100;
var y = cmyk[2] / 100;
var k = cmyk[3] / 100;
var r;
var g;
var b;
r = 1 - Math.min(1, c * (1 - k) + k);
g = 1 - Math.min(1, m * (1 - k) + k);
b = 1 - Math.min(1, y * (1 - k) + k);
return [r * 255, g * 255, b * 255];
};
convert.xyz.rgb = function (xyz) {
var x = xyz[0] / 100;
var y = xyz[1] / 100;
var z = xyz[2] / 100;
var r;
var g;
var b;
r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
// assume sRGB
r = r > 0.0031308
? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
: r * 12.92;
g = g > 0.0031308
? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
: g * 12.92;
b = b > 0.0031308
? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
: b * 12.92;
r = Math.min(Math.max(0, r), 1);
g = Math.min(Math.max(0, g), 1);
b = Math.min(Math.max(0, b), 1);
return [r * 255, g * 255, b * 255];
};
convert.xyz.lab = function (xyz) {
var x = xyz[0];
var y = xyz[1];
var z = xyz[2];
var l;
var a;
var b;
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
l = (116 * y) - 16;
a = 500 * (x - y);
b = 200 * (y - z);
return [l, a, b];
};
convert.lab.xyz = function (lab) {
var l = lab[0];
var a = lab[1];
var b = lab[2];
var x;
var y;
var z;
y = (l + 16) / 116;
x = a / 500 + y;
z = y - b / 200;
var y2 = Math.pow(y, 3);
var x2 = Math.pow(x, 3);
var z2 = Math.pow(z, 3);
y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
x *= 95.047;
y *= 100;
z *= 108.883;
return [x, y, z];
};
convert.lab.lch = function (lab) {
var l = lab[0];
var a = lab[1];
var b = lab[2];
var hr;
var h;
var c;
hr = Math.atan2(b, a);
h = hr * 360 / 2 / Math.PI;
if (h < 0) {
h += 360;
}
c = Math.sqrt(a * a + b * b);
return [l, c, h];
};
convert.lch.lab = function (lch) {
var l = lch[0];
var c = lch[1];
var h = lch[2];
var a;
var b;
var hr;
hr = h / 360 * 2 * Math.PI;
a = c * Math.cos(hr);
b = c * Math.sin(hr);
return [l, a, b];
};
convert.rgb.ansi16 = function (args) {
var r = args[0];
var g = args[1];
var b = args[2];
var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
value = Math.round(value / 50);
if (value === 0) {
return 30;
}
var ansi = 30
+ ((Math.round(b / 255) << 2)
| (Math.round(g / 255) << 1)
| Math.round(r / 255));
if (value === 2) {
ansi += 60;
}
return ansi;
};
convert.hsv.ansi16 = function (args) {
// optimization here; we already know the value and don't need to get
// it converted for us.
return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
};
convert.rgb.ansi256 = function (args) {
var r = args[0];
var g = args[1];
var b = args[2];
// we use the extended greyscale palette here, with the exception of
// black and white. normal palette only has 4 greyscale shades.
if (r === g && g === b) {
if (r < 8) {
return 16;
}
if (r > 248) {
return 231;
}
return Math.round(((r - 8) / 247) * 24) + 232;
}
var ansi = 16
+ (36 * Math.round(r / 255 * 5))
+ (6 * Math.round(g / 255 * 5))
+ Math.round(b / 255 * 5);
return ansi;
};
convert.ansi16.rgb = function (args) {
var color = args % 10;
// handle greyscale
if (color === 0 || color === 7) {
if (args > 50) {
color += 3.5;
}
color = color / 10.5 * 255;
return [color, color, color];
}
var mult = (~~(args > 50) + 1) * 0.5;
var r = ((color & 1) * mult) * 255;
var g = (((color >> 1) & 1) * mult) * 255;
var b = (((color >> 2) & 1) * mult) * 255;
return [r, g, b];
};
convert.ansi256.rgb = function (args) {
// handle greyscale
if (args >= 232) {
var c = (args - 232) * 10 + 8;
return [c, c, c];
}
args -= 16;
var rem;
var r = Math.floor(args / 36) / 5 * 255;
var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
var b = (rem % 6) / 5 * 255;
return [r, g, b];
};
convert.rgb.hex = function (args) {
var integer = ((Math.round(args[0]) & 0xFF) << 16)
+ ((Math.round(args[1]) & 0xFF) << 8)
+ (Math.round(args[2]) & 0xFF);
var string = integer.toString(16).toUpperCase();
return '000000'.substring(string.length) + string;
};
convert.hex.rgb = function (args) {
var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
if (!match) {
return [0, 0, 0];
}
var colorString = match[0];
if (match[0].length === 3) {
colorString = colorString.split('').map(function (char) {
return char + char;
}).join('');
}
var integer = parseInt(colorString, 16);
var r = (integer >> 16) & 0xFF;
var g = (integer >> 8) & 0xFF;
var b = integer & 0xFF;
return [r, g, b];
};
convert.rgb.hcg = function (rgb) {
var r = rgb[0] / 255;
var g = rgb[1] / 255;
var b = rgb[2] / 255;
var max = Math.max(Math.max(r, g), b);
var min = Math.min(Math.min(r, g), b);
var chroma = (max - min);
var grayscale;
var hue;
if (chroma < 1) {
grayscale = min / (1 - chroma);
} else {
grayscale = 0;
}
if (chroma <= 0) {
hue = 0;
} else
if (max === r) {
hue = ((g - b) / chroma) % 6;
} else
if (max === g) {
hue = 2 + (b - r) / chroma;
} else {
hue = 4 + (r - g) / chroma + 4;
}
hue /= 6;
hue %= 1;
return [hue * 360, chroma * 100, grayscale * 100];
};
convert.hsl.hcg = function (hsl) {
var s = hsl[1] / 100;
var l = hsl[2] / 100;
var c = 1;
var f = 0;
if (l < 0.5) {
c = 2.0 * s * l;
} else {
c = 2.0 * s * (1.0 - l);
}
if (c < 1.0) {
f = (l - 0.5 * c) / (1.0 - c);
}
return [hsl[0], c * 100, f * 100];
};
convert.hsv.hcg = function (hsv) {
var s = hsv[1] / 100;
var v = hsv[2] / 100;
var c = s * v;
var f = 0;
if (c < 1.0) {
f = (v - c) / (1 - c);
}
return [hsv[0], c * 100, f * 100];
};
convert.hcg.rgb = function (hcg) {
var h = hcg[0] / 360;
var c = hcg[1] / 100;
var g = hcg[2] / 100;
if (c === 0.0) {
return [g * 255, g * 255, g * 255];
}
var pure = [0, 0, 0];
var hi = (h % 1) * 6;
var v = hi % 1;
var w = 1 - v;
var mg = 0;
switch (Math.floor(hi)) {
case 0:
pure[0] = 1; pure[1] = v; pure[2] = 0; break;
case 1:
pure[0] = w; pure[1] = 1; pure[2] = 0; break;
case 2:
pure[0] = 0; pure[1] = 1; pure[2] = v; break;
case 3:
pure[0] = 0; pure[1] = w; pure[2] = 1; break;
case 4:
pure[0] = v; pure[1] = 0; pure[2] = 1; break;
default:
pure[0] = 1; pure[1] = 0; pure[2] = w;
}
mg = (1.0 - c) * g;
return [
(c * pure[0] + mg) * 255,
(c * pure[1] + mg) * 255,
(c * pure[2] + mg) * 255
];
};
convert.hcg.hsv = function (hcg) {
var c = hcg[1] / 100;
var g = hcg[2] / 100;
var v = c + g * (1.0 - c);
var f = 0;
if (v > 0.0) {
f = c / v;
}
return [hcg[0], f * 100, v * 100];
};
convert.hcg.hsl = function (hcg) {
var c = hcg[1] / 100;
var g = hcg[2] / 100;
var l = g * (1.0 - c) + 0.5 * c;
var s = 0;
if (l > 0.0 && l < 0.5) {
s = c / (2 * l);
} else
if (l >= 0.5 && l < 1.0) {
s = c / (2 * (1 - l));
}
return [hcg[0], s * 100, l * 100];
};
convert.hcg.hwb = function (hcg) {
var c = hcg[1] / 100;
var g = hcg[2] / 100;
var v = c + g * (1.0 - c);
return [hcg[0], (v - c) * 100, (1 - v) * 100];
};
convert.hwb.hcg = function (hwb) {
var w = hwb[1] / 100;
var b = hwb[2] / 100;
var v = 1 - b;
var c = v - w;
var g = 0;
if (c < 1) {
g = (v - c) / (1 - c);
}
return [hwb[0], c * 100, g * 100];
};
convert.apple.rgb = function (apple) {
return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
};
convert.rgb.apple = function (rgb) {
return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
};
convert.gray.rgb = function (args) {
return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
};
convert.gray.hsl = convert.gray.hsv = function (args) {
return [0, 0, args[0]];
};
convert.gray.hwb = function (gray) {
return [0, 100, gray[0]];
};
convert.gray.cmyk = function (gray) {
return [0, 0, 0, gray[0]];
};
convert.gray.lab = function (gray) {
return [gray[0], 0, 0];
};
convert.gray.hex = function (gray) {
var val = Math.round(gray[0] / 100 * 255) & 0xFF;
var integer = (val << 16) + (val << 8) + val;
var string = integer.toString(16).toUpperCase();
return '000000'.substring(string.length) + string;
};
convert.rgb.gray = function (rgb) {
var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
return [val / 255 * 100];
};
@@ -0,0 +1,78 @@
var conversions = require('./conversions');
var route = require('./route');
var convert = {};
var models = Object.keys(conversions);
function wrapRaw(fn) {
var wrappedFn = function (args) {
if (args === undefined || args === null) {
return args;
}
if (arguments.length > 1) {
args = Array.prototype.slice.call(arguments);
}
return fn(args);
};
// preserve .conversion property if there is one
if ('conversion' in fn) {
wrappedFn.conversion = fn.conversion;
}
return wrappedFn;
}
function wrapRounded(fn) {
var wrappedFn = function (args) {
if (args === undefined || args === null) {
return args;
}
if (arguments.length > 1) {
args = Array.prototype.slice.call(arguments);
}
var result = fn(args);
// we're assuming the result is an array here.
// see notice in conversions.js; don't use box types
// in conversion functions.
if (typeof result === 'object') {
for (var len = result.length, i = 0; i < len; i++) {
result[i] = Math.round(result[i]);
}
}
return result;
};
// preserve .conversion property if there is one
if ('conversion' in fn) {
wrappedFn.conversion = fn.conversion;
}
return wrappedFn;
}
models.forEach(function (fromModel) {
convert[fromModel] = {};
Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
var routes = route(fromModel);
var routeModels = Object.keys(routes);
routeModels.forEach(function (toModel) {
var fn = routes[toModel];
convert[fromModel][toModel] = wrapRounded(fn);
convert[fromModel][toModel].raw = wrapRaw(fn);
});
});
module.exports = convert;
@@ -0,0 +1,46 @@
{
"name": "color-convert",
"description": "Plain color conversion functions",
"version": "1.9.3",
"author": "Heather Arthur <fayearthur@gmail.com>",
"license": "MIT",
"repository": "Qix-/color-convert",
"scripts": {
"pretest": "xo",
"test": "node test/basic.js"
},
"keywords": [
"color",
"colour",
"convert",
"converter",
"conversion",
"rgb",
"hsl",
"hsv",
"hwb",
"cmyk",
"ansi",
"ansi16"
],
"files": [
"index.js",
"conversions.js",
"css-keywords.js",
"route.js"
],
"xo": {
"rules": {
"default-case": 0,
"no-inline-comments": 0,
"operator-linebreak": 0
}
},
"devDependencies": {
"chalk": "1.1.1",
"xo": "0.11.2"
},
"dependencies": {
"color-name": "1.1.3"
}
}
@@ -0,0 +1,97 @@
var conversions = require('./conversions');
/*
this function routes a model to all other models.
all functions that are routed have a property `.conversion` attached
to the returned synthetic function. This property is an array
of strings, each with the steps in between the 'from' and 'to'
color models (inclusive).
conversions that are not possible simply are not included.
*/
function buildGraph() {
var graph = {};
// https://jsperf.com/object-keys-vs-for-in-with-closure/3
var models = Object.keys(conversions);
for (var len = models.length, i = 0; i < len; i++) {
graph[models[i]] = {
// http://jsperf.com/1-vs-infinity
// micro-opt, but this is simple.
distance: -1,
parent: null
};
}
return graph;
}
// https://en.wikipedia.org/wiki/Breadth-first_search
function deriveBFS(fromModel) {
var graph = buildGraph();
var queue = [fromModel]; // unshift -> queue -> pop
graph[fromModel].distance = 0;
while (queue.length) {
var current = queue.pop();
var adjacents = Object.keys(conversions[current]);
for (var len = adjacents.length, i = 0; i < len; i++) {
var adjacent = adjacents[i];
var node = graph[adjacent];
if (node.distance === -1) {
node.distance = graph[current].distance + 1;
node.parent = current;
queue.unshift(adjacent);
}
}
}
return graph;
}
function link(from, to) {
return function (args) {
return to(from(args));
};
}
function wrapConversion(toModel, graph) {
var path = [graph[toModel].parent, toModel];
var fn = conversions[graph[toModel].parent][toModel];
var cur = graph[toModel].parent;
while (graph[cur].parent) {
path.unshift(graph[cur].parent);
fn = link(conversions[graph[cur].parent][cur], fn);
cur = graph[cur].parent;
}
fn.conversion = path;
return fn;
}
module.exports = function (fromModel) {
var graph = deriveBFS(fromModel);
var conversion = {};
var models = Object.keys(graph);
for (var len = models.length, i = 0; i < len; i++) {
var toModel = models[i];
var node = graph[toModel];
if (node.parent === null) {
// no possible conversion, or this node is the source model.
continue;
}
conversion[toModel] = wrapConversion(toModel, graph);
}
return conversion;
};
@@ -0,0 +1,8 @@
The MIT License (MIT)
Copyright (c) 2015 Dmitry Ivanov
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,152 @@
'use strict'
module.exports = {
"aliceblue": [240, 248, 255],
"antiquewhite": [250, 235, 215],
"aqua": [0, 255, 255],
"aquamarine": [127, 255, 212],
"azure": [240, 255, 255],
"beige": [245, 245, 220],
"bisque": [255, 228, 196],
"black": [0, 0, 0],
"blanchedalmond": [255, 235, 205],
"blue": [0, 0, 255],
"blueviolet": [138, 43, 226],
"brown": [165, 42, 42],
"burlywood": [222, 184, 135],
"cadetblue": [95, 158, 160],
"chartreuse": [127, 255, 0],
"chocolate": [210, 105, 30],
"coral": [255, 127, 80],
"cornflowerblue": [100, 149, 237],
"cornsilk": [255, 248, 220],
"crimson": [220, 20, 60],
"cyan": [0, 255, 255],
"darkblue": [0, 0, 139],
"darkcyan": [0, 139, 139],
"darkgoldenrod": [184, 134, 11],
"darkgray": [169, 169, 169],
"darkgreen": [0, 100, 0],
"darkgrey": [169, 169, 169],
"darkkhaki": [189, 183, 107],
"darkmagenta": [139, 0, 139],
"darkolivegreen": [85, 107, 47],
"darkorange": [255, 140, 0],
"darkorchid": [153, 50, 204],
"darkred": [139, 0, 0],
"darksalmon": [233, 150, 122],
"darkseagreen": [143, 188, 143],
"darkslateblue": [72, 61, 139],
"darkslategray": [47, 79, 79],
"darkslategrey": [47, 79, 79],
"darkturquoise": [0, 206, 209],
"darkviolet": [148, 0, 211],
"deeppink": [255, 20, 147],
"deepskyblue": [0, 191, 255],
"dimgray": [105, 105, 105],
"dimgrey": [105, 105, 105],
"dodgerblue": [30, 144, 255],
"firebrick": [178, 34, 34],
"floralwhite": [255, 250, 240],
"forestgreen": [34, 139, 34],
"fuchsia": [255, 0, 255],
"gainsboro": [220, 220, 220],
"ghostwhite": [248, 248, 255],
"gold": [255, 215, 0],
"goldenrod": [218, 165, 32],
"gray": [128, 128, 128],
"green": [0, 128, 0],
"greenyellow": [173, 255, 47],
"grey": [128, 128, 128],
"honeydew": [240, 255, 240],
"hotpink": [255, 105, 180],
"indianred": [205, 92, 92],
"indigo": [75, 0, 130],
"ivory": [255, 255, 240],
"khaki": [240, 230, 140],
"lavender": [230, 230, 250],
"lavenderblush": [255, 240, 245],
"lawngreen": [124, 252, 0],
"lemonchiffon": [255, 250, 205],
"lightblue": [173, 216, 230],
"lightcoral": [240, 128, 128],
"lightcyan": [224, 255, 255],
"lightgoldenrodyellow": [250, 250, 210],
"lightgray": [211, 211, 211],
"lightgreen": [144, 238, 144],
"lightgrey": [211, 211, 211],
"lightpink": [255, 182, 193],
"lightsalmon": [255, 160, 122],
"lightseagreen": [32, 178, 170],
"lightskyblue": [135, 206, 250],
"lightslategray": [119, 136, 153],
"lightslategrey": [119, 136, 153],
"lightsteelblue": [176, 196, 222],
"lightyellow": [255, 255, 224],
"lime": [0, 255, 0],
"limegreen": [50, 205, 50],
"linen": [250, 240, 230],
"magenta": [255, 0, 255],
"maroon": [128, 0, 0],
"mediumaquamarine": [102, 205, 170],
"mediumblue": [0, 0, 205],
"mediumorchid": [186, 85, 211],
"mediumpurple": [147, 112, 219],
"mediumseagreen": [60, 179, 113],
"mediumslateblue": [123, 104, 238],
"mediumspringgreen": [0, 250, 154],
"mediumturquoise": [72, 209, 204],
"mediumvioletred": [199, 21, 133],
"midnightblue": [25, 25, 112],
"mintcream": [245, 255, 250],
"mistyrose": [255, 228, 225],
"moccasin": [255, 228, 181],
"navajowhite": [255, 222, 173],
"navy": [0, 0, 128],
"oldlace": [253, 245, 230],
"olive": [128, 128, 0],
"olivedrab": [107, 142, 35],
"orange": [255, 165, 0],
"orangered": [255, 69, 0],
"orchid": [218, 112, 214],
"palegoldenrod": [238, 232, 170],
"palegreen": [152, 251, 152],
"paleturquoise": [175, 238, 238],
"palevioletred": [219, 112, 147],
"papayawhip": [255, 239, 213],
"peachpuff": [255, 218, 185],
"peru": [205, 133, 63],
"pink": [255, 192, 203],
"plum": [221, 160, 221],
"powderblue": [176, 224, 230],
"purple": [128, 0, 128],
"rebeccapurple": [102, 51, 153],
"red": [255, 0, 0],
"rosybrown": [188, 143, 143],
"royalblue": [65, 105, 225],
"saddlebrown": [139, 69, 19],
"salmon": [250, 128, 114],
"sandybrown": [244, 164, 96],
"seagreen": [46, 139, 87],
"seashell": [255, 245, 238],
"sienna": [160, 82, 45],
"silver": [192, 192, 192],
"skyblue": [135, 206, 235],
"slateblue": [106, 90, 205],
"slategray": [112, 128, 144],
"slategrey": [112, 128, 144],
"snow": [255, 250, 250],
"springgreen": [0, 255, 127],
"steelblue": [70, 130, 180],
"tan": [210, 180, 140],
"teal": [0, 128, 128],
"thistle": [216, 191, 216],
"tomato": [255, 99, 71],
"turquoise": [64, 224, 208],
"violet": [238, 130, 238],
"wheat": [245, 222, 179],
"white": [255, 255, 255],
"whitesmoke": [245, 245, 245],
"yellow": [255, 255, 0],
"yellowgreen": [154, 205, 50]
};
@@ -0,0 +1,25 @@
{
"name": "color-name",
"version": "1.1.3",
"description": "A list of color names and its values",
"main": "index.js",
"scripts": {
"test": "node test.js"
},
"repository": {
"type": "git",
"url": "git@github.com:dfcreative/color-name.git"
},
"keywords": [
"color-name",
"color",
"color-keyword",
"keyword"
],
"author": "DY <dfcreative@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/dfcreative/color-name/issues"
},
"homepage": "https://github.com/dfcreative/color-name"
}
@@ -0,0 +1,11 @@
'use strict';
var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
module.exports = function (str) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string');
}
return str.replace(matchOperatorsRe, '\\$&');
};
@@ -1,6 +1,6 @@
The MIT License
The MIT License (MIT)
Copyright (c) 2015 Rich Harris
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -0,0 +1,41 @@
{
"name": "escape-string-regexp",
"version": "1.0.5",
"description": "Escape RegExp special characters",
"license": "MIT",
"repository": "sindresorhus/escape-string-regexp",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"maintainers": [
"Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)",
"Joshua Boy Nicolai Appelman <joshua@jbna.nl> (jbna.nl)"
],
"engines": {
"node": ">=0.8.0"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js"
],
"keywords": [
"escape",
"regex",
"regexp",
"re",
"regular",
"expression",
"string",
"str",
"special",
"characters"
],
"devDependencies": {
"ava": "*",
"xo": "*"
}
}
@@ -0,0 +1,27 @@
# escape-string-regexp [![Build Status](https://travis-ci.org/sindresorhus/escape-string-regexp.svg?branch=master)](https://travis-ci.org/sindresorhus/escape-string-regexp)
> Escape RegExp special characters
## Install
```
$ npm install --save escape-string-regexp
```
## Usage
```js
const escapeStringRegexp = require('escape-string-regexp');
const escapedString = escapeStringRegexp('how much $ for a unicorn?');
//=> 'how much \$ for a unicorn\?'
new RegExp(escapedString);
```
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)
@@ -0,0 +1,8 @@
'use strict';
module.exports = (flag, argv) => {
argv = argv || process.argv;
const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
const pos = argv.indexOf(prefix + flag);
const terminatorPos = argv.indexOf('--');
return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
};
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,44 @@
{
"name": "has-flag",
"version": "3.0.0",
"description": "Check if argv has a specific flag",
"license": "MIT",
"repository": "sindresorhus/has-flag",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=4"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js"
],
"keywords": [
"has",
"check",
"detect",
"contains",
"find",
"flag",
"cli",
"command-line",
"argv",
"process",
"arg",
"args",
"argument",
"arguments",
"getopt",
"minimist",
"optimist"
],
"devDependencies": {
"ava": "*",
"xo": "*"
}
}
@@ -0,0 +1,70 @@
# has-flag [![Build Status](https://travis-ci.org/sindresorhus/has-flag.svg?branch=master)](https://travis-ci.org/sindresorhus/has-flag)
> Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag
Correctly stops looking after an `--` argument terminator.
## Install
```
$ npm install has-flag
```
## Usage
```js
// foo.js
const hasFlag = require('has-flag');
hasFlag('unicorn');
//=> true
hasFlag('--unicorn');
//=> true
hasFlag('f');
//=> true
hasFlag('-f');
//=> true
hasFlag('foo=bar');
//=> true
hasFlag('foo');
//=> false
hasFlag('rainbow');
//=> false
```
```
$ node foo.js -f --unicorn --foo=bar -- --rainbow
```
## API
### hasFlag(flag, [argv])
Returns a boolean for whether the flag exists.
#### flag
Type: `string`
CLI flag to look for. The `--` prefix is optional.
#### argv
Type: `string[]`<br>
Default: `process.argv`
CLI arguments.
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
@@ -0,0 +1,5 @@
'use strict';
module.exports = {
stdout: false,
stderr: false
};
@@ -0,0 +1,131 @@
'use strict';
const os = require('os');
const hasFlag = require('has-flag');
const env = process.env;
let forceColor;
if (hasFlag('no-color') ||
hasFlag('no-colors') ||
hasFlag('color=false')) {
forceColor = false;
} else if (hasFlag('color') ||
hasFlag('colors') ||
hasFlag('color=true') ||
hasFlag('color=always')) {
forceColor = true;
}
if ('FORCE_COLOR' in env) {
forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
}
function translateLevel(level) {
if (level === 0) {
return false;
}
return {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3
};
}
function supportsColor(stream) {
if (forceColor === false) {
return 0;
}
if (hasFlag('color=16m') ||
hasFlag('color=full') ||
hasFlag('color=truecolor')) {
return 3;
}
if (hasFlag('color=256')) {
return 2;
}
if (stream && !stream.isTTY && forceColor !== true) {
return 0;
}
const min = forceColor ? 1 : 0;
if (process.platform === 'win32') {
// Node.js 7.5.0 is the first version of Node.js to include a patch to
// libuv that enables 256 color output on Windows. Anything earlier and it
// won't work. However, here we target Node.js 8 at minimum as it is an LTS
// release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
// release that supports 256 colors. Windows 10 build 14931 is the first release
// that supports 16m/TrueColor.
const osRelease = os.release().split('.');
if (
Number(process.versions.node.split('.')[0]) >= 8 &&
Number(osRelease[0]) >= 10 &&
Number(osRelease[2]) >= 10586
) {
return Number(osRelease[2]) >= 14931 ? 3 : 2;
}
return 1;
}
if ('CI' in env) {
if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
return 1;
}
return min;
}
if ('TEAMCITY_VERSION' in env) {
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
}
if (env.COLORTERM === 'truecolor') {
return 3;
}
if ('TERM_PROGRAM' in env) {
const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
switch (env.TERM_PROGRAM) {
case 'iTerm.app':
return version >= 3 ? 3 : 2;
case 'Apple_Terminal':
return 2;
// No default
}
}
if (/-256(color)?$/i.test(env.TERM)) {
return 2;
}
if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
return 1;
}
if ('COLORTERM' in env) {
return 1;
}
if (env.TERM === 'dumb') {
return min;
}
return min;
}
function getSupportLevel(stream) {
const level = supportsColor(stream);
return translateLevel(level);
}
module.exports = {
supportsColor: getSupportLevel,
stdout: getSupportLevel(process.stdout),
stderr: getSupportLevel(process.stderr)
};
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,53 @@
{
"name": "supports-color",
"version": "5.5.0",
"description": "Detect whether a terminal supports color",
"license": "MIT",
"repository": "chalk/supports-color",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=4"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js",
"browser.js"
],
"keywords": [
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"ansi",
"styles",
"tty",
"rgb",
"256",
"shell",
"xterm",
"command-line",
"support",
"supports",
"capability",
"detect",
"truecolor",
"16m"
],
"dependencies": {
"has-flag": "^3.0.0"
},
"devDependencies": {
"ava": "^0.25.0",
"import-fresh": "^2.0.0",
"xo": "^0.20.0"
},
"browser": "browser.js"
}
@@ -0,0 +1,66 @@
# supports-color [![Build Status](https://travis-ci.org/chalk/supports-color.svg?branch=master)](https://travis-ci.org/chalk/supports-color)
> Detect whether a terminal supports color
## Install
```
$ npm install supports-color
```
## Usage
```js
const supportsColor = require('supports-color');
if (supportsColor.stdout) {
console.log('Terminal stdout supports color');
}
if (supportsColor.stdout.has256) {
console.log('Terminal stdout supports 256 colors');
}
if (supportsColor.stderr.has16m) {
console.log('Terminal stderr supports 16 million colors (truecolor)');
}
```
## API
Returns an `Object` with a `stdout` and `stderr` property for testing either streams. Each property is an `Object`, or `false` if color is not supported.
The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag:
- `.level = 1` and `.hasBasic = true`: Basic color support (16 colors)
- `.level = 2` and `.has256 = true`: 256 color support
- `.level = 3` and `.has16m = true`: Truecolor support (16 million colors)
## Info
It obeys the `--color` and `--no-color` CLI flags.
Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, add the environment variable `FORCE_COLOR=1` to forcefully enable color or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.
Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
## Related
- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module
- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)
## License
MIT
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@babel/code-frame",
"version": "7.22.5",
"version": "7.22.10",
"description": "Generate errors that contain a code frame that point to source locations.",
"author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-code-frame",
@@ -16,7 +16,8 @@
},
"main": "./lib/index.js",
"dependencies": {
"@babel/highlight": "^7.22.5"
"@babel/highlight": "^7.22.10",
"chalk": "^2.4.2"
},
"devDependencies": {
"strip-ansi": "^4.0.0"
+3 -1
View File
@@ -8,6 +8,8 @@ Object.defineProperty(exports, "__ initialize @babel/core cjs proxy __", {
},
});
exports.version = require("./package.json").version;
const functionNames = [
"createConfigItem",
"loadPartialConfig",
@@ -17,7 +19,7 @@ const functionNames = [
"transformFromAst",
"parse",
];
const propertyNames = ["types", "tokTypes", "traverse", "template", "version"];
const propertyNames = ["types", "tokTypes", "traverse", "template"];
for (const name of functionNames) {
exports[name] = function (...args) {
@@ -224,14 +224,16 @@ function buildEnvDescriptors({
dirname,
options
}, alias, descriptors, envName) {
const opts = options.env && options.env[envName];
var _options$env;
const opts = (_options$env = options.env) == null ? void 0 : _options$env[envName];
return opts ? descriptors(dirname, opts, `${alias}.env["${envName}"]`) : null;
}
function buildOverrideDescriptors({
dirname,
options
}, alias, descriptors, index) {
const opts = options.overrides && options.overrides[index];
var _options$overrides;
const opts = (_options$overrides = options.overrides) == null ? void 0 : _options$overrides[index];
if (!opts) throw new Error("Assertion failure - missing override");
return descriptors(dirname, opts, `${alias}.overrides[${index}]`);
}
@@ -239,9 +241,10 @@ function buildOverrideEnvDescriptors({
dirname,
options
}, alias, descriptors, index, envName) {
const override = options.overrides && options.overrides[index];
var _options$overrides2, _override$env;
const override = (_options$overrides2 = options.overrides) == null ? void 0 : _options$overrides2[index];
if (!override) throw new Error("Assertion failure - missing override");
const opts = override.env && override.env[envName];
const opts = (_override$env = override.env) == null ? void 0 : _override$env[envName];
return opts ? descriptors(dirname, opts, `${alias}.overrides[${index}].env["${envName}"]`) : null;
}
function makeChainWalker({
@@ -19,7 +19,8 @@ var _item = require("./item");
var _caching = require("./caching");
var _resolveTargets = require("./resolve-targets");
function isEqualDescriptor(a, b) {
return a.name === b.name && a.value === b.value && a.options === b.options && a.dirname === b.dirname && a.alias === b.alias && a.ownPass === b.ownPass && (a.file && a.file.request) === (b.file && b.file.request) && (a.file && a.file.resolved) === (b.file && b.file.resolved);
var _a$file, _b$file, _a$file2, _b$file2;
return a.name === b.name && a.value === b.value && a.options === b.options && a.dirname === b.dirname && a.alias === b.alias && a.ownPass === b.ownPass && ((_a$file = a.file) == null ? void 0 : _a$file.request) === ((_b$file = b.file) == null ? void 0 : _b$file.request) && ((_a$file2 = a.file) == null ? void 0 : _a$file2.resolved) === ((_b$file2 = b.file) == null ? void 0 : _b$file2.resolved);
}
function* handlerOf(value) {
return value;
+2 -1
View File
@@ -223,7 +223,8 @@ var _transformFile = require("./transform-file");
var _transformAst = require("./transform-ast");
var _parse = require("./parse");
var thisFile = require("./index");
const version = "7.22.9";
;
const version = "7.22.10";
exports.version = version;
const DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs", ".cjs"]);
exports.DEFAULT_EXTENSIONS = DEFAULT_EXTENSIONS;
@@ -78,7 +78,9 @@ function* transformFile(file, pluginPasses) {
}
}
const visitor = _traverse().default.visitors.merge(visitors, passes, file.opts.wrapPluginVisitorMethod);
(0, _traverse().default)(file.ast, visitor, file.scope);
{
(0, _traverse().default)(file.ast, visitor, file.scope);
}
for (const [plugin, pass] of passPairs) {
const fn = plugin.post;
if (fn) {
+10 -10
View File
@@ -1,6 +1,6 @@
{
"name": "@babel/core",
"version": "7.22.9",
"version": "7.22.10",
"description": "Babel compiler core.",
"main": "./lib/index.js",
"author": "The Babel Team (https://babel.dev/team)",
@@ -47,15 +47,15 @@
},
"dependencies": {
"@ampproject/remapping": "^2.2.0",
"@babel/code-frame": "^7.22.5",
"@babel/generator": "^7.22.9",
"@babel/helper-compilation-targets": "^7.22.9",
"@babel/code-frame": "^7.22.10",
"@babel/generator": "^7.22.10",
"@babel/helper-compilation-targets": "^7.22.10",
"@babel/helper-module-transforms": "^7.22.9",
"@babel/helpers": "^7.22.6",
"@babel/parser": "^7.22.7",
"@babel/helpers": "^7.22.10",
"@babel/parser": "^7.22.10",
"@babel/template": "^7.22.5",
"@babel/traverse": "^7.22.8",
"@babel/types": "^7.22.5",
"@babel/traverse": "^7.22.10",
"@babel/types": "^7.22.10",
"convert-source-map": "^1.7.0",
"debug": "^4.1.0",
"gensync": "^1.0.0-beta.2",
@@ -63,11 +63,11 @@
"semver": "^6.3.1"
},
"devDependencies": {
"@babel/helper-transform-fixture-test-runner": "^7.22.7",
"@babel/helper-transform-fixture-test-runner": "^7.22.10",
"@babel/plugin-syntax-flow": "^7.22.5",
"@babel/plugin-transform-flow-strip-types": "^7.22.5",
"@babel/plugin-transform-modules-commonjs": "^7.22.5",
"@babel/preset-env": "^7.22.9",
"@babel/preset-env": "^7.22.10",
"@babel/preset-typescript": "^7.22.5",
"@jridgewell/trace-mapping": "^0.3.17",
"@types/convert-source-map": "^1.5.1",
@@ -13,7 +13,7 @@ const {
const client = new WorkerClient();
exports.meta = {
name: "@babel/eslint-parser/experimental-worker",
version: "7.22.9"
version: "7.22.10"
};
exports.parseForESLint = function (code, options = {}) {
const normalizedOptions = normalizeESLintConfig(options);
+1 -1
View File
@@ -10,7 +10,7 @@ const {
const client = new LocalClient();
exports.meta = {
name: "@babel/eslint-parser",
version: "7.22.9"
version: "7.22.10"
};
exports.parse = function (code, options = {}) {
return baseParse(code, normalizeESLintConfig(options), client);
+1 -1
View File
@@ -21,7 +21,7 @@ module.exports = function parse(code, options, client) {
isRunningMinSupportedCoreVersion = semver.satisfies(client.getVersion(), minSupportedCoreVersion);
}
if (!isRunningMinSupportedCoreVersion) {
throw new Error(`@babel/eslint-parser@${"7.22.9"} does not support @babel/core@${client.getVersion()}. Please upgrade to @babel/core@${minSupportedCoreVersion}.`);
throw new Error(`@babel/eslint-parser@${"7.22.10"} does not support @babel/core@${client.getVersion()}. Please upgrade to @babel/core@${minSupportedCoreVersion}.`);
}
const {
ast,
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@babel/eslint-parser",
"version": "7.22.9",
"version": "7.22.10",
"description": "ESLint parser that allows for linting of experimental syntax transformed by Babel",
"author": "The Babel Team (https://babel.dev/team)",
"license": "MIT",
@@ -27,7 +27,7 @@
"./package.json": "./package.json"
},
"peerDependencies": {
"@babel/core": ">=7.11.0",
"@babel/core": "^7.11.0",
"eslint": "^7.5.0 || ^8.0.0"
},
"dependencies": {
@@ -36,7 +36,7 @@
"semver": "^6.3.1"
},
"devDependencies": {
"@babel/core": "^7.22.9",
"@babel/core": "^7.22.10",
"dedent": "^0.7.0",
"eslint": "^8.22.0"
}
@@ -66,9 +66,9 @@ function ClassBody(node) {
}
}
function ClassProperty(node) {
var _node$key$loc, _node$key$loc$end;
var _node$key$loc;
this.printJoin(node.decorators, node);
const endLine = (_node$key$loc = node.key.loc) == null ? void 0 : (_node$key$loc$end = _node$key$loc.end) == null ? void 0 : _node$key$loc$end.line;
const endLine = (_node$key$loc = node.key.loc) == null || (_node$key$loc = _node$key$loc.end) == null ? void 0 : _node$key$loc.line;
if (endLine) this.catchUp(endLine);
this.tsPrintClassMemberModifiers(node);
if (node.computed) {
@@ -95,9 +95,9 @@ function ClassProperty(node) {
this.semicolon();
}
function ClassAccessorProperty(node) {
var _node$key$loc2, _node$key$loc2$end;
var _node$key$loc2;
this.printJoin(node.decorators, node);
const endLine = (_node$key$loc2 = node.key.loc) == null ? void 0 : (_node$key$loc2$end = _node$key$loc2.end) == null ? void 0 : _node$key$loc2$end.line;
const endLine = (_node$key$loc2 = node.key.loc) == null || (_node$key$loc2 = _node$key$loc2.end) == null ? void 0 : _node$key$loc2.line;
if (endLine) this.catchUp(endLine);
this.tsPrintClassMemberModifiers(node);
this.word("accessor", true);
@@ -152,9 +152,9 @@ function ClassPrivateMethod(node) {
this.print(node.body, node);
}
function _classMethodHead(node) {
var _node$key$loc3, _node$key$loc3$end;
var _node$key$loc3;
this.printJoin(node.decorators, node);
const endLine = (_node$key$loc3 = node.key.loc) == null ? void 0 : (_node$key$loc3$end = _node$key$loc3.end) == null ? void 0 : _node$key$loc3$end.line;
const endLine = (_node$key$loc3 = node.key.loc) == null || (_node$key$loc3 = _node$key$loc3.end) == null ? void 0 : _node$key$loc3.line;
if (endLine) this.catchUp(endLine);
this.tsPrintClassMemberModifiers(node);
this._methodHead(node);
+2 -2
View File
@@ -276,7 +276,7 @@ class Printer {
_catchUp(prop, loc) {
var _loc$prop;
if (!this.format.retainLines) return;
const line = loc == null ? void 0 : (_loc$prop = loc[prop]) == null ? void 0 : _loc$prop.line;
const line = loc == null || (_loc$prop = loc[prop]) == null ? void 0 : _loc$prop.line;
if (line != null) {
const count = line - this._buf.getCurrentLine();
for (let i = 0; i < count; i++) {
@@ -374,7 +374,7 @@ class Printer {
}
getPossibleRaw(node) {
const extra = node.extra;
if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) {
if ((extra == null ? void 0 : extra.raw) != null && extra.rawValue != null && node.value === extra.rawValue) {
return extra.raw;
}
}
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@babel/generator",
"version": "7.22.9",
"version": "7.22.10",
"description": "Turns an AST into code.",
"author": "The Babel Team (https://babel.dev/team)",
"license": "MIT",
@@ -19,14 +19,14 @@
"lib"
],
"dependencies": {
"@babel/types": "^7.22.5",
"@babel/types": "^7.22.10",
"@jridgewell/gen-mapping": "^0.3.2",
"@jridgewell/trace-mapping": "^0.3.17",
"jsesc": "^2.5.1"
},
"devDependencies": {
"@babel/helper-fixtures": "^7.22.9",
"@babel/parser": "^7.22.7",
"@babel/parser": "^7.22.10",
"@jridgewell/sourcemap-codec": "^1.4.15",
"@types/jsesc": "^2.5.0",
"charcodes": "^0.2.0"
@@ -1,6 +1,6 @@
{
"name": "@babel/helper-compilation-targets",
"version": "7.22.9",
"version": "7.22.10",
"author": "The Babel Team (https://babel.dev/team)",
"license": "MIT",
"description": "Helper functions on Babel compilation targets",
@@ -28,11 +28,7 @@
"lru-cache": "^5.1.1",
"semver": "^6.3.1"
},
"peerDependencies": {
"@babel/core": "^7.0.0"
},
"devDependencies": {
"@babel/core": "^7.22.9",
"@babel/helper-plugin-test-runner": "^7.22.5",
"@types/lru-cache": "^5.1.1",
"@types/semver": "^5.5.0"
@@ -31,7 +31,7 @@ var _default = Object.freeze({
iterableToArrayLimitLoose: helper("7.0.0-beta.0", 'export default function _iterableToArrayLimitLoose(arr,i){var _i=arr&&("undefined"!=typeof Symbol&&arr[Symbol.iterator]||arr["@@iterator"]);if(null!=_i){var _s,_arr=[];for(_i=_i.call(arr);arr.length<i&&!(_s=_i.next()).done;)_arr.push(_s.value);return _arr}}'),
jsx: helper("7.0.0-beta.0", 'var REACT_ELEMENT_TYPE;export default function _createRawReactElement(type,props,key,children){REACT_ELEMENT_TYPE||(REACT_ELEMENT_TYPE="function"==typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103);var defaultProps=type&&type.defaultProps,childrenLength=arguments.length-3;if(props||0===childrenLength||(props={children:void 0}),1===childrenLength)props.children=children;else if(childrenLength>1){for(var childArray=new Array(childrenLength),i=0;i<childrenLength;i++)childArray[i]=arguments[i+3];props.children=childArray}if(props&&defaultProps)for(var propName in defaultProps)void 0===props[propName]&&(props[propName]=defaultProps[propName]);else props||(props=defaultProps||{});return{$$typeof:REACT_ELEMENT_TYPE,type:type,key:void 0===key?null:""+key,ref:null,props:props,_owner:null}}'),
objectSpread2: helper("7.5.0", 'import defineProperty from"defineProperty";function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))),keys.push.apply(keys,symbols)}return keys}export default function _objectSpread2(target){for(var i=1;i<arguments.length;i++){var source=null!=arguments[i]?arguments[i]:{};i%2?ownKeys(Object(source),!0).forEach((function(key){defineProperty(target,key,source[key])})):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys(Object(source)).forEach((function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))}))}return target}'),
regeneratorRuntime: helper("7.18.0", 'export default function _regeneratorRuntime(){"use strict";\n/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */_regeneratorRuntime=function(){return exports};var exports={},Op=Object.prototype,hasOwn=Op.hasOwnProperty,defineProperty=Object.defineProperty||function(obj,key,desc){obj[key]=desc.value},$Symbol="function"==typeof Symbol?Symbol:{},iteratorSymbol=$Symbol.iterator||"@@iterator",asyncIteratorSymbol=$Symbol.asyncIterator||"@@asyncIterator",toStringTagSymbol=$Symbol.toStringTag||"@@toStringTag";function define(obj,key,value){return Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}),obj[key]}try{define({},"")}catch(err){define=function(obj,key,value){return obj[key]=value}}function wrap(innerFn,outerFn,self,tryLocsList){var protoGenerator=outerFn&&outerFn.prototype instanceof Generator?outerFn:Generator,generator=Object.create(protoGenerator.prototype),context=new Context(tryLocsList||[]);return defineProperty(generator,"_invoke",{value:makeInvokeMethod(innerFn,self,context)}),generator}function tryCatch(fn,obj,arg){try{return{type:"normal",arg:fn.call(obj,arg)}}catch(err){return{type:"throw",arg:err}}}exports.wrap=wrap;var ContinueSentinel={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var IteratorPrototype={};define(IteratorPrototype,iteratorSymbol,(function(){return this}));var getProto=Object.getPrototypeOf,NativeIteratorPrototype=getProto&&getProto(getProto(values([])));NativeIteratorPrototype&&NativeIteratorPrototype!==Op&&hasOwn.call(NativeIteratorPrototype,iteratorSymbol)&&(IteratorPrototype=NativeIteratorPrototype);var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(IteratorPrototype);function defineIteratorMethods(prototype){["next","throw","return"].forEach((function(method){define(prototype,method,(function(arg){return this._invoke(method,arg)}))}))}function AsyncIterator(generator,PromiseImpl){function invoke(method,arg,resolve,reject){var record=tryCatch(generator[method],generator,arg);if("throw"!==record.type){var result=record.arg,value=result.value;return value&&"object"==typeof value&&hasOwn.call(value,"__await")?PromiseImpl.resolve(value.__await).then((function(value){invoke("next",value,resolve,reject)}),(function(err){invoke("throw",err,resolve,reject)})):PromiseImpl.resolve(value).then((function(unwrapped){result.value=unwrapped,resolve(result)}),(function(error){return invoke("throw",error,resolve,reject)}))}reject(record.arg)}var previousPromise;defineProperty(this,"_invoke",{value:function(method,arg){function callInvokeWithMethodAndArg(){return new PromiseImpl((function(resolve,reject){invoke(method,arg,resolve,reject)}))}return previousPromise=previousPromise?previousPromise.then(callInvokeWithMethodAndArg,callInvokeWithMethodAndArg):callInvokeWithMethodAndArg()}})}function makeInvokeMethod(innerFn,self,context){var state="suspendedStart";return function(method,arg){if("executing"===state)throw new Error("Generator is already running");if("completed"===state){if("throw"===method)throw arg;return doneResult()}for(context.method=method,context.arg=arg;;){var delegate=context.delegate;if(delegate){var delegateResult=maybeInvokeDelegate(delegate,context);if(delegateResult){if(delegateResult===ContinueSentinel)continue;return delegateResult}}if("next"===context.method)context.sent=context._sent=context.arg;else if("throw"===context.method){if("suspendedStart"===state)throw state="completed",context.arg;context.dispatchException(context.arg)}else"return"===context.method&&context.abrupt("return",context.arg);state="executing";var record=tryCatch(innerFn,self,context);if("normal"===record.type){if(state=context.done?"completed":"suspendedYield",record.arg===ContinueSentinel)continue;return{value:record.arg,done:context.done}}"throw"===record.type&&(state="completed",context.method="throw",context.arg=record.arg)}}}function maybeInvokeDelegate(delegate,context){var methodName=context.method,method=delegate.iterator[methodName];if(undefined===method)return context.delegate=null,"throw"===methodName&&delegate.iterator.return&&(context.method="return",context.arg=undefined,maybeInvokeDelegate(delegate,context),"throw"===context.method)||"return"!==methodName&&(context.method="throw",context.arg=new TypeError("The iterator does not provide a \'"+methodName+"\' method")),ContinueSentinel;var record=tryCatch(method,delegate.iterator,context.arg);if("throw"===record.type)return context.method="throw",context.arg=record.arg,context.delegate=null,ContinueSentinel;var info=record.arg;return info?info.done?(context[delegate.resultName]=info.value,context.next=delegate.nextLoc,"return"!==context.method&&(context.method="next",context.arg=undefined),context.delegate=null,ContinueSentinel):info:(context.method="throw",context.arg=new TypeError("iteratorLine truncated
regeneratorRuntime: helper("7.18.0", 'export default function _regeneratorRuntime(){"use strict";\n/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */_regeneratorRuntime=function(){return exports};var exports={},Op=Object.prototype,hasOwn=Op.hasOwnProperty,defineProperty=Object.defineProperty||function(obj,key,desc){obj[key]=desc.value},$Symbol="function"==typeof Symbol?Symbol:{},iteratorSymbol=$Symbol.iterator||"@@iterator",asyncIteratorSymbol=$Symbol.asyncIterator||"@@asyncIterator",toStringTagSymbol=$Symbol.toStringTag||"@@toStringTag";function define(obj,key,value){return Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}),obj[key]}try{define({},"")}catch(err){define=function(obj,key,value){return obj[key]=value}}function wrap(innerFn,outerFn,self,tryLocsList){var protoGenerator=outerFn&&outerFn.prototype instanceof Generator?outerFn:Generator,generator=Object.create(protoGenerator.prototype),context=new Context(tryLocsList||[]);return defineProperty(generator,"_invoke",{value:makeInvokeMethod(innerFn,self,context)}),generator}function tryCatch(fn,obj,arg){try{return{type:"normal",arg:fn.call(obj,arg)}}catch(err){return{type:"throw",arg:err}}}exports.wrap=wrap;var ContinueSentinel={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var IteratorPrototype={};define(IteratorPrototype,iteratorSymbol,(function(){return this}));var getProto=Object.getPrototypeOf,NativeIteratorPrototype=getProto&&getProto(getProto(values([])));NativeIteratorPrototype&&NativeIteratorPrototype!==Op&&hasOwn.call(NativeIteratorPrototype,iteratorSymbol)&&(IteratorPrototype=NativeIteratorPrototype);var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(IteratorPrototype);function defineIteratorMethods(prototype){["next","throw","return"].forEach((function(method){define(prototype,method,(function(arg){return this._invoke(method,arg)}))}))}function AsyncIterator(generator,PromiseImpl){function invoke(method,arg,resolve,reject){var record=tryCatch(generator[method],generator,arg);if("throw"!==record.type){var result=record.arg,value=result.value;return value&&"object"==typeof value&&hasOwn.call(value,"__await")?PromiseImpl.resolve(value.__await).then((function(value){invoke("next",value,resolve,reject)}),(function(err){invoke("throw",err,resolve,reject)})):PromiseImpl.resolve(value).then((function(unwrapped){result.value=unwrapped,resolve(result)}),(function(error){return invoke("throw",error,resolve,reject)}))}reject(record.arg)}var previousPromise;defineProperty(this,"_invoke",{value:function(method,arg){function callInvokeWithMethodAndArg(){return new PromiseImpl((function(resolve,reject){invoke(method,arg,resolve,reject)}))}return previousPromise=previousPromise?previousPromise.then(callInvokeWithMethodAndArg,callInvokeWithMethodAndArg):callInvokeWithMethodAndArg()}})}function makeInvokeMethod(innerFn,self,context){var state="suspendedStart";return function(method,arg){if("executing"===state)throw new Error("Generator is already running");if("completed"===state){if("throw"===method)throw arg;return{value:void 0,done:!0}}for(context.method=method,context.arg=arg;;){var delegate=context.delegate;if(delegate){var delegateResult=maybeInvokeDelegate(delegate,context);if(delegateResult){if(delegateResult===ContinueSentinel)continue;return delegateResult}}if("next"===context.method)context.sent=context._sent=context.arg;else if("throw"===context.method){if("suspendedStart"===state)throw state="completed",context.arg;context.dispatchException(context.arg)}else"return"===context.method&&context.abrupt("return",context.arg);state="executing";var record=tryCatch(innerFn,self,context);if("normal"===record.type){if(state=context.done?"completed":"suspendedYield",record.arg===ContinueSentinel)continue;return{value:record.arg,done:context.done}}"throw"===record.type&&(state="completed",context.method="throw",context.arg=record.arg)}}}function maybeInvokeDelegate(delegate,context){var methodName=context.method,method=delegate.iterator[methodName];if(undefined===method)return context.delegate=null,"throw"===methodName&&delegate.iterator.return&&(context.method="return",context.arg=undefined,maybeInvokeDelegate(delegate,context),"throw"===context.method)||"return"!==methodName&&(context.method="throw",context.arg=new TypeError("The iterator does not provide a \'"+methodName+"\' method")),ContinueSentinel;var record=tryCatch(method,delegate.iterator,context.arg);if("throw"===record.type)return context.method="throw",context.arg=record.arg,context.delegate=null,ContinueSentinel;var info=record.arg;return info?info.done?(context[delegate.resultName]=info.value,context.next=delegate.nextLoc,"return"!==context.method&&(context.method="next",context.arg=undefined),context.delegate=null,ContinueSentinel):info:(context.method="throw",context.arg=new TypeError(Line truncated
typeof: helper("7.0.0-beta.0", 'export default function _typeof(obj){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_typeof(obj)}'),
using: helper("7.22.0", 'export default function _using(stack,value,isAwait){if(null==value)return value;if("object"!=typeof value)throw new TypeError("using declarations can only be used with objects, null, or undefined.");if(isAwait)var dispose=value[Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose")];if(null==dispose&&(dispose=value[Symbol.dispose||Symbol.for("Symbol.dispose")]),"function"!=typeof dispose)throw new TypeError("Property [Symbol.dispose] is not a function.");return stack.push({v:value,d:dispose,a:isAwait}),value}'),
wrapRegExp: helper("7.19.0", 'import setPrototypeOf from"setPrototypeOf";import inherits from"inherits";export default function _wrapRegExp(){_wrapRegExp=function(re,groups){return new BabelRegExp(re,void 0,groups)};var _super=RegExp.prototype,_groups=new WeakMap;function BabelRegExp(re,flags,groups){var _this=new RegExp(re,flags);return _groups.set(_this,groups||_groups.get(re)),setPrototypeOf(_this,BabelRegExp.prototype)}function buildGroups(result,re){var g=_groups.get(re);return Object.keys(g).reduce((function(groups,name){var i=g[name];if("number"==typeof i)groups[name]=result[i];else{for(var k=0;void 0===result[i[k]]&&k+1<i.length;)k++;groups[name]=result[i[k]]}return groups}),Object.create(null))}return inherits(BabelRegExp,RegExp),BabelRegExp.prototype.exec=function(str){var result=_super.exec.call(this,str);if(result){result.groups=buildGroups(result,this);var indices=result.indices;indices&&(indices.groups=buildGroups(indices,this))}return result},BabelRegExp.prototype[Symbol.replace]=function(str,substitution){if("string"==typeof substitution){var groups=_groups.get(this);return _super[Symbol.replace].call(this,str,substitution.replace(/\\$<([^>]+)>/g,(function(_,name){var group=groups[name];return"$"+(Array.isArray(group)?group.join("$"):group)})))}if("function"==typeof substitution){var _this=this;return _super[Symbol.replace].call(this,str,(function(){var args=arguments;return"object"!=typeof args[args.length-1]&&(args=[].slice.call(args)).push(buildGroups(args,_this)),substitution.apply(this,args)}))}return _super[Symbol.replace].call(this,str,substitution)},_wrapRegExp.apply(this,arguments)}')
@@ -315,7 +315,7 @@ function _regeneratorRuntime() {
};
};
function values(iterable) {
if (iterable) {
if (iterable || iterable === "") {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
@@ -340,9 +340,7 @@ function _regeneratorRuntime() {
return next.next = next;
}
}
return {
next: doneResult
};
throw new TypeError(typeof iterable + " is not iterable");
}
_exports.values = values;
function doneResult() {
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@babel/helpers",
"version": "7.22.6",
"version": "7.22.10",
"description": "Collection of helper functions used by Babel transforms.",
"author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-helpers",
@@ -16,14 +16,14 @@
"main": "./lib/index.js",
"dependencies": {
"@babel/template": "^7.22.5",
"@babel/traverse": "^7.22.6",
"@babel/types": "^7.22.5"
"@babel/traverse": "^7.22.10",
"@babel/types": "^7.22.10"
},
"devDependencies": {
"@babel/generator": "^7.22.5",
"@babel/generator": "^7.22.10",
"@babel/helper-plugin-test-runner": "^7.22.5",
"@babel/parser": "^7.22.6",
"regenerator-runtime": "^0.13.11",
"@babel/parser": "^7.22.10",
"regenerator-runtime": "^0.14.0",
"terser": "^5.9.0"
},
"engines": {
+20 -10
View File
@@ -4,11 +4,11 @@ Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = highlight;
exports.getChalk = getChalk;
exports.shouldHighlight = shouldHighlight;
var _jsTokens = require("js-tokens");
var _helperValidatorIdentifier = require("@babel/helper-validator-identifier");
var _chalk = require("chalk");
var _chalk2 = require("chalk");
const chalk = _chalk2;
const sometimesKeywords = new Set(["as", "async", "from", "get", "of", "set"]);
function getDefs(chalk) {
return {
@@ -75,18 +75,28 @@ function highlightTokens(defs, text) {
return highlighted;
}
function shouldHighlight(options) {
return !!_chalk.supportsColor || options.forceColor;
return !!chalk.supportsColor || options.forceColor;
}
function getChalk(options) {
return options.forceColor ? new _chalk.constructor({
enabled: true,
level: 1
}) : _chalk;
let chalkWithForcedColor = undefined;
function getChalk(forceColor) {
if (forceColor) {
var _chalkWithForcedColor;
(_chalkWithForcedColor = chalkWithForcedColor) != null ? _chalkWithForcedColor : chalkWithForcedColor = new chalk.constructor({
enabled: true,
level: 1
});
return chalkWithForcedColor;
}
return chalk;
}
{
{
exports.getChalk = options => getChalk(options.forceColor);
}
}
function highlight(code, options = {}) {
if (code !== "" && shouldHighlight(options)) {
const chalk = getChalk(options);
const defs = getDefs(chalk);
const defs = getDefs(getChalk(options.forceColor));
return highlightTokens(defs, code);
} else {
return code;
+2 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@babel/highlight",
"version": "7.22.5",
"version": "7.22.10",
"description": "Syntax highlight JavaScript strings for output in terminals.",
"author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-highlight",
@@ -16,11 +16,10 @@
"main": "./lib/index.js",
"dependencies": {
"@babel/helper-validator-identifier": "^7.22.5",
"chalk": "^2.0.0",
"chalk": "^2.4.2",
"js-tokens": "^4.0.0"
},
"devDependencies": {
"@types/chalk": "^2.0.0",
"strip-ansi": "^4.0.0"
},
"engines": {
+115 -160
View File
@@ -1377,54 +1377,6 @@ const reservedWordLikeSet = new Set(["break", "case", "catch", "continue", "debu
function canBeReservedWord(word) {
return reservedWordLikeSet.has(word);
}
const SCOPE_OTHER = 0b000000000,
SCOPE_PROGRAM = 0b000000001,
SCOPE_FUNCTION = 0b000000010,
SCOPE_ARROW = 0b000000100,
SCOPE_SIMPLE_CATCH = 0b000001000,
SCOPE_SUPER = 0b000010000,
SCOPE_DIRECT_SUPER = 0b000100000,
SCOPE_CLASS = 0b001000000,
SCOPE_STATIC_BLOCK = 0b010000000,
SCOPE_TS_MODULE = 0b100000000,
SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_STATIC_BLOCK | SCOPE_TS_MODULE;
const BIND_KIND_VALUE = 0b0000000000001,
BIND_KIND_TYPE = 0b0000000000010,
BIND_SCOPE_VAR = 0b0000000000100,
BIND_SCOPE_LEXICAL = 0b0000000001000,
BIND_SCOPE_FUNCTION = 0b0000000010000,
BIND_FLAGS_NONE = 0b00000001000000,
BIND_FLAGS_CLASS = 0b00000010000000,
BIND_FLAGS_TS_ENUM = 0b00000100000000,
BIND_FLAGS_TS_CONST_ENUM = 0b00001000000000,
BIND_FLAGS_TS_EXPORT_ONLY = 0b00010000000000,
BIND_FLAGS_FLOW_DECLARE_FN = 0b00100000000000,
BIND_FLAGS_TS_IMPORT = 0b01000000000000,
BIND_FLAGS_NO_LET_IN_LEXICAL = 0b10000000000000;
const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS | BIND_FLAGS_NO_LET_IN_LEXICAL,
BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | BIND_FLAGS_NO_LET_IN_LEXICAL,
BIND_CATCH_PARAM = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM | BIND_FLAGS_NO_LET_IN_LEXICAL,
BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
BIND_TS_TYPE_IMPORT = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_TS_IMPORT,
BIND_FLOW_DECLARE_FN = BIND_FLAGS_FLOW_DECLARE_FN;
const CLASS_ELEMENT_FLAG_STATIC = 0b100,
CLASS_ELEMENT_KIND_GETTER = 0b010,
CLASS_ELEMENT_KIND_SETTER = 0b001,
CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
CLASS_ELEMENT_OTHER = 0;
class Scope {
constructor(flags) {
this.var = new Set();
@@ -1443,39 +1395,39 @@ class ScopeHandler {
this.inModule = inModule;
}
get inTopLevel() {
return (this.currentScope().flags & SCOPE_PROGRAM) > 0;
return (this.currentScope().flags & 1) > 0;
}
get inFunction() {
return (this.currentVarScopeFlags() & SCOPE_FUNCTION) > 0;
return (this.currentVarScopeFlags() & 2) > 0;
}
get allowSuper() {
return (this.currentThisScopeFlags() & SCOPE_SUPER) > 0;
return (this.currentThisScopeFlags() & 16) > 0;
}
get allowDirectSuper() {
return (this.currentThisScopeFlags() & SCOPE_DIRECT_SUPER) > 0;
return (this.currentThisScopeFlags() & 32) > 0;
}
get inClass() {
return (this.currentThisScopeFlags() & SCOPE_CLASS) > 0;
return (this.currentThisScopeFlags() & 64) > 0;
}
get inClassAndNotInNonArrowFunction() {
const flags = this.currentThisScopeFlags();
return (flags & SCOPE_CLASS) > 0 && (flags & SCOPE_FUNCTION) === 0;
return (flags & 64) > 0 && (flags & 2) === 0;
}
get inStaticBlock() {
for (let i = this.scopeStack.length - 1;; i--) {
const {
flags
} = this.scopeStack[i];
if (flags & SCOPE_STATIC_BLOCK) {
if (flags & 128) {
return true;
}
if (flags & (SCOPE_VAR | SCOPE_CLASS)) {
if (flags & (387 | 64)) {
return false;
}
}
}
get inNonArrowFunction() {
return (this.currentThisScopeFlags() & SCOPE_FUNCTION) > 0;
return (this.currentThisScopeFlags() & 2) > 0;
}
get treatFunctionsAsVar() {
return this.treatFunctionsAsVarInScope(this.currentScope());
@@ -1491,35 +1443,35 @@ class ScopeHandler {
return scope.flags;
}
treatFunctionsAsVarInScope(scope) {
return !!(scope.flags & (SCOPE_FUNCTION | SCOPE_STATIC_BLOCK) || !this.parser.inModule && scope.flags & SCOPE_PROGRAM);
return !!(scope.flags & (2 | 128) || !this.parser.inModule && scope.flags & 1);
}
declareName(name, bindingType, loc) {
let scope = this.currentScope();
if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
if (bindingType & 8 || bindingType & 16) {
this.checkRedeclarationInScope(scope, name, bindingType, loc);
if (bindingType & BIND_SCOPE_FUNCTION) {
if (bindingType & 16) {
scope.functions.add(name);
} else {
scope.lexical.add(name);
}
if (bindingType & BIND_SCOPE_LEXICAL) {
if (bindingType & 8) {
this.maybeExportDefined(scope, name);
}
} else if (bindingType & BIND_SCOPE_VAR) {
} else if (bindingType & 4) {
for (let i = this.scopeStack.length - 1; i >= 0; --i) {
scope = this.scopeStack[i];
this.checkRedeclarationInScope(scope, name, bindingType, loc);
scope.var.add(name);
this.maybeExportDefined(scope, name);
if (scope.flags & SCOPE_VAR) break;
if (scope.flags & 387) break;
}
}
if (this.parser.inModule && scope.flags & SCOPE_PROGRAM) {
if (this.parser.inModule && scope.flags & 1) {
this.undefinedExports.delete(name);
}
}
maybeExportDefined(scope, name) {
if (this.parser.inModule && scope.flags & SCOPE_PROGRAM) {
if (this.parser.inModule && scope.flags & 1) {
this.undefinedExports.delete(name);
}
}
@@ -1532,14 +1484,14 @@ class ScopeHandler {
}
}
isRedeclaredInScope(scope, name, bindingType) {
if (!(bindingType & BIND_KIND_VALUE)) return false;
if (bindingType & BIND_SCOPE_LEXICAL) {
if (!(bindingType & 1)) return false;
if (bindingType & 8) {
return scope.lexical.has(name) || scope.functions.has(name) || scope.var.has(name);
}
if (bindingType & BIND_SCOPE_FUNCTION) {
if (bindingType & 16) {
return scope.lexical.has(name) || !this.treatFunctionsAsVarInScope(scope) && scope.var.has(name);
}
return scope.lexical.has(name) && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical.values().next().value === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.has(name);
return scope.lexical.has(name) && !(scope.flags & 8 && scope.lexical.values().next().value === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.has(name);
}
checkLocalExport(id) {
const {
@@ -1558,7 +1510,7 @@ class ScopeHandler {
const {
flags
} = this.scopeStack[i];
if (flags & SCOPE_VAR) {
if (flags & 387) {
return flags;
}
}
@@ -1568,7 +1520,7 @@ class ScopeHandler {
const {
flags
} = this.scopeStack[i];
if (flags & (SCOPE_VAR | SCOPE_CLASS) && !(flags & SCOPE_ARROW)) {
if (flags & (387 | 64) && !(flags & 4)) {
return flags;
}
}
@@ -1586,7 +1538,7 @@ class FlowScopeHandler extends ScopeHandler {
}
declareName(name, bindingType, loc) {
const scope = this.currentScope();
if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
if (bindingType & 2048) {
this.checkRedeclarationInScope(scope, name, bindingType, loc);
this.maybeExportDefined(scope, name);
scope.declareFunctions.add(name);
@@ -1596,7 +1548,7 @@ class FlowScopeHandler extends ScopeHandler {
}
isRedeclaredInScope(scope, name, bindingType) {
if (super.isRedeclaredInScope(scope, name, bindingType)) return true;
if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
if (bindingType & 2048) {
return !scope.declareFunctions.has(name) && (scope.lexical.has(name) || scope.functions.has(name));
}
return false;
@@ -3355,13 +3307,13 @@ class ClassScopeHandler {
undefinedPrivateNames
} = this.current();
let redefined = privateNames.has(name);
if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
if (elementType & 3) {
const accessor = redefined && loneAccessors.get(name);
if (accessor) {
const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
const oldStatic = accessor & 4;
const newStatic = elementType & 4;
const oldKind = accessor & 3;
const newKind = elementType & 3;
redefined = oldKind === newKind || oldStatic !== newStatic;
if (!redefined) loneAccessors.delete(name);
} else if (!redefined) {
@@ -3392,20 +3344,15 @@ class ClassScopeHandler {
}
}
}
const kExpression = 0,
kMaybeArrowParameterDeclaration = 1,
kMaybeAsyncArrowParameterDeclaration = 2,
kParameterDeclaration = 3;
class ExpressionScope {
constructor(type = kExpression) {
this.type = void 0;
constructor(type = 0) {
this.type = type;
}
canBeArrowParameterDeclaration() {
return this.type === kMaybeAsyncArrowParameterDeclaration || this.type === kMaybeArrowParameterDeclaration;
return this.type === 2 || this.type === 1;
}
isCertainlyParameterDeclaration() {
return this.type === kParameterDeclaration;
return this.type === 3;
}
}
class ArrowHeadParsingScope extends ExpressionScope {
@@ -3486,7 +3433,7 @@ class ExpressionScopeHandler {
let i = stack.length - 1;
let scope = stack[i];
while (scope.canBeArrowParameterDeclaration()) {
if (scope.type === kMaybeAsyncArrowParameterDeclaration) {
if (scope.type === 2) {
scope.recordDeclarationError(Errors.AwaitBindingIdentifier, {
at
});
@@ -3514,13 +3461,13 @@ class ExpressionScopeHandler {
}
}
function newParameterDeclarationScope() {
return new ExpressionScope(kParameterDeclaration);
return new ExpressionScope(3);
}
function newArrowHeadScope() {
return new ArrowHeadParsingScope(kMaybeArrowParameterDeclaration);
return new ArrowHeadParsingScope(1);
}
function newAsyncArrowScope() {
return new ArrowHeadParsingScope(kMaybeAsyncArrowParameterDeclaration);
return new ArrowHeadParsingScope(2);
}
function newExpressionScope() {
return new ExpressionScope();
@@ -3758,7 +3705,7 @@ class UtilParser extends Tokenizer {
if (this.inModule) {
paramFlags |= PARAM_AWAIT;
}
this.scope.enter(SCOPE_PROGRAM);
this.scope.enter(1);
this.prodParam.enter(paramFlags);
}
checkDestructuringPrivate(refExpressionErrors) {
@@ -4109,7 +4056,7 @@ var flow = superClass => class FlowParserMixin extends superClass {
id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
this.resetEndLocation(id);
this.semicolon();
this.scope.declareName(node.id.name, BIND_FLOW_DECLARE_FN, node.id.loc.start);
this.scope.declareName(node.id.name, 2048, node.id.loc.start);
return this.finishNode(node, "DeclareFunction");
}
flowParseDeclare(node, insideModule) {
@@ -4145,12 +4092,12 @@ var flow = superClass => class FlowParserMixin extends superClass {
flowParseDeclareVariable(node) {
this.next();
node.id = this.flowParseTypeAnnotatableIdentifier(true);
this.scope.declareName(node.id.name, BIND_VAR, node.id.loc.start);
this.scope.declareName(node.id.name, 5, node.id.loc.start);
this.semicolon();
return this.finishNode(node, "DeclareVariable");
}
flowParseDeclareModule(node) {
this.scope.enter(SCOPE_OTHER);
this.scope.enter(0);
if (this.match(131)) {
node.id = super.parseExprAtom();
} else {
@@ -4269,7 +4216,7 @@ var flow = superClass => class FlowParserMixin extends superClass {
}
flowParseInterfaceish(node, isClass) {
node.id = this.flowParseRestrictedIdentifier(!isClass, true);
this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.loc.start);
this.scope.declareName(node.id.name, isClass ? 17 : 8201, node.id.loc.start);
if (this.match(47)) {
node.typeParameters = this.flowParseTypeParameterDeclaration();
} else {
@@ -4337,7 +4284,7 @@ var flow = superClass => class FlowParserMixin extends superClass {
}
flowParseTypeAlias(node) {
node.id = this.flowParseRestrictedIdentifier(false, true);
this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.loc.start);
this.scope.declareName(node.id.name, 8201, node.id.loc.start);
if (this.match(47)) {
node.typeParameters = this.flowParseTypeParameterDeclaration();
} else {
@@ -4350,7 +4297,7 @@ var flow = superClass => class FlowParserMixin extends superClass {
flowParseOpaqueType(node, declare) {
this.expectContextual(128);
node.id = this.flowParseRestrictedIdentifier(true, true);
this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.loc.start);
this.scope.declareName(node.id.name, 8201, node.id.loc.start);
if (this.match(47)) {
node.typeParameters = this.flowParseTypeParameterDeclaration();
} else {
@@ -5268,7 +5215,7 @@ var flow = superClass => class FlowParserMixin extends superClass {
finishArrowValidation(node) {
var _node$extra;
this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingCommaLoc, false);
this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
this.scope.enter(2 | 4);
super.checkParams(node, false, true);
this.scope.exit();
}
@@ -7050,14 +6997,14 @@ class TypeScriptScopeHandler extends ScopeHandler {
return new TypeScriptScope(flags);
}
enter(flags) {
if (flags == SCOPE_TS_MODULE) {
if (flags == 256) {
this.importsStack.push(new Set());
}
super.enter(flags);
}
exit() {
const flags = super.exit();
if (flags == SCOPE_TS_MODULE) {
if (flags == 256) {
this.importsStack.pop();
}
return flags;
@@ -7075,7 +7022,7 @@ class TypeScriptScopeHandler extends ScopeHandler {
return false;
}
declareName(name, bindingType, loc) {
if (bindingType & BIND_FLAGS_TS_IMPORT) {
if (bindingType & 4096) {
if (this.hasImport(name, true)) {
this.parser.raise(Errors.VarRedeclaration, {
at: loc,
@@ -7086,40 +7033,42 @@ class TypeScriptScopeHandler extends ScopeHandler {
return;
}
const scope = this.currentScope();
if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
if (bindingType & 1024) {
this.maybeExportDefined(scope, name);
scope.exportOnlyBindings.add(name);
return;
}
super.declareName(name, bindingType, loc);
if (bindingType & BIND_KIND_TYPE) {
if (!(bindingType & BIND_KIND_VALUE)) {
if (bindingType & 2) {
if (!(bindingType & 1)) {
this.checkRedeclarationInScope(scope, name, bindingType, loc);
this.maybeExportDefined(scope, name);
}
scope.types.add(name);
}
if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.add(name);
if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.add(name);
if (bindingType & BIND_FLAGS_CLASS) scope.classes.add(name);
if (bindingType & 256) scope.enums.add(name);
if (bindingType & 512) {
scope.constEnums.add(name);
}
if (bindingType & 128) scope.classes.add(name);
}
isRedeclaredInScope(scope, name, bindingType) {
if (scope.enums.has(name)) {
if (bindingType & BIND_FLAGS_TS_ENUM) {
const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
if (bindingType & 256) {
const isConst = !!(bindingType & 512);
const wasConst = scope.constEnums.has(name);
return isConst !== wasConst;
}
return true;
}
if (bindingType & BIND_FLAGS_CLASS && scope.classes.has(name)) {
if (bindingType & 128 && scope.classes.has(name)) {
if (scope.lexical.has(name)) {
return !!(bindingType & BIND_KIND_VALUE);
return !!(bindingType & 1);
} else {
return false;
}
}
if (bindingType & BIND_KIND_TYPE && scope.types.has(name)) {
if (bindingType & 2 && scope.types.has(name)) {
return true;
}
return super.isRedeclaredInScope(scope, name, bindingType);
@@ -7426,7 +7375,7 @@ class LValParser extends NodeUtils {
}
checkLVal(expression, {
in: ancestor,
binding = BIND_NONE,
binding = 64,
checkClashes = false,
strictModeChanged = false,
hasParenthesizedAncestor = false
@@ -7435,7 +7384,7 @@ class LValParser extends NodeUtils {
const type = expression.type;
if (this.isObjectMethod(expression)) return;
if (type === "MemberExpression") {
if (binding !== BIND_NONE) {
if (binding !== 64) {
this.raise(Errors.InvalidPropertyBindingPattern, {
at: expression
});
@@ -7461,7 +7410,7 @@ class LValParser extends NodeUtils {
const validity = this.isValidLVal(type, !(hasParenthesizedAncestor || (_expression$extra = expression.extra) != null && _expression$extra.parenthesized) && ancestor.type === "AssignmentExpression", binding);
if (validity === true) return;
if (validity === false) {
const ParseErrorClass = binding === BIND_NONE ? Errors.InvalidLhs : Errors.InvalidLhsBinding;
const ParseErrorClass = binding === 64 ? Errors.InvalidLhs : Errors.InvalidLhsBinding;
this.raise(ParseErrorClass, {
at: expression,
ancestor
@@ -7486,7 +7435,7 @@ class LValParser extends NodeUtils {
}
checkIdentifier(at, bindingType, strictModeChanged = false) {
if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(at.name, this.inModule) : isStrictBindOnlyReservedWord(at.name))) {
if (bindingType === BIND_NONE) {
if (bindingType === 64) {
this.raise(Errors.StrictEvalArguments, {
at,
referenceName: at.name
@@ -7498,12 +7447,12 @@ class LValParser extends NodeUtils {
});
}
}
if (bindingType & BIND_FLAGS_NO_LET_IN_LEXICAL && at.name === "let") {
if (bindingType & 8192 && at.name === "let") {
this.raise(Errors.LetInLexicalBinding, {
at
});
}
if (!(bindingType & BIND_NONE)) {
if (!(bindingType & 64)) {
this.declareNameFromIdentifier(at, bindingType);
}
}
@@ -8676,7 +8625,7 @@ var typescript = superClass => class TypeScriptParserMixin extends superClass {
if (properties.declare) node.declare = true;
if (tokenIsIdentifier(this.state.type)) {
node.id = this.parseIdentifier();
this.checkIdentifier(node.id, BIND_TS_INTERFACE);
this.checkIdentifier(node.id, 130);
} else {
node.id = null;
this.raise(TSErrors.MissingInterfaceName, {
@@ -8694,7 +8643,7 @@ var typescript = superClass => class TypeScriptParserMixin extends superClass {
}
tsParseTypeAliasDeclaration(node) {
node.id = this.parseIdentifier();
this.checkIdentifier(node.id, BIND_TS_TYPE);
this.checkIdentifier(node.id, 2);
node.typeAnnotation = this.tsInType(() => {
node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers);
this.expect(29);
@@ -8774,7 +8723,7 @@ var typescript = superClass => class TypeScriptParserMixin extends superClass {
if (properties.declare) node.declare = true;
this.expectContextual(124);
node.id = this.parseIdentifier();
this.checkIdentifier(node.id, node.const ? BIND_TS_CONST_ENUM : BIND_TS_ENUM);
this.checkIdentifier(node.id, node.const ? 8971 : 8459);
this.expect(5);
node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
this.expect(8);
@@ -8782,7 +8731,7 @@ var typescript = superClass => class TypeScriptParserMixin extends superClass {
}
tsParseModuleBlock() {
const node = this.startNode();
this.scope.enter(SCOPE_OTHER);
this.scope.enter(0);
this.expect(5);
super.parseBlockOrModuleBlockBody(node.body = [], undefined, true, 8);
this.scope.exit();
@@ -8791,14 +8740,14 @@ var typescript = superClass => class TypeScriptParserMixin extends superClass {
tsParseModuleOrNamespaceDeclaration(node, nested = false) {
node.id = this.parseIdentifier();
if (!nested) {
this.checkIdentifier(node.id, BIND_TS_NAMESPACE);
this.checkIdentifier(node.id, 1024);
}
if (this.eat(16)) {
const inner = this.startNode();
this.tsParseModuleOrNamespaceDeclaration(inner, true);
node.body = inner;
} else {
this.scope.enter(SCOPE_TS_MODULE);
this.scope.enter(256);
this.prodParam.enter(PARAM);
node.body = this.tsParseModuleBlock();
this.prodParam.exit();
@@ -8816,7 +8765,7 @@ var typescript = superClass => class TypeScriptParserMixin extends superClass {
this.unexpected();
}
if (this.match(5)) {
this.scope.enter(SCOPE_TS_MODULE);
this.scope.enter(256);
this.prodParam.enter(PARAM);
node.body = this.tsParseModuleBlock();
this.prodParam.exit();
@@ -8829,7 +8778,7 @@ var typescript = superClass => class TypeScriptParserMixin extends superClass {
tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier, isExport) {
node.isExport = isExport || false;
node.id = maybeDefaultIdentifier || this.parseIdentifier();
this.checkIdentifier(node.id, BIND_FLAGS_TS_IMPORT);
this.checkIdentifier(node.id, 4096);
this.expect(29);
const moduleReference = this.tsParseModuleReference();
if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") {
@@ -8943,7 +8892,7 @@ var typescript = superClass => class TypeScriptParserMixin extends superClass {
}
case "global":
if (this.match(5)) {
this.scope.enter(SCOPE_TS_MODULE);
this.scope.enter(256);
this.prodParam.enter(PARAM);
const mod = node;
mod.global = true;
@@ -9112,7 +9061,7 @@ var typescript = superClass => class TypeScriptParserMixin extends superClass {
}
registerFunctionStatementId(node) {
if (!node.body && node.id) {
this.checkIdentifier(node.id, BIND_TS_AMBIENT);
this.checkIdentifier(node.id, 1024);
} else {
super.registerFunctionStatementId(node);
}
@@ -9541,7 +9490,7 @@ var typescript = superClass => class TypeScriptParserMixin extends superClass {
if ((!isStatement || optionalId) && this.isContextual(111)) {
return;
}
super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
super.parseClassId(node, isStatement, optionalId, node.declare ? 1024 : 8331);
const typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);
if (typeParameters) node.typeParameters = typeParameters;
}
@@ -9830,9 +9779,9 @@ var typescript = superClass => class TypeScriptParserMixin extends superClass {
TSTypeCastExpression: true,
TSParameterProperty: "parameter",
TSNonNullExpression: "expression",
TSAsExpression: (binding !== BIND_NONE || !isUnparenthesizedInAssign) && ["expression", true],
TSSatisfiesExpression: (binding !== BIND_NONE || !isUnparenthesizedInAssign) && ["expression", true],
TSTypeAssertion: (binding !== BIND_NONE || !isUnparenthesizedInAssign) && ["expression", true]
TSAsExpression: (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true],
TSSatisfiesExpression: (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true],
TSTypeAssertion: (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true]
}, type) || super.isValidLVal(type, isUnparenthesizedInAssign, binding);
}
parseBindingAtom() {
@@ -10043,7 +9992,7 @@ var typescript = superClass => class TypeScriptParserMixin extends superClass {
return this.finishNode(specifier, "ImportSpecifier");
}
specifier.importKind = "value";
return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, isInTypeOnlyImport ? BIND_TS_TYPE_IMPORT : BIND_FLAGS_TS_IMPORT);
return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, isInTypeOnlyImport ? 4098 : 4096);
}
parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) {
const leftOfAsKey = isImport ? "imported" : "local";
@@ -10100,7 +10049,7 @@ var typescript = superClass => class TypeScriptParserMixin extends superClass {
node[rightOfAsKey] = cloneIdentifier(node[leftOfAsKey]);
}
if (isImport) {
this.checkIdentifier(node[rightOfAsKey], hasTypeSpecifier ? BIND_TS_TYPE_IMPORT : BIND_FLAGS_TS_IMPORT);
this.checkIdentifier(node[rightOfAsKey], hasTypeSpecifier ? 4098 : 4096);
}
}
};
@@ -10240,7 +10189,8 @@ var placeholders = superClass => class PlaceholdersParserMixin extends superClas
super.verifyBreakContinue(node, isBreak);
}
parseExpressionStatement(node, expr) {
if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
var _expr$extra;
if (expr.type !== "Placeholder" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
return super.parseExpressionStatement(node, expr);
}
if (this.match(14)) {
@@ -10518,12 +10468,16 @@ const defaultOptions = {
annexB: true
};
function getOptions(opts) {
if (opts && opts.annexB != null && opts.annexB !== false) {
if (opts == null) {
return Object.assign({}, defaultOptions);
}
if (opts.annexB != null && opts.annexB !== false) {
throw new Error("The `annexB` option can only be set to `false`.");
}
const options = {};
for (const key of Object.keys(defaultOptions)) {
options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
var _opts$key;
options[key] = (_opts$key = opts[key]) != null ? _opts$key : defaultOptions[key];
}
return options;
}
@@ -11885,7 +11839,7 @@ class ExpressionParser extends LValParser {
parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
this.initFunction(node, isAsync);
node.generator = isGenerator;
this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
this.scope.enter(2 | 16 | (inClassScope ? 64 : 0) | (allowDirectSuper ? 32 : 0));
this.prodParam.enter(functionFlags(isAsync, node.generator));
this.parseFunctionParams(node, isConstructor);
const finishedNode = this.parseFunctionBodyAndFinish(node, type, true);
@@ -11906,7 +11860,7 @@ class ExpressionParser extends LValParser {
return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
}
parseArrowExpression(node, params, isAsync, trailingCommaLoc) {
this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
this.scope.enter(2 | 4);
let flags = functionFlags(isAsync, false);
if (!this.match(5) && this.prodParam.hasIn) {
flags |= PARAM_IN;
@@ -11954,7 +11908,7 @@ class ExpressionParser extends LValParser {
const strictModeChanged = !oldStrict && this.state.strict;
this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
if (this.state.strict && node.id) {
this.checkIdentifier(node.id, BIND_OUTSIDE, strictModeChanged);
this.checkIdentifier(node.id, 65, strictModeChanged);
}
});
this.prodParam.exit();
@@ -11979,7 +11933,7 @@ class ExpressionParser extends LValParser {
for (const param of node.params) {
this.checkLVal(param, {
in: formalParameters,
binding: BIND_VAR,
binding: 5,
checkClashes,
strictModeChanged
});
@@ -12896,7 +12850,7 @@ class StatementParser extends ExpressionParser {
if (this.isAwaitAllowed() && this.eatContextual(96)) {
awaitAt = this.state.lastTokStartLoc;
}
this.scope.enter(SCOPE_OTHER);
this.scope.enter(0);
this.expect(10);
if (this.match(13)) {
if (awaitAt !== null) {
@@ -13007,7 +12961,7 @@ class StatementParser extends ExpressionParser {
const cases = node.cases = [];
this.expect(5);
this.state.labels.push(switchLabel);
this.scope.enter(SCOPE_OTHER);
this.scope.enter(0);
let cur;
for (let sawDefault; !this.match(8);) {
if (this.match(61) || this.match(65)) {
@@ -13055,12 +13009,12 @@ class StatementParser extends ExpressionParser {
}
parseCatchClauseParam() {
const param = this.parseBindingAtom();
this.scope.enter(this.options.annexB && param.type === "Identifier" ? SCOPE_SIMPLE_CATCH : 0);
this.scope.enter(this.options.annexB && param.type === "Identifier" ? 8 : 0);
this.checkLVal(param, {
in: {
type: "CatchClause"
},
binding: BIND_CATCH_PARAM
binding: 9
});
return param;
}
@@ -13077,7 +13031,7 @@ class StatementParser extends ExpressionParser {
this.expect(11);
} else {
clause.param = null;
this.scope.enter(SCOPE_OTHER);
this.scope.enter(0);
}
clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false));
this.scope.exit();
@@ -13161,7 +13115,7 @@ class StatementParser extends ExpressionParser {
}
this.expect(5);
if (createNewLexicalScope) {
this.scope.enter(SCOPE_OTHER);
this.scope.enter(0);
}
this.parseBlockBody(node, allowDirectives, false, 8, afterBlockParse);
if (createNewLexicalScope) {
@@ -13277,7 +13231,7 @@ class StatementParser extends ExpressionParser {
in: {
type: "VariableDeclarator"
},
binding: kind === "var" ? BIND_VAR : BIND_LEXICAL
binding: kind === "var" ? 5 : 8201
});
decl.id = id;
}
@@ -13304,7 +13258,7 @@ class StatementParser extends ExpressionParser {
}
const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
this.state.maybeInArrowParameters = false;
this.scope.enter(SCOPE_FUNCTION);
this.scope.enter(2);
this.prodParam.enter(functionFlags(isAsync, node.generator));
if (!isDeclaration) {
node.id = this.parseFunctionId();
@@ -13332,7 +13286,7 @@ class StatementParser extends ExpressionParser {
}
registerFunctionStatementId(node) {
if (!node.id) return;
this.scope.declareName(node.id.name, !this.options.annexB || this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION, node.id.loc.start);
this.scope.declareName(node.id.name, !this.options.annexB || this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? 5 : 8201 : 17, node.id.loc.start);
}
parseClass(node, isStatement, optionalId) {
this.next();
@@ -13571,7 +13525,7 @@ class StatementParser extends ExpressionParser {
}
parseClassStaticBlock(classBody, member) {
var _member$decorators;
this.scope.enter(SCOPE_CLASS | SCOPE_STATIC_BLOCK | SCOPE_SUPER);
this.scope.enter(64 | 128 | 16);
const oldLabels = this.state.labels;
this.state.labels = [];
this.prodParam.enter(PARAM);
@@ -13598,7 +13552,7 @@ class StatementParser extends ExpressionParser {
pushClassPrivateProperty(classBody, prop) {
const node = this.parseClassPrivateProperty(prop);
classBody.body.push(node);
this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), CLASS_ELEMENT_OTHER, node.key.loc.start);
this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start);
}
pushClassAccessorProperty(classBody, prop, isPrivate) {
if (!isPrivate && !prop.computed) {
@@ -13612,7 +13566,7 @@ class StatementParser extends ExpressionParser {
const node = this.parseClassAccessorProperty(prop);
classBody.body.push(node);
if (isPrivate) {
this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), CLASS_ELEMENT_OTHER, node.key.loc.start);
this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start);
}
}
pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
@@ -13621,7 +13575,7 @@ class StatementParser extends ExpressionParser {
pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
classBody.body.push(node);
const kind = node.kind === "get" ? node.static ? CLASS_ELEMENT_STATIC_GETTER : CLASS_ELEMENT_INSTANCE_GETTER : node.kind === "set" ? node.static ? CLASS_ELEMENT_STATIC_SETTER : CLASS_ELEMENT_INSTANCE_SETTER : CLASS_ELEMENT_OTHER;
const kind = node.kind === "get" ? node.static ? 6 : 2 : node.kind === "set" ? node.static ? 5 : 1 : 0;
this.declareClassPrivateMethodInScope(node, kind);
}
declareClassPrivateMethodInScope(node, kind) {
@@ -13644,7 +13598,7 @@ class StatementParser extends ExpressionParser {
return this.finishNode(node, "ClassAccessorProperty");
}
parseInitializer(node) {
this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
this.scope.enter(64 | 16);
this.expressionScope.enter(newExpressionScope());
this.prodParam.enter(PARAM);
node.value = this.eat(29) ? this.parseMaybeAssignAllowIn() : null;
@@ -13652,7 +13606,7 @@ class StatementParser extends ExpressionParser {
this.prodParam.exit();
this.scope.exit();
}
parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
parseClassId(node, isStatement, optionalId, bindingType = 8331) {
if (tokenIsIdentifier(this.state.type)) {
node.id = this.parseIdentifier();
if (isStatement) {
@@ -13891,6 +13845,7 @@ class StatementParser extends ExpressionParser {
}
checkExport(node, checkNames, isDefault, isFrom) {
if (checkNames) {
var _node$specifiers;
if (isDefault) {
this.checkDuplicateExports(node, "default");
if (this.hasPlugin("exportDefaultFrom")) {
@@ -13902,7 +13857,7 @@ class StatementParser extends ExpressionParser {
});
}
}
} else if (node.specifiers && node.specifiers.length) {
} else if ((_node$specifiers = node.specifiers) != null && _node$specifiers.length) {
for (const specifier of node.specifiers) {
const {
exported
@@ -14123,8 +14078,8 @@ class StatementParser extends ExpressionParser {
return this.parseImportSourceAndAttributes(node);
}
parseImportSourceAndAttributes(node) {
var _node$specifiers;
(_node$specifiers = node.specifiers) != null ? _node$specifiers : node.specifiers = [];
var _node$specifiers2;
(_node$specifiers2 = node.specifiers) != null ? _node$specifiers2 : node.specifiers = [];
node.source = this.parseImportSource();
this.maybeParseImportAttributes(node);
this.checkImportReflection(node);
@@ -14140,7 +14095,7 @@ class StatementParser extends ExpressionParser {
specifier.local = this.parseIdentifier();
node.specifiers.push(this.finishImportSpecifier(specifier, type));
}
finishImportSpecifier(specifier, type, bindingType = BIND_LEXICAL) {
finishImportSpecifier(specifier, type, bindingType = 8201) {
this.checkLVal(specifier.local, {
in: {
type
+6 -2
View File
@@ -27,12 +27,16 @@ const defaultOptions = {
};
exports.defaultOptions = defaultOptions;
function getOptions(opts) {
if (opts && opts.annexB != null && opts.annexB !== false) {
if (opts == null) {
return Object.assign({}, defaultOptions);
}
if (opts.annexB != null && opts.annexB !== false) {
throw new Error("The `annexB` option can only be set to `false`.");
}
const options = {};
for (const key of Object.keys(defaultOptions)) {
options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
var _opts$key;
options[key] = (_opts$key = opts[key]) != null ? _opts$key : defaultOptions[key];
}
return options;
}
@@ -1374,7 +1374,7 @@ class ExpressionParser extends _lval.default {
parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
this.initFunction(node, isAsync);
node.generator = isGenerator;
this.scope.enter(_scopeflags.SCOPE_FUNCTION | _scopeflags.SCOPE_SUPER | (inClassScope ? _scopeflags.SCOPE_CLASS : 0) | (allowDirectSuper ? _scopeflags.SCOPE_DIRECT_SUPER : 0));
this.scope.enter(_scopeflags.ScopeFlag.FUNCTION | _scopeflags.ScopeFlag.SUPER | (inClassScope ? _scopeflags.ScopeFlag.CLASS : 0) | (allowDirectSuper ? _scopeflags.ScopeFlag.DIRECT_SUPER : 0));
this.prodParam.enter((0, _productionParameter.functionFlags)(isAsync, node.generator));
this.parseFunctionParams(node, isConstructor);
const finishedNode = this.parseFunctionBodyAndFinish(node, type, true);
@@ -1395,7 +1395,7 @@ class ExpressionParser extends _lval.default {
return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
}
parseArrowExpression(node, params, isAsync, trailingCommaLoc) {
this.scope.enter(_scopeflags.SCOPE_FUNCTION | _scopeflags.SCOPE_ARROW);
this.scope.enter(_scopeflags.ScopeFlag.FUNCTION | _scopeflags.ScopeFlag.ARROW);
let flags = (0, _productionParameter.functionFlags)(isAsync, false);
if (!this.match(5) && this.prodParam.hasIn) {
flags |= _productionParameter.PARAM_IN;
@@ -1443,7 +1443,7 @@ class ExpressionParser extends _lval.default {
const strictModeChanged = !oldStrict && this.state.strict;
this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
if (this.state.strict && node.id) {
this.checkIdentifier(node.id, _scopeflags.BIND_OUTSIDE, strictModeChanged);
this.checkIdentifier(node.id, _scopeflags.BindingFlag.TYPE_OUTSIDE, strictModeChanged);
}
});
this.prodParam.exit();
@@ -1468,7 +1468,7 @@ class ExpressionParser extends _lval.default {
for (const param of node.params) {
this.checkLVal(param, {
in: formalParameters,
binding: _scopeflags.BIND_VAR,
binding: _scopeflags.BindingFlag.TYPE_VAR,
checkClashes,
strictModeChanged
});
+6 -6
View File
@@ -305,7 +305,7 @@ class LValParser extends _node.NodeUtils {
}
checkLVal(expression, {
in: ancestor,
binding = _scopeflags.BIND_NONE,
binding = _scopeflags.BindingFlag.TYPE_NONE,
checkClashes = false,
strictModeChanged = false,
hasParenthesizedAncestor = false
@@ -314,7 +314,7 @@ class LValParser extends _node.NodeUtils {
const type = expression.type;
if (this.isObjectMethod(expression)) return;
if (type === "MemberExpression") {
if (binding !== _scopeflags.BIND_NONE) {
if (binding !== _scopeflags.BindingFlag.TYPE_NONE) {
this.raise(_parseError.Errors.InvalidPropertyBindingPattern, {
at: expression
});
@@ -340,7 +340,7 @@ class LValParser extends _node.NodeUtils {
const validity = this.isValidLVal(type, !(hasParenthesizedAncestor || (_expression$extra = expression.extra) != null && _expression$extra.parenthesized) && ancestor.type === "AssignmentExpression", binding);
if (validity === true) return;
if (validity === false) {
const ParseErrorClass = binding === _scopeflags.BIND_NONE ? _parseError.Errors.InvalidLhs : _parseError.Errors.InvalidLhsBinding;
const ParseErrorClass = binding === _scopeflags.BindingFlag.TYPE_NONE ? _parseError.Errors.InvalidLhs : _parseError.Errors.InvalidLhsBinding;
this.raise(ParseErrorClass, {
at: expression,
ancestor
@@ -365,7 +365,7 @@ class LValParser extends _node.NodeUtils {
}
checkIdentifier(at, bindingType, strictModeChanged = false) {
if (this.state.strict && (strictModeChanged ? (0, _identifier.isStrictBindReservedWord)(at.name, this.inModule) : (0, _identifier.isStrictBindOnlyReservedWord)(at.name))) {
if (bindingType === _scopeflags.BIND_NONE) {
if (bindingType === _scopeflags.BindingFlag.TYPE_NONE) {
this.raise(_parseError.Errors.StrictEvalArguments, {
at,
referenceName: at.name
@@ -377,12 +377,12 @@ class LValParser extends _node.NodeUtils {
});
}
}
if (bindingType & _scopeflags.BIND_FLAGS_NO_LET_IN_LEXICAL && at.name === "let") {
if (bindingType & _scopeflags.BindingFlag.FLAG_NO_LET_IN_LEXICAL && at.name === "let") {
this.raise(_parseError.Errors.LetInLexicalBinding, {
at
});
}
if (!(bindingType & _scopeflags.BIND_NONE)) {
if (!(bindingType & _scopeflags.BindingFlag.TYPE_NONE)) {
this.declareNameFromIdentifier(at, bindingType);
}
}
+20 -19
View File
@@ -598,7 +598,7 @@ class StatementParser extends _expression.default {
if (this.isAwaitAllowed() && this.eatContextual(96)) {
awaitAt = this.state.lastTokStartLoc;
}
this.scope.enter(_scopeflags.SCOPE_OTHER);
this.scope.enter(_scopeflags.ScopeFlag.OTHER);
this.expect(10);
if (this.match(13)) {
if (awaitAt !== null) {
@@ -709,7 +709,7 @@ class StatementParser extends _expression.default {
const cases = node.cases = [];
this.expect(5);
this.state.labels.push(switchLabel);
this.scope.enter(_scopeflags.SCOPE_OTHER);
this.scope.enter(_scopeflags.ScopeFlag.OTHER);
let cur;
for (let sawDefault; !this.match(8);) {
if (this.match(61) || this.match(65)) {
@@ -757,12 +757,12 @@ class StatementParser extends _expression.default {
}
parseCatchClauseParam() {
const param = this.parseBindingAtom();
this.scope.enter(this.options.annexB && param.type === "Identifier" ? _scopeflags.SCOPE_SIMPLE_CATCH : 0);
this.scope.enter(this.options.annexB && param.type === "Identifier" ? _scopeflags.ScopeFlag.SIMPLE_CATCH : 0);
this.checkLVal(param, {
in: {
type: "CatchClause"
},
binding: _scopeflags.BIND_CATCH_PARAM
binding: _scopeflags.BindingFlag.TYPE_CATCH_PARAM
});
return param;
}
@@ -779,7 +779,7 @@ class StatementParser extends _expression.default {
this.expect(11);
} else {
clause.param = null;
this.scope.enter(_scopeflags.SCOPE_OTHER);
this.scope.enter(_scopeflags.ScopeFlag.OTHER);
}
clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false));
this.scope.exit();
@@ -863,7 +863,7 @@ class StatementParser extends _expression.default {
}
this.expect(5);
if (createNewLexicalScope) {
this.scope.enter(_scopeflags.SCOPE_OTHER);
this.scope.enter(_scopeflags.ScopeFlag.OTHER);
}
this.parseBlockBody(node, allowDirectives, false, 8, afterBlockParse);
if (createNewLexicalScope) {
@@ -979,7 +979,7 @@ class StatementParser extends _expression.default {
in: {
type: "VariableDeclarator"
},
binding: kind === "var" ? _scopeflags.BIND_VAR : _scopeflags.BIND_LEXICAL
binding: kind === "var" ? _scopeflags.BindingFlag.TYPE_VAR : _scopeflags.BindingFlag.TYPE_LEXICAL
});
decl.id = id;
}
@@ -1006,7 +1006,7 @@ class StatementParser extends _expression.default {
}
const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
this.state.maybeInArrowParameters = false;
this.scope.enter(_scopeflags.SCOPE_FUNCTION);
this.scope.enter(_scopeflags.ScopeFlag.FUNCTION);
this.prodParam.enter((0, _productionParameter.functionFlags)(isAsync, node.generator));
if (!isDeclaration) {
node.id = this.parseFunctionId();
@@ -1034,7 +1034,7 @@ class StatementParser extends _expression.default {
}
registerFunctionStatementId(node) {
if (!node.id) return;
this.scope.declareName(node.id.name, !this.options.annexB || this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? _scopeflags.BIND_VAR : _scopeflags.BIND_LEXICAL : _scopeflags.BIND_FUNCTION, node.id.loc.start);
this.scope.declareName(node.id.name, !this.options.annexB || this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? _scopeflags.BindingFlag.TYPE_VAR : _scopeflags.BindingFlag.TYPE_LEXICAL : _scopeflags.BindingFlag.TYPE_FUNCTION, node.id.loc.start);
}
parseClass(node, isStatement, optionalId) {
this.next();
@@ -1273,7 +1273,7 @@ class StatementParser extends _expression.default {
}
parseClassStaticBlock(classBody, member) {
var _member$decorators;
this.scope.enter(_scopeflags.SCOPE_CLASS | _scopeflags.SCOPE_STATIC_BLOCK | _scopeflags.SCOPE_SUPER);
this.scope.enter(_scopeflags.ScopeFlag.CLASS | _scopeflags.ScopeFlag.STATIC_BLOCK | _scopeflags.ScopeFlag.SUPER);
const oldLabels = this.state.labels;
this.state.labels = [];
this.prodParam.enter(_productionParameter.PARAM);
@@ -1300,7 +1300,7 @@ class StatementParser extends _expression.default {
pushClassPrivateProperty(classBody, prop) {
const node = this.parseClassPrivateProperty(prop);
classBody.body.push(node);
this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), _scopeflags.CLASS_ELEMENT_OTHER, node.key.loc.start);
this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), _scopeflags.ClassElementType.OTHER, node.key.loc.start);
}
pushClassAccessorProperty(classBody, prop, isPrivate) {
if (!isPrivate && !prop.computed) {
@@ -1314,7 +1314,7 @@ class StatementParser extends _expression.default {
const node = this.parseClassAccessorProperty(prop);
classBody.body.push(node);
if (isPrivate) {
this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), _scopeflags.CLASS_ELEMENT_OTHER, node.key.loc.start);
this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), _scopeflags.ClassElementType.OTHER, node.key.loc.start);
}
}
pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
@@ -1323,7 +1323,7 @@ class StatementParser extends _expression.default {
pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
classBody.body.push(node);
const kind = node.kind === "get" ? node.static ? _scopeflags.CLASS_ELEMENT_STATIC_GETTER : _scopeflags.CLASS_ELEMENT_INSTANCE_GETTER : node.kind === "set" ? node.static ? _scopeflags.CLASS_ELEMENT_STATIC_SETTER : _scopeflags.CLASS_ELEMENT_INSTANCE_SETTER : _scopeflags.CLASS_ELEMENT_OTHER;
const kind = node.kind === "get" ? node.static ? _scopeflags.ClassElementType.STATIC_GETTER : _scopeflags.ClassElementType.INSTANCE_GETTER : node.kind === "set" ? node.static ? _scopeflags.ClassElementType.STATIC_SETTER : _scopeflags.ClassElementType.INSTANCE_SETTER : _scopeflags.ClassElementType.OTHER;
this.declareClassPrivateMethodInScope(node, kind);
}
declareClassPrivateMethodInScope(node, kind) {
@@ -1346,7 +1346,7 @@ class StatementParser extends _expression.default {
return this.finishNode(node, "ClassAccessorProperty");
}
parseInitializer(node) {
this.scope.enter(_scopeflags.SCOPE_CLASS | _scopeflags.SCOPE_SUPER);
this.scope.enter(_scopeflags.ScopeFlag.CLASS | _scopeflags.ScopeFlag.SUPER);
this.expressionScope.enter((0, _expressionScope.newExpressionScope)());
this.prodParam.enter(_productionParameter.PARAM);
node.value = this.eat(29) ? this.parseMaybeAssignAllowIn() : null;
@@ -1354,7 +1354,7 @@ class StatementParser extends _expression.default {
this.prodParam.exit();
this.scope.exit();
}
parseClassId(node, isStatement, optionalId, bindingType = _scopeflags.BIND_CLASS) {
parseClassId(node, isStatement, optionalId, bindingType = _scopeflags.BindingFlag.TYPE_CLASS) {
if ((0, _types.tokenIsIdentifier)(this.state.type)) {
node.id = this.parseIdentifier();
if (isStatement) {
@@ -1593,6 +1593,7 @@ class StatementParser extends _expression.default {
}
checkExport(node, checkNames, isDefault, isFrom) {
if (checkNames) {
var _node$specifiers;
if (isDefault) {
this.checkDuplicateExports(node, "default");
if (this.hasPlugin("exportDefaultFrom")) {
@@ -1604,7 +1605,7 @@ class StatementParser extends _expression.default {
});
}
}
} else if (node.specifiers && node.specifiers.length) {
} else if ((_node$specifiers = node.specifiers) != null && _node$specifiers.length) {
for (const specifier of node.specifiers) {
const {
exported
@@ -1826,8 +1827,8 @@ class StatementParser extends _expression.default {
return this.parseImportSourceAndAttributes(node);
}
parseImportSourceAndAttributes(node) {
var _node$specifiers;
(_node$specifiers = node.specifiers) != null ? _node$specifiers : node.specifiers = [];
var _node$specifiers2;
(_node$specifiers2 = node.specifiers) != null ? _node$specifiers2 : node.specifiers = [];
node.source = this.parseImportSource();
this.maybeParseImportAttributes(node);
this.checkImportReflection(node);
@@ -1843,7 +1844,7 @@ class StatementParser extends _expression.default {
specifier.local = this.parseIdentifier();
node.specifiers.push(this.finishImportSpecifier(specifier, type));
}
finishImportSpecifier(specifier, type, bindingType = _scopeflags.BIND_LEXICAL) {
finishImportSpecifier(specifier, type, bindingType = _scopeflags.BindingFlag.TYPE_LEXICAL) {
this.checkLVal(specifier.local, {
in: {
type
+1 -1
View File
@@ -212,7 +212,7 @@ class UtilParser extends _tokenizer.default {
if (this.inModule) {
paramFlags |= _productionParameter.PARAM_AWAIT;
}
this.scope.enter(_scopeflags.SCOPE_PROGRAM);
this.scope.enter(_scopeflags.ScopeFlag.PROGRAM);
this.prodParam.enter(paramFlags);
}
checkDestructuringPrivate(refExpressionErrors) {
@@ -231,7 +231,7 @@ var _default = superClass => class FlowParserMixin extends superClass {
id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
this.resetEndLocation(id);
this.semicolon();
this.scope.declareName(node.id.name, _scopeflags.BIND_FLOW_DECLARE_FN, node.id.loc.start);
this.scope.declareName(node.id.name, _scopeflags.BindingFlag.TYPE_FLOW_DECLARE_FN, node.id.loc.start);
return this.finishNode(node, "DeclareFunction");
}
flowParseDeclare(node, insideModule) {
@@ -267,12 +267,12 @@ var _default = superClass => class FlowParserMixin extends superClass {
flowParseDeclareVariable(node) {
this.next();
node.id = this.flowParseTypeAnnotatableIdentifier(true);
this.scope.declareName(node.id.name, _scopeflags.BIND_VAR, node.id.loc.start);
this.scope.declareName(node.id.name, _scopeflags.BindingFlag.TYPE_VAR, node.id.loc.start);
this.semicolon();
return this.finishNode(node, "DeclareVariable");
}
flowParseDeclareModule(node) {
this.scope.enter(_scopeflags.SCOPE_OTHER);
this.scope.enter(_scopeflags.ScopeFlag.OTHER);
if (this.match(131)) {
node.id = super.parseExprAtom();
} else {
@@ -391,7 +391,7 @@ var _default = superClass => class FlowParserMixin extends superClass {
}
flowParseInterfaceish(node, isClass) {
node.id = this.flowParseRestrictedIdentifier(!isClass, true);
this.scope.declareName(node.id.name, isClass ? _scopeflags.BIND_FUNCTION : _scopeflags.BIND_LEXICAL, node.id.loc.start);
this.scope.declareName(node.id.name, isClass ? _scopeflags.BindingFlag.TYPE_FUNCTION : _scopeflags.BindingFlag.TYPE_LEXICAL, node.id.loc.start);
if (this.match(47)) {
node.typeParameters = this.flowParseTypeParameterDeclaration();
} else {
@@ -459,7 +459,7 @@ var _default = superClass => class FlowParserMixin extends superClass {
}
flowParseTypeAlias(node) {
node.id = this.flowParseRestrictedIdentifier(false, true);
this.scope.declareName(node.id.name, _scopeflags.BIND_LEXICAL, node.id.loc.start);
this.scope.declareName(node.id.name, _scopeflags.BindingFlag.TYPE_LEXICAL, node.id.loc.start);
if (this.match(47)) {
node.typeParameters = this.flowParseTypeParameterDeclaration();
} else {
@@ -472,7 +472,7 @@ var _default = superClass => class FlowParserMixin extends superClass {
flowParseOpaqueType(node, declare) {
this.expectContextual(128);
node.id = this.flowParseRestrictedIdentifier(true, true);
this.scope.declareName(node.id.name, _scopeflags.BIND_LEXICAL, node.id.loc.start);
this.scope.declareName(node.id.name, _scopeflags.BindingFlag.TYPE_LEXICAL, node.id.loc.start);
if (this.match(47)) {
node.typeParameters = this.flowParseTypeParameterDeclaration();
} else {
@@ -1390,7 +1390,7 @@ var _default = superClass => class FlowParserMixin extends superClass {
finishArrowValidation(node) {
var _node$extra;
this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingCommaLoc, false);
this.scope.enter(_scopeflags.SCOPE_FUNCTION | _scopeflags.SCOPE_ARROW);
this.scope.enter(_scopeflags.ScopeFlag.FUNCTION | _scopeflags.ScopeFlag.ARROW);
super.checkParams(node, false, true);
this.scope.exit();
}
@@ -18,7 +18,7 @@ class FlowScopeHandler extends _scope.default {
}
declareName(name, bindingType, loc) {
const scope = this.currentScope();
if (bindingType & _scopeflags.BIND_FLAGS_FLOW_DECLARE_FN) {
if (bindingType & _scopeflags.BindingFlag.FLAG_FLOW_DECLARE_FN) {
this.checkRedeclarationInScope(scope, name, bindingType, loc);
this.maybeExportDefined(scope, name);
scope.declareFunctions.add(name);
@@ -28,7 +28,7 @@ class FlowScopeHandler extends _scope.default {
}
isRedeclaredInScope(scope, name, bindingType) {
if (super.isRedeclaredInScope(scope, name, bindingType)) return true;
if (bindingType & _scopeflags.BIND_FLAGS_FLOW_DECLARE_FN) {
if (bindingType & _scopeflags.BindingFlag.FLAG_FLOW_DECLARE_FN) {
return !scope.declareFunctions.has(name) && (scope.lexical.has(name) || scope.functions.has(name));
}
return false;
@@ -73,7 +73,8 @@ var _default = superClass => class PlaceholdersParserMixin extends superClass {
super.verifyBreakContinue(node, isBreak);
}
parseExpressionStatement(node, expr) {
if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
var _expr$extra;
if (expr.type !== "Placeholder" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
return super.parseExpressionStatement(node, expr);
}
if (this.match(14)) {
@@ -1153,7 +1153,7 @@ var _default = superClass => class TypeScriptParserMixin extends superClass {
if (properties.declare) node.declare = true;
if ((0, _types.tokenIsIdentifier)(this.state.type)) {
node.id = this.parseIdentifier();
this.checkIdentifier(node.id, _scopeflags.BIND_TS_INTERFACE);
this.checkIdentifier(node.id, _scopeflags.BindingFlag.TYPE_TS_INTERFACE);
} else {
node.id = null;
this.raise(TSErrors.MissingInterfaceName, {
@@ -1171,7 +1171,7 @@ var _default = superClass => class TypeScriptParserMixin extends superClass {
}
tsParseTypeAliasDeclaration(node) {
node.id = this.parseIdentifier();
this.checkIdentifier(node.id, _scopeflags.BIND_TS_TYPE);
this.checkIdentifier(node.id, _scopeflags.BindingFlag.TYPE_TS_TYPE);
node.typeAnnotation = this.tsInType(() => {
node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers);
this.expect(29);
@@ -1251,7 +1251,7 @@ var _default = superClass => class TypeScriptParserMixin extends superClass {
if (properties.declare) node.declare = true;
this.expectContextual(124);
node.id = this.parseIdentifier();
this.checkIdentifier(node.id, node.const ? _scopeflags.BIND_TS_CONST_ENUM : _scopeflags.BIND_TS_ENUM);
this.checkIdentifier(node.id, node.const ? _scopeflags.BindingFlag.TYPE_TS_CONST_ENUM : _scopeflags.BindingFlag.TYPE_TS_ENUM);
this.expect(5);
node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
this.expect(8);
@@ -1259,7 +1259,7 @@ var _default = superClass => class TypeScriptParserMixin extends superClass {
}
tsParseModuleBlock() {
const node = this.startNode();
this.scope.enter(_scopeflags.SCOPE_OTHER);
this.scope.enter(_scopeflags.ScopeFlag.OTHER);
this.expect(5);
super.parseBlockOrModuleBlockBody(node.body = [], undefined, true, 8);
this.scope.exit();
@@ -1268,14 +1268,14 @@ var _default = superClass => class TypeScriptParserMixin extends superClass {
tsParseModuleOrNamespaceDeclaration(node, nested = false) {
node.id = this.parseIdentifier();
if (!nested) {
this.checkIdentifier(node.id, _scopeflags.BIND_TS_NAMESPACE);
this.checkIdentifier(node.id, _scopeflags.BindingFlag.TYPE_TS_NAMESPACE);
}
if (this.eat(16)) {
const inner = this.startNode();
this.tsParseModuleOrNamespaceDeclaration(inner, true);
node.body = inner;
} else {
this.scope.enter(_scopeflags.SCOPE_TS_MODULE);
this.scope.enter(_scopeflags.ScopeFlag.TS_MODULE);
this.prodParam.enter(_productionParameter.PARAM);
node.body = this.tsParseModuleBlock();
this.prodParam.exit();
@@ -1293,7 +1293,7 @@ var _default = superClass => class TypeScriptParserMixin extends superClass {
this.unexpected();
}
if (this.match(5)) {
this.scope.enter(_scopeflags.SCOPE_TS_MODULE);
this.scope.enter(_scopeflags.ScopeFlag.TS_MODULE);
this.prodParam.enter(_productionParameter.PARAM);
node.body = this.tsParseModuleBlock();
this.prodParam.exit();
@@ -1306,7 +1306,7 @@ var _default = superClass => class TypeScriptParserMixin extends superClass {
tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier, isExport) {
node.isExport = isExport || false;
node.id = maybeDefaultIdentifier || this.parseIdentifier();
this.checkIdentifier(node.id, _scopeflags.BIND_FLAGS_TS_IMPORT);
this.checkIdentifier(node.id, _scopeflags.BindingFlag.TYPE_TS_VALUE_IMPORT);
this.expect(29);
const moduleReference = this.tsParseModuleReference();
if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") {
@@ -1420,7 +1420,7 @@ var _default = superClass => class TypeScriptParserMixin extends superClass {
}
case "global":
if (this.match(5)) {
this.scope.enter(_scopeflags.SCOPE_TS_MODULE);
this.scope.enter(_scopeflags.ScopeFlag.TS_MODULE);
this.prodParam.enter(_productionParameter.PARAM);
const mod = node;
mod.global = true;
@@ -1589,7 +1589,7 @@ var _default = superClass => class TypeScriptParserMixin extends superClass {
}
registerFunctionStatementId(node) {
if (!node.body && node.id) {
this.checkIdentifier(node.id, _scopeflags.BIND_TS_AMBIENT);
this.checkIdentifier(node.id, _scopeflags.BindingFlag.TYPE_TS_AMBIENT);
} else {
super.registerFunctionStatementId(node);
}
@@ -2018,7 +2018,7 @@ var _default = superClass => class TypeScriptParserMixin extends superClass {
if ((!isStatement || optionalId) && this.isContextual(111)) {
return;
}
super.parseClassId(node, isStatement, optionalId, node.declare ? _scopeflags.BIND_TS_AMBIENT : _scopeflags.BIND_CLASS);
super.parseClassId(node, isStatement, optionalId, node.declare ? _scopeflags.BindingFlag.TYPE_TS_AMBIENT : _scopeflags.BindingFlag.TYPE_CLASS);
const typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);
if (typeParameters) node.typeParameters = typeParameters;
}
@@ -2308,9 +2308,9 @@ var _default = superClass => class TypeScriptParserMixin extends superClass {
TSTypeCastExpression: true,
TSParameterProperty: "parameter",
TSNonNullExpression: "expression",
TSAsExpression: (binding !== _scopeflags.BIND_NONE || !isUnparenthesizedInAssign) && ["expression", true],
TSSatisfiesExpression: (binding !== _scopeflags.BIND_NONE || !isUnparenthesizedInAssign) && ["expression", true],
TSTypeAssertion: (binding !== _scopeflags.BIND_NONE || !isUnparenthesizedInAssign) && ["expression", true]
TSAsExpression: (binding !== _scopeflags.BindingFlag.TYPE_NONE || !isUnparenthesizedInAssign) && ["expression", true],
TSSatisfiesExpression: (binding !== _scopeflags.BindingFlag.TYPE_NONE || !isUnparenthesizedInAssign) && ["expression", true],
TSTypeAssertion: (binding !== _scopeflags.BindingFlag.TYPE_NONE || !isUnparenthesizedInAssign) && ["expression", true]
}, type) || super.isValidLVal(type, isUnparenthesizedInAssign, binding);
}
parseBindingAtom() {
@@ -2521,7 +2521,7 @@ var _default = superClass => class TypeScriptParserMixin extends superClass {
return this.finishNode(specifier, "ImportSpecifier");
}
specifier.importKind = "value";
return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, isInTypeOnlyImport ? _scopeflags.BIND_TS_TYPE_IMPORT : _scopeflags.BIND_FLAGS_TS_IMPORT);
return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, isInTypeOnlyImport ? _scopeflags.BindingFlag.TYPE_TS_TYPE_IMPORT : _scopeflags.BindingFlag.TYPE_TS_VALUE_IMPORT);
}
parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) {
const leftOfAsKey = isImport ? "imported" : "local";
@@ -2578,7 +2578,7 @@ var _default = superClass => class TypeScriptParserMixin extends superClass {
node[rightOfAsKey] = (0, _node.cloneIdentifier)(node[leftOfAsKey]);
}
if (isImport) {
this.checkIdentifier(node[rightOfAsKey], hasTypeSpecifier ? _scopeflags.BIND_TS_TYPE_IMPORT : _scopeflags.BIND_FLAGS_TS_IMPORT);
this.checkIdentifier(node[rightOfAsKey], hasTypeSpecifier ? _scopeflags.BindingFlag.TYPE_TS_TYPE_IMPORT : _scopeflags.BindingFlag.TYPE_TS_VALUE_IMPORT);
}
}
};
@@ -27,14 +27,14 @@ class TypeScriptScopeHandler extends _scope.default {
return new TypeScriptScope(flags);
}
enter(flags) {
if (flags == _scopeflags.SCOPE_TS_MODULE) {
if (flags == _scopeflags.ScopeFlag.TS_MODULE) {
this.importsStack.push(new Set());
}
super.enter(flags);
}
exit() {
const flags = super.exit();
if (flags == _scopeflags.SCOPE_TS_MODULE) {
if (flags == _scopeflags.ScopeFlag.TS_MODULE) {
this.importsStack.pop();
}
return flags;
@@ -52,7 +52,7 @@ class TypeScriptScopeHandler extends _scope.default {
return false;
}
declareName(name, bindingType, loc) {
if (bindingType & _scopeflags.BIND_FLAGS_TS_IMPORT) {
if (bindingType & _scopeflags.BindingFlag.FLAG_TS_IMPORT) {
if (this.hasImport(name, true)) {
this.parser.raise(_parseError.Errors.VarRedeclaration, {
at: loc,
@@ -63,40 +63,42 @@ class TypeScriptScopeHandler extends _scope.default {
return;
}
const scope = this.currentScope();
if (bindingType & _scopeflags.BIND_FLAGS_TS_EXPORT_ONLY) {
if (bindingType & _scopeflags.BindingFlag.FLAG_TS_EXPORT_ONLY) {
this.maybeExportDefined(scope, name);
scope.exportOnlyBindings.add(name);
return;
}
super.declareName(name, bindingType, loc);
if (bindingType & _scopeflags.BIND_KIND_TYPE) {
if (!(bindingType & _scopeflags.BIND_KIND_VALUE)) {
if (bindingType & _scopeflags.BindingFlag.KIND_TYPE) {
if (!(bindingType & _scopeflags.BindingFlag.KIND_VALUE)) {
this.checkRedeclarationInScope(scope, name, bindingType, loc);
this.maybeExportDefined(scope, name);
}
scope.types.add(name);
}
if (bindingType & _scopeflags.BIND_FLAGS_TS_ENUM) scope.enums.add(name);
if (bindingType & _scopeflags.BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.add(name);
if (bindingType & _scopeflags.BIND_FLAGS_CLASS) scope.classes.add(name);
if (bindingType & _scopeflags.BindingFlag.FLAG_TS_ENUM) scope.enums.add(name);
if (bindingType & _scopeflags.BindingFlag.FLAG_TS_CONST_ENUM) {
scope.constEnums.add(name);
}
if (bindingType & _scopeflags.BindingFlag.FLAG_CLASS) scope.classes.add(name);
}
isRedeclaredInScope(scope, name, bindingType) {
if (scope.enums.has(name)) {
if (bindingType & _scopeflags.BIND_FLAGS_TS_ENUM) {
const isConst = !!(bindingType & _scopeflags.BIND_FLAGS_TS_CONST_ENUM);
if (bindingType & _scopeflags.BindingFlag.FLAG_TS_ENUM) {
const isConst = !!(bindingType & _scopeflags.BindingFlag.FLAG_TS_CONST_ENUM);
const wasConst = scope.constEnums.has(name);
return isConst !== wasConst;
}
return true;
}
if (bindingType & _scopeflags.BIND_FLAGS_CLASS && scope.classes.has(name)) {
if (bindingType & _scopeflags.BindingFlag.FLAG_CLASS && scope.classes.has(name)) {
if (scope.lexical.has(name)) {
return !!(bindingType & _scopeflags.BIND_KIND_VALUE);
return !!(bindingType & _scopeflags.BindingFlag.KIND_VALUE);
} else {
return false;
}
}
if (bindingType & _scopeflags.BIND_KIND_TYPE && scope.types.has(name)) {
if (bindingType & _scopeflags.BindingFlag.KIND_TYPE && scope.types.has(name)) {
return true;
}
return super.isRedeclaredInScope(scope, name, bindingType);
@@ -50,13 +50,13 @@ class ClassScopeHandler {
undefinedPrivateNames
} = this.current();
let redefined = privateNames.has(name);
if (elementType & _scopeflags.CLASS_ELEMENT_KIND_ACCESSOR) {
if (elementType & _scopeflags.ClassElementType.KIND_ACCESSOR) {
const accessor = redefined && loneAccessors.get(name);
if (accessor) {
const oldStatic = accessor & _scopeflags.CLASS_ELEMENT_FLAG_STATIC;
const newStatic = elementType & _scopeflags.CLASS_ELEMENT_FLAG_STATIC;
const oldKind = accessor & _scopeflags.CLASS_ELEMENT_KIND_ACCESSOR;
const newKind = elementType & _scopeflags.CLASS_ELEMENT_KIND_ACCESSOR;
const oldStatic = accessor & _scopeflags.ClassElementType.FLAG_STATIC;
const newStatic = elementType & _scopeflags.ClassElementType.FLAG_STATIC;
const oldKind = accessor & _scopeflags.ClassElementType.KIND_ACCESSOR;
const newKind = elementType & _scopeflags.ClassElementType.KIND_ACCESSOR;
redefined = oldKind === newKind || oldStatic !== newStatic;
if (!redefined) loneAccessors.delete(name);
} else if (!redefined) {
@@ -9,20 +9,15 @@ exports.newAsyncArrowScope = newAsyncArrowScope;
exports.newExpressionScope = newExpressionScope;
exports.newParameterDeclarationScope = newParameterDeclarationScope;
var _parseError = require("../parse-error");
const kExpression = 0,
kMaybeArrowParameterDeclaration = 1,
kMaybeAsyncArrowParameterDeclaration = 2,
kParameterDeclaration = 3;
class ExpressionScope {
constructor(type = kExpression) {
this.type = void 0;
constructor(type = 0) {
this.type = type;
}
canBeArrowParameterDeclaration() {
return this.type === kMaybeAsyncArrowParameterDeclaration || this.type === kMaybeArrowParameterDeclaration;
return this.type === 2 || this.type === 1;
}
isCertainlyParameterDeclaration() {
return this.type === kParameterDeclaration;
return this.type === 3;
}
}
class ArrowHeadParsingScope extends ExpressionScope {
@@ -103,7 +98,7 @@ class ExpressionScopeHandler {
let i = stack.length - 1;
let scope = stack[i];
while (scope.canBeArrowParameterDeclaration()) {
if (scope.type === kMaybeAsyncArrowParameterDeclaration) {
if (scope.type === 2) {
scope.recordDeclarationError(_parseError.Errors.AwaitBindingIdentifier, {
at
});
@@ -132,13 +127,13 @@ class ExpressionScopeHandler {
}
exports.default = ExpressionScopeHandler;
function newParameterDeclarationScope() {
return new ExpressionScope(kParameterDeclaration);
return new ExpressionScope(3);
}
function newArrowHeadScope() {
return new ArrowHeadParsingScope(kMaybeArrowParameterDeclaration);
return new ArrowHeadParsingScope(1);
}
function newAsyncArrowScope() {
return new ArrowHeadParsingScope(kMaybeAsyncArrowParameterDeclaration);
return new ArrowHeadParsingScope(2);
}
function newExpressionScope() {
return new ExpressionScope();
+23 -23
View File
@@ -25,39 +25,39 @@ class ScopeHandler {
this.inModule = inModule;
}
get inTopLevel() {
return (this.currentScope().flags & _scopeflags.SCOPE_PROGRAM) > 0;
return (this.currentScope().flags & _scopeflags.ScopeFlag.PROGRAM) > 0;
}
get inFunction() {
return (this.currentVarScopeFlags() & _scopeflags.SCOPE_FUNCTION) > 0;
return (this.currentVarScopeFlags() & _scopeflags.ScopeFlag.FUNCTION) > 0;
}
get allowSuper() {
return (this.currentThisScopeFlags() & _scopeflags.SCOPE_SUPER) > 0;
return (this.currentThisScopeFlags() & _scopeflags.ScopeFlag.SUPER) > 0;
}
get allowDirectSuper() {
return (this.currentThisScopeFlags() & _scopeflags.SCOPE_DIRECT_SUPER) > 0;
return (this.currentThisScopeFlags() & _scopeflags.ScopeFlag.DIRECT_SUPER) > 0;
}
get inClass() {
return (this.currentThisScopeFlags() & _scopeflags.SCOPE_CLASS) > 0;
return (this.currentThisScopeFlags() & _scopeflags.ScopeFlag.CLASS) > 0;
}
get inClassAndNotInNonArrowFunction() {
const flags = this.currentThisScopeFlags();
return (flags & _scopeflags.SCOPE_CLASS) > 0 && (flags & _scopeflags.SCOPE_FUNCTION) === 0;
return (flags & _scopeflags.ScopeFlag.CLASS) > 0 && (flags & _scopeflags.ScopeFlag.FUNCTION) === 0;
}
get inStaticBlock() {
for (let i = this.scopeStack.length - 1;; i--) {
const {
flags
} = this.scopeStack[i];
if (flags & _scopeflags.SCOPE_STATIC_BLOCK) {
if (flags & _scopeflags.ScopeFlag.STATIC_BLOCK) {
return true;
}
if (flags & (_scopeflags.SCOPE_VAR | _scopeflags.SCOPE_CLASS)) {
if (flags & (_scopeflags.ScopeFlag.VAR | _scopeflags.ScopeFlag.CLASS)) {
return false;
}
}
}
get inNonArrowFunction() {
return (this.currentThisScopeFlags() & _scopeflags.SCOPE_FUNCTION) > 0;
return (this.currentThisScopeFlags() & _scopeflags.ScopeFlag.FUNCTION) > 0;
}
get treatFunctionsAsVar() {
return this.treatFunctionsAsVarInScope(this.currentScope());
@@ -73,35 +73,35 @@ class ScopeHandler {
return scope.flags;
}
treatFunctionsAsVarInScope(scope) {
return !!(scope.flags & (_scopeflags.SCOPE_FUNCTION | _scopeflags.SCOPE_STATIC_BLOCK) || !this.parser.inModule && scope.flags & _scopeflags.SCOPE_PROGRAM);
return !!(scope.flags & (_scopeflags.ScopeFlag.FUNCTION | _scopeflags.ScopeFlag.STATIC_BLOCK) || !this.parser.inModule && scope.flags & _scopeflags.ScopeFlag.PROGRAM);
}
declareName(name, bindingType, loc) {
let scope = this.currentScope();
if (bindingType & _scopeflags.BIND_SCOPE_LEXICAL || bindingType & _scopeflags.BIND_SCOPE_FUNCTION) {
if (bindingType & _scopeflags.BindingFlag.SCOPE_LEXICAL || bindingType & _scopeflags.BindingFlag.SCOPE_FUNCTION) {
this.checkRedeclarationInScope(scope, name, bindingType, loc);
if (bindingType & _scopeflags.BIND_SCOPE_FUNCTION) {
if (bindingType & _scopeflags.BindingFlag.SCOPE_FUNCTION) {
scope.functions.add(name);
} else {
scope.lexical.add(name);
}
if (bindingType & _scopeflags.BIND_SCOPE_LEXICAL) {
if (bindingType & _scopeflags.BindingFlag.SCOPE_LEXICAL) {
this.maybeExportDefined(scope, name);
}
} else if (bindingType & _scopeflags.BIND_SCOPE_VAR) {
} else if (bindingType & _scopeflags.BindingFlag.SCOPE_VAR) {
for (let i = this.scopeStack.length - 1; i >= 0; --i) {
scope = this.scopeStack[i];
this.checkRedeclarationInScope(scope, name, bindingType, loc);
scope.var.add(name);
this.maybeExportDefined(scope, name);
if (scope.flags & _scopeflags.SCOPE_VAR) break;
if (scope.flags & _scopeflags.ScopeFlag.VAR) break;
}
}
if (this.parser.inModule && scope.flags & _scopeflags.SCOPE_PROGRAM) {
if (this.parser.inModule && scope.flags & _scopeflags.ScopeFlag.PROGRAM) {
this.undefinedExports.delete(name);
}
}
maybeExportDefined(scope, name) {
if (this.parser.inModule && scope.flags & _scopeflags.SCOPE_PROGRAM) {
if (this.parser.inModule && scope.flags & _scopeflags.ScopeFlag.PROGRAM) {
this.undefinedExports.delete(name);
}
}
@@ -114,14 +114,14 @@ class ScopeHandler {
}
}
isRedeclaredInScope(scope, name, bindingType) {
if (!(bindingType & _scopeflags.BIND_KIND_VALUE)) return false;
if (bindingType & _scopeflags.BIND_SCOPE_LEXICAL) {
if (!(bindingType & _scopeflags.BindingFlag.KIND_VALUE)) return false;
if (bindingType & _scopeflags.BindingFlag.SCOPE_LEXICAL) {
return scope.lexical.has(name) || scope.functions.has(name) || scope.var.has(name);
}
if (bindingType & _scopeflags.BIND_SCOPE_FUNCTION) {
if (bindingType & _scopeflags.BindingFlag.SCOPE_FUNCTION) {
return scope.lexical.has(name) || !this.treatFunctionsAsVarInScope(scope) && scope.var.has(name);
}
return scope.lexical.has(name) && !(scope.flags & _scopeflags.SCOPE_SIMPLE_CATCH && scope.lexical.values().next().value === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.has(name);
return scope.lexical.has(name) && !(scope.flags & _scopeflags.ScopeFlag.SIMPLE_CATCH && scope.lexical.values().next().value === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.has(name);
}
checkLocalExport(id) {
const {
@@ -140,7 +140,7 @@ class ScopeHandler {
const {
flags
} = this.scopeStack[i];
if (flags & _scopeflags.SCOPE_VAR) {
if (flags & _scopeflags.ScopeFlag.VAR) {
return flags;
}
}
@@ -150,7 +150,7 @@ class ScopeHandler {
const {
flags
} = this.scopeStack[i];
if (flags & (_scopeflags.SCOPE_VAR | _scopeflags.SCOPE_CLASS) && !(flags & _scopeflags.SCOPE_ARROW)) {
if (flags & (_scopeflags.ScopeFlag.VAR | _scopeflags.ScopeFlag.CLASS) && !(flags & _scopeflags.ScopeFlag.ARROW)) {
return flags;
}
}
+60 -99
View File
@@ -3,104 +3,65 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.SCOPE_VAR = exports.SCOPE_TS_MODULE = exports.SCOPE_SUPER = exports.SCOPE_STATIC_BLOCK = exports.SCOPE_SIMPLE_CATCH = exports.SCOPE_PROGRAM = exports.SCOPE_OTHER = exports.SCOPE_FUNCTION = exports.SCOPE_DIRECT_SUPER = exports.SCOPE_CLASS = exports.SCOPE_ARROW = exports.CLASS_ELEMENT_STATIC_SETTER = exports.CLASS_ELEMENT_STATIC_GETTER = exports.CLASS_ELEMENT_OTHER = exports.CLASS_ELEMENT_KIND_SETTER = exports.CLASS_ELEMENT_KIND_GETTER = exports.CLASS_ELEMENT_KIND_ACCESSOR = exports.CLASS_ELEMENT_INSTANCE_SETTER = exports.CLASS_ELEMENT_INSTANCE_GETTER = exports.CLASS_ELEMENT_FLAG_STATIC = exports.BIND_VAR = exports.BIND_TS_TYPE_IMPORT = exports.BIND_TS_TYPE = exports.BIND_TS_NAMESPACE = exports.BIND_TS_INTERFACE = exports.BIND_TS_ENUM = exports.BIND_TS_CONST_ENUM = exports.BIND_TS_AMBIENT = exports.BIND_SCOPE_VAR = exports.BIND_SCOPE_OUTSIDE = exports.BIND_SCOPE_LEXICAL = exports.BIND_SCOPE_FUNCTION = exports.BIND_OUTSIDE = exports.BIND_NONE = exports.BIND_LEXICAL = exports.BIND_KIND_VALUE = exports.BIND_KIND_TYPE = exports.BIND_FUNCTION = exports.BIND_FLOW_DECLARE_FN = exports.BIND_FLAGS_TS_IMPORT = exports.BIND_FLAGS_TS_EXPORT_ONLY = exports.BIND_FLAGS_TS_ENUM = exports.BIND_FLAGS_TS_CONST_ENUM = exports.BIND_FLAGS_NO_LET_IN_LEXICAL = exports.BIND_FLAGS_NONE = exports.BIND_FLAGS_FLOW_DECLARE_FN = exports.BIND_FLAGS_CLASS = exports.BIND_CLASS = exports.BIND_CATCH_PARAM = void 0;
const SCOPE_OTHER = 0b000000000,
SCOPE_PROGRAM = 0b000000001,
SCOPE_FUNCTION = 0b000000010,
SCOPE_ARROW = 0b000000100,
SCOPE_SIMPLE_CATCH = 0b000001000,
SCOPE_SUPER = 0b000010000,
SCOPE_DIRECT_SUPER = 0b000100000,
SCOPE_CLASS = 0b001000000,
SCOPE_STATIC_BLOCK = 0b010000000,
SCOPE_TS_MODULE = 0b100000000,
SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_STATIC_BLOCK | SCOPE_TS_MODULE;
exports.SCOPE_VAR = SCOPE_VAR;
exports.SCOPE_TS_MODULE = SCOPE_TS_MODULE;
exports.SCOPE_STATIC_BLOCK = SCOPE_STATIC_BLOCK;
exports.SCOPE_CLASS = SCOPE_CLASS;
exports.SCOPE_DIRECT_SUPER = SCOPE_DIRECT_SUPER;
exports.SCOPE_SUPER = SCOPE_SUPER;
exports.SCOPE_SIMPLE_CATCH = SCOPE_SIMPLE_CATCH;
exports.SCOPE_ARROW = SCOPE_ARROW;
exports.SCOPE_FUNCTION = SCOPE_FUNCTION;
exports.SCOPE_PROGRAM = SCOPE_PROGRAM;
exports.SCOPE_OTHER = SCOPE_OTHER;
const BIND_KIND_VALUE = 0b0000000000001,
BIND_KIND_TYPE = 0b0000000000010,
BIND_SCOPE_VAR = 0b0000000000100,
BIND_SCOPE_LEXICAL = 0b0000000001000,
BIND_SCOPE_FUNCTION = 0b0000000010000,
BIND_SCOPE_OUTSIDE = 0b0000000100000,
BIND_FLAGS_NONE = 0b00000001000000,
BIND_FLAGS_CLASS = 0b00000010000000,
BIND_FLAGS_TS_ENUM = 0b00000100000000,
BIND_FLAGS_TS_CONST_ENUM = 0b00001000000000,
BIND_FLAGS_TS_EXPORT_ONLY = 0b00010000000000,
BIND_FLAGS_FLOW_DECLARE_FN = 0b00100000000000,
BIND_FLAGS_TS_IMPORT = 0b01000000000000,
BIND_FLAGS_NO_LET_IN_LEXICAL = 0b10000000000000;
exports.BIND_FLAGS_NO_LET_IN_LEXICAL = BIND_FLAGS_NO_LET_IN_LEXICAL;
exports.BIND_FLAGS_TS_IMPORT = BIND_FLAGS_TS_IMPORT;
exports.BIND_FLAGS_FLOW_DECLARE_FN = BIND_FLAGS_FLOW_DECLARE_FN;
exports.BIND_FLAGS_TS_EXPORT_ONLY = BIND_FLAGS_TS_EXPORT_ONLY;
exports.BIND_FLAGS_TS_CONST_ENUM = BIND_FLAGS_TS_CONST_ENUM;
exports.BIND_FLAGS_TS_ENUM = BIND_FLAGS_TS_ENUM;
exports.BIND_FLAGS_CLASS = BIND_FLAGS_CLASS;
exports.BIND_FLAGS_NONE = BIND_FLAGS_NONE;
exports.BIND_SCOPE_OUTSIDE = BIND_SCOPE_OUTSIDE;
exports.BIND_SCOPE_FUNCTION = BIND_SCOPE_FUNCTION;
exports.BIND_SCOPE_LEXICAL = BIND_SCOPE_LEXICAL;
exports.BIND_SCOPE_VAR = BIND_SCOPE_VAR;
exports.BIND_KIND_TYPE = BIND_KIND_TYPE;
exports.BIND_KIND_VALUE = BIND_KIND_VALUE;
const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS | BIND_FLAGS_NO_LET_IN_LEXICAL,
BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | BIND_FLAGS_NO_LET_IN_LEXICAL,
BIND_CATCH_PARAM = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM | BIND_FLAGS_NO_LET_IN_LEXICAL,
BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
BIND_TS_TYPE_IMPORT = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_TS_IMPORT,
BIND_FLOW_DECLARE_FN = BIND_FLAGS_FLOW_DECLARE_FN;
exports.BIND_FLOW_DECLARE_FN = BIND_FLOW_DECLARE_FN;
exports.BIND_TS_TYPE_IMPORT = BIND_TS_TYPE_IMPORT;
exports.BIND_TS_NAMESPACE = BIND_TS_NAMESPACE;
exports.BIND_TS_CONST_ENUM = BIND_TS_CONST_ENUM;
exports.BIND_OUTSIDE = BIND_OUTSIDE;
exports.BIND_NONE = BIND_NONE;
exports.BIND_TS_AMBIENT = BIND_TS_AMBIENT;
exports.BIND_TS_ENUM = BIND_TS_ENUM;
exports.BIND_TS_TYPE = BIND_TS_TYPE;
exports.BIND_TS_INTERFACE = BIND_TS_INTERFACE;
exports.BIND_FUNCTION = BIND_FUNCTION;
exports.BIND_VAR = BIND_VAR;
exports.BIND_CATCH_PARAM = BIND_CATCH_PARAM;
exports.BIND_LEXICAL = BIND_LEXICAL;
exports.BIND_CLASS = BIND_CLASS;
const CLASS_ELEMENT_FLAG_STATIC = 0b100,
CLASS_ELEMENT_KIND_GETTER = 0b010,
CLASS_ELEMENT_KIND_SETTER = 0b001,
CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
exports.CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_ACCESSOR;
exports.CLASS_ELEMENT_KIND_SETTER = CLASS_ELEMENT_KIND_SETTER;
exports.CLASS_ELEMENT_KIND_GETTER = CLASS_ELEMENT_KIND_GETTER;
exports.CLASS_ELEMENT_FLAG_STATIC = CLASS_ELEMENT_FLAG_STATIC;
const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
CLASS_ELEMENT_OTHER = 0;
exports.CLASS_ELEMENT_OTHER = CLASS_ELEMENT_OTHER;
exports.CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_INSTANCE_SETTER;
exports.CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_INSTANCE_GETTER;
exports.CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_STATIC_SETTER;
exports.CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_STATIC_GETTER;
exports.ScopeFlag = exports.ClassElementType = exports.BindingFlag = void 0;
var ScopeFlag = {
OTHER: 0,
PROGRAM: 1,
FUNCTION: 2,
ARROW: 4,
SIMPLE_CATCH: 8,
SUPER: 16,
DIRECT_SUPER: 32,
CLASS: 64,
STATIC_BLOCK: 128,
TS_MODULE: 256,
VAR: 387
};
exports.ScopeFlag = ScopeFlag;
var BindingFlag = {
KIND_VALUE: 1,
KIND_TYPE: 2,
SCOPE_VAR: 4,
SCOPE_LEXICAL: 8,
SCOPE_FUNCTION: 16,
SCOPE_OUTSIDE: 32,
FLAG_NONE: 64,
FLAG_CLASS: 128,
FLAG_TS_ENUM: 256,
FLAG_TS_CONST_ENUM: 512,
FLAG_TS_EXPORT_ONLY: 1024,
FLAG_FLOW_DECLARE_FN: 2048,
FLAG_TS_IMPORT: 4096,
FLAG_NO_LET_IN_LEXICAL: 8192,
TYPE_CLASS: 8331,
TYPE_LEXICAL: 8201,
TYPE_CATCH_PARAM: 9,
TYPE_VAR: 5,
TYPE_FUNCTION: 17,
TYPE_TS_INTERFACE: 130,
TYPE_TS_TYPE: 2,
TYPE_TS_ENUM: 8459,
TYPE_TS_AMBIENT: 1024,
TYPE_NONE: 64,
TYPE_OUTSIDE: 65,
TYPE_TS_CONST_ENUM: 8971,
TYPE_TS_NAMESPACE: 1024,
TYPE_TS_TYPE_IMPORT: 4098,
TYPE_TS_VALUE_IMPORT: 4096,
TYPE_FLOW_DECLARE_FN: 2048
};
exports.BindingFlag = BindingFlag;
var ClassElementType = {
OTHER: 0,
FLAG_STATIC: 4,
KIND_GETTER: 2,
KIND_SETTER: 1,
KIND_ACCESSOR: 3,
STATIC_GETTER: 6,
STATIC_SETTER: 5,
INSTANCE_GETTER: 2,
INSTANCE_SETTER: 1
};
exports.ClassElementType = ClassElementType;
//# sourceMappingURL=scopeflags.js.map
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@babel/parser",
"version": "7.22.7",
"version": "7.22.10",
"description": "A JavaScript parser",
"author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-parser",
@@ -34,9 +34,9 @@
"node": ">=6.0.0"
},
"devDependencies": {
"@babel/code-frame": "^7.22.5",
"@babel/code-frame": "^7.22.10",
"@babel/helper-check-duplicate-nodes": "^7.22.5",
"@babel/helper-fixtures": "^7.22.6",
"@babel/helper-fixtures": "^7.22.9",
"@babel/helper-string-parser": "^7.22.5",
"@babel/helper-validator-identifier": "^7.22.5",
"charcodes": "^0.2.0"
+24 -3
View File
@@ -6,9 +6,11 @@ Object.defineProperty(exports, "__esModule", {
exports.clear = clear;
exports.clearPath = clearPath;
exports.clearScope = clearScope;
exports.getCachedPaths = getCachedPaths;
exports.getOrCreateCachedPaths = getOrCreateCachedPaths;
exports.scope = exports.path = void 0;
let path = new WeakMap();
exports.path = path;
let pathsCache = new WeakMap();
exports.path = pathsCache;
let scope = new WeakMap();
exports.scope = scope;
function clear() {
@@ -16,10 +18,29 @@ function clear() {
clearScope();
}
function clearPath() {
exports.path = path = new WeakMap();
exports.path = pathsCache = new WeakMap();
}
function clearScope() {
exports.scope = scope = new WeakMap();
}
const nullHub = Object.freeze({});
function getCachedPaths(hub, parent) {
var _pathsCache$get, _hub;
{
hub = null;
}
return (_pathsCache$get = pathsCache.get((_hub = hub) != null ? _hub : nullHub)) == null ? void 0 : _pathsCache$get.get(parent);
}
function getOrCreateCachedPaths(hub, parent) {
var _hub2, _hub3;
{
hub = null;
}
let parents = pathsCache.get((_hub2 = hub) != null ? _hub2 : nullHub);
if (!parents) pathsCache.set((_hub3 = hub) != null ? _hub3 : nullHub, parents = new WeakMap());
let paths = parents.get(parent);
if (!paths) parents.set(parent, paths = new Map());
return paths;
}
//# sourceMappingURL=cache.js.map
+5 -3
View File
@@ -35,18 +35,21 @@ const {
removeProperties,
traverseFast
} = _t;
function traverse(parent, opts = {}, scope, state, parentPath) {
function traverse(parent, opts = {}, scope, state, parentPath, visitSelf) {
if (!parent) return;
if (!opts.noScope && !scope) {
if (parent.type !== "Program" && parent.type !== "File") {
throw new Error("You must pass a scope and parentPath unless traversing a Program/File. " + `Instead of that you tried to traverse a ${parent.type} node without ` + "passing scope and parentPath.");
}
}
if (!parentPath && visitSelf) {
throw new Error("visitSelf can only be used when providing a NodePath.");
}
if (!VISITOR_KEYS[parent.type]) {
return;
}
visitors.explode(opts);
(0, _traverseNode.traverseNode)(parent, opts, scope, state, parentPath);
(0, _traverseNode.traverseNode)(parent, opts, scope, state, parentPath, null, visitSelf);
}
var _default = traverse;
exports.default = _default;
@@ -62,7 +65,6 @@ traverse.node = function (node, opts, scope, state, path, skipKeys) {
};
traverse.clearNode = function (node, opts) {
removeProperties(node, opts);
cache.path.delete(node);
};
traverse.removeProperties = function (tree, opts) {
traverseFast(tree, traverse.clearNode, opts);
@@ -107,10 +107,7 @@ function setType(path, type) {
function arrowFunctionToExpression({
allowInsertArrow = true,
allowInsertArrowWithRest = allowInsertArrow,
noNewArrows = !(() => {
var _arguments$;
return (_arguments$ = arguments[0]) == null ? void 0 : _arguments$.specCompliant;
})()
noNewArrows = !(_arguments$ => (_arguments$ = arguments[0]) == null ? void 0 : _arguments$.specCompliant)()
} = {}) {
if (!this.isArrowFunctionExpression()) {
throw this.buildCodeFrameError("Cannot convert non-arrow function to a function expression.");
+2 -6
View File
@@ -10,7 +10,7 @@ var _index = require("../index");
var _scope = require("../scope");
var _t = require("@babel/types");
var t = _t;
var _cache = require("../cache");
var cache = require("../cache");
var _generator = require("@babel/generator");
var NodePath_ancestry = require("./ancestry");
var NodePath_inference = require("./inference");
@@ -68,11 +68,7 @@ class NodePath {
throw new Error("To get a node path the parent needs to exist");
}
const targetNode = container[key];
let paths = _cache.path.get(parent);
if (!paths) {
paths = new Map();
_cache.path.set(parent, paths);
}
const paths = cache.getOrCreateCachedPaths(hub, parent);
let path = paths.get(targetNode);
if (!path) {
path = new NodePath(hub, parent);
@@ -5,12 +5,10 @@ Object.defineProperty(exports, "__esModule", {
});
exports.isBindingIdentifier = isBindingIdentifier;
exports.isBlockScoped = isBlockScoped;
exports.isExistentialTypeParam = isExistentialTypeParam;
exports.isExpression = isExpression;
exports.isFlow = isFlow;
exports.isForAwaitStatement = isForAwaitStatement;
exports.isGenerated = isGenerated;
exports.isNumericLiteralTypeAnnotation = isNumericLiteralTypeAnnotation;
exports.isPure = isPure;
exports.isReferenced = isReferenced;
exports.isReferencedIdentifier = isReferencedIdentifier;
@@ -151,11 +149,15 @@ function isForAwaitStatement() {
await: true
});
}
function isExistentialTypeParam() {
throw new Error("`path.isExistentialTypeParam` has been renamed to `path.isExistsTypeAnnotation()` in Babel 7.");
}
function isNumericLiteralTypeAnnotation() {
throw new Error("`path.isNumericLiteralTypeAnnotation()` has been renamed to `path.isNumberLiteralTypeAnnotation()` in Babel 7.");
{
{
exports.isExistentialTypeParam = function isExistentialTypeParam() {
throw new Error("`path.isExistentialTypeParam` has been renamed to `path.isExistsTypeAnnotation()` in Babel 7.");
};
exports.isNumericLiteralTypeAnnotation = function isNumericLiteralTypeAnnotation() {
throw new Error("`path.isNumericLiteralTypeAnnotation()` has been renamed to `path.isNumberLiteralTypeAnnotation()` in Babel 7.");
};
}
}
//# sourceMappingURL=virtual-types-validator.js.map
@@ -62,10 +62,11 @@ function _containerInsert(from, nodes) {
const paths = [];
this.container.splice(from, 0, ...nodes);
for (let i = 0; i < nodes.length; i++) {
var _this$context;
const to = from + i;
const path = this.getSibling(to);
paths.push(path);
if (this.context && this.context.queue) {
if ((_this$context = this.context) != null && _this$context.queue) {
path.pushContext(this.context);
}
}
@@ -158,7 +159,7 @@ function insertAfter(nodes_) {
}
function updateSiblingKeys(fromIndex, incrementBy) {
if (!this.parent) return;
const paths = _cache.path.get(this.parent);
const paths = (0, _cache.getCachedPaths)(this.hub, this.parent) || [];
for (const [, path] of paths) {
if (typeof path.key === "number" && path.key >= fromIndex) {
path.key += incrementBy;
@@ -46,7 +46,9 @@ function _remove() {
}
function _markRemoved() {
this._traverseFlags |= _index.SHOULD_SKIP | _index.REMOVED;
if (this.parent) _cache.path.get(this.parent).delete(this.node);
if (this.parent) {
(0, _cache.getCachedPaths)(this.hub, this.parent).delete(this.node);
}
this.node = null;
}
function _assertUnremoved() {
@@ -39,12 +39,12 @@ const {
yieldExpression
} = _t;
function replaceWithMultiple(nodes) {
var _pathCache$get;
var _getCachedPaths;
this.resync();
nodes = this._verifyNodeList(nodes);
inheritLeadingComments(nodes[0], this.node);
inheritTrailingComments(nodes[nodes.length - 1], this.node);
(_pathCache$get = _cache.path.get(this.parent)) == null ? void 0 : _pathCache$get.delete(this.node);
(_getCachedPaths = (0, _cache.getCachedPaths)(this.hub, this.parent)) == null ? void 0 : _getCachedPaths.delete(this.node);
this.node = this.container[this.key] = null;
const paths = this.insertAfter(nodes);
if (this.node) {
@@ -122,7 +122,7 @@ function replaceWith(replacementPath) {
return [nodePath ? this.get(nodePath) : this];
}
function _replaceWith(node) {
var _pathCache$get2;
var _getCachedPaths2;
if (!this.container) {
throw new ReferenceError("Container is falsy");
}
@@ -132,7 +132,7 @@ function _replaceWith(node) {
validate(this.parent, this.key, node);
}
this.debug(`Replace with ${node == null ? void 0 : node.type}`);
(_pathCache$get2 = _cache.path.get(this.parent)) == null ? void 0 : _pathCache$get2.set(node, this).delete(this.node);
(_getCachedPaths2 = (0, _cache.getCachedPaths)(this.hub, this.parent)) == null ? void 0 : _getCachedPaths2.set(node, this).delete(this.node);
this.node = this.container[this.key] = node;
}
function replaceExpressionWithStatements(nodes) {
+2 -1
View File
@@ -62,9 +62,10 @@ function gatherNodeParts(node, parts) {
switch (node == null ? void 0 : node.type) {
default:
if (isImportDeclaration(node) || isExportDeclaration(node)) {
var _node$specifiers;
if ((isExportAllDeclaration(node) || isExportNamedDeclaration(node) || isImportDeclaration(node)) && node.source) {
gatherNodeParts(node.source, parts);
} else if ((isExportNamedDeclaration(node) || isImportDeclaration(node)) && node.specifiers && node.specifiers.length) {
} else if ((isExportNamedDeclaration(node) || isImportDeclaration(node)) && (_node$specifiers = node.specifiers) != null && _node$specifiers.length) {
for (const e of node.specifiers) gatherNodeParts(e, parts);
} else if ((isExportDefaultDeclaration(node) || isExportNamedDeclaration(node)) && node.declaration) {
gatherNodeParts(node.declaration, parts);
@@ -9,12 +9,16 @@ var _t = require("@babel/types");
const {
VISITOR_KEYS
} = _t;
function traverseNode(node, opts, scope, state, path, skipKeys) {
function traverseNode(node, opts, scope, state, path, skipKeys, visitSelf) {
const keys = VISITOR_KEYS[node.type];
if (!keys) return false;
const context = new _context.default(scope, opts, state, path);
if (visitSelf) {
if (skipKeys != null && skipKeys[path.parentKey]) return false;
return context.visitQueue([path]);
}
for (const key of keys) {
if (skipKeys && skipKeys[key]) continue;
if (skipKeys != null && skipKeys[key]) continue;
if (context.visit(node, key)) {
return true;
}
+6 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@babel/traverse",
"version": "7.22.8",
"version": "7.22.10",
"description": "The Babel Traverse module maintains the overall tree state, and is responsible for replacing, removing, and adding nodes",
"author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-traverse",
@@ -16,18 +16,19 @@
},
"main": "./lib/index.js",
"dependencies": {
"@babel/code-frame": "^7.22.5",
"@babel/generator": "^7.22.7",
"@babel/code-frame": "^7.22.10",
"@babel/generator": "^7.22.10",
"@babel/helper-environment-visitor": "^7.22.5",
"@babel/helper-function-name": "^7.22.5",
"@babel/helper-hoist-variables": "^7.22.5",
"@babel/helper-split-export-declaration": "^7.22.6",
"@babel/parser": "^7.22.7",
"@babel/types": "^7.22.5",
"@babel/parser": "^7.22.10",
"@babel/types": "^7.22.10",
"debug": "^4.1.0",
"globals": "^11.1.0"
},
"devDependencies": {
"@babel/core": "^7.22.10",
"@babel/helper-plugin-test-runner": "^7.22.5"
},
"engines": {
@@ -449,7 +449,14 @@ defineType("NumericLiteral", {
deprecatedAlias: "NumberLiteral",
fields: {
value: {
validate: (0, _utils.assertValueType)("number")
validate: (0, _utils.chain)((0, _utils.assertValueType)("number"), Object.assign(function (node, key, val) {
if (1 / val < 0 || !Number.isFinite(val)) {
const error = new Error("NumericLiterals must be non-negative finite numbers. " + `You can use t.valueToNode(${val}) instead.`);
{}
}
}, {
type: "number"
}))
}
},
aliases: ["Expression", "Pureish", "Literal", "Immutable"]
@@ -7,6 +7,7 @@ exports.default = isType;
var _definitions = require("../definitions");
function isType(nodeType, targetType) {
if (nodeType === targetType) return true;
if (nodeType == null) return false;
if (_definitions.ALIAS_KEYS[targetType]) return false;
const aliases = _definitions.FLIPPED_ALIAS_KEYS[targetType];
if (aliases) {
+3 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@babel/types",
"version": "7.22.5",
"version": "7.22.10",
"description": "Babel Types is a Lodash-esque utility library for AST nodes",
"author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-types",
@@ -29,9 +29,8 @@
"to-fast-properties": "^2.0.0"
},
"devDependencies": {
"@babel/generator": "^7.22.5",
"@babel/parser": "^7.22.5",
"chalk": "^4.1.0",
"@babel/generator": "^7.22.10",
"@babel/parser": "^7.22.10",
"glob": "^7.2.0"
},
"engines": {
@@ -128,7 +128,7 @@ const inlineTagToAST = ({
* @param {import('./index.js').JsdocBlockWithInline} jsdoc
* @param {import('jsdoc-type-pratt-parser').ParseMode} mode
* @param {object} opts
* @param {boolean} [opts.throwOnTypeParsingErrors=false]
* @param {boolean} [opts.throwOnTypeParsingErrors]
* @returns {JsdocBlock}
*/
const commentParserToESTree = (jsdoc, mode, {
@@ -405,7 +405,7 @@ const commentHandler = settings => {
const ast = commentParserToESTree(jsdoc, mode);
const _ast = /** @type {unknown} */ast;
return esquery.matches( /** @type {import('estree').Node} */
_ast, selector, null, {
_ast, selector, undefined, {
visitorKeys: {
...jsdocTypePrattParser.visitorKeys,
...jsdocVisitorKeys
@@ -563,6 +563,20 @@ const optionalBrackets = /^\[(?<name>[^=]*)=[^\]]*\]/u;
const preserveTypeTokenizer = typeTokenizer('preserve');
const preserveDescriptionTokenizer = descriptionTokenizer('preserve');
const plainNameTokenizer = nameTokenizer();
/**
* Can't import `comment-parser/es6/parser/tokenizers/index.js`,
* so we redefine here.
* @typedef {(spec: import('comment-parser').Spec) =>
* import('comment-parser').Spec} CommentParserTokenizer
*/
/**
* @param {object} [cfg]
* @param {string[]} [cfg.noTypes]
* @param {string[]} [cfg.noNames]
* @returns {CommentParserTokenizer[]}
*/
const getTokenizers = ({
noTypes = defaultNoTypes,
noNames = defaultNoNames
@@ -602,11 +616,11 @@ const getTokenizers = ({
extra.match(/(\s*)([^\r]*)(\r)?/u);
}
if (optionalBrackets.test(name)) {
var _name$match, _name$match$groups;
var _name$match;
name =
/** @type {string} */
/** @type {RegExpMatchArray} */
(_name$match = name.match(optionalBrackets)) === null || _name$match === void 0 ? void 0 : (_name$match$groups = _name$match.groups) === null || _name$match$groups === void 0 ? void 0 : _name$match$groups.name;
(_name$match = name.match(optionalBrackets)) === null || _name$match === void 0 || (_name$match = _name$match.groups) === null || _name$match === void 0 ? void 0 : _name$match.name;
spec.optional = true;
} else {
spec.optional = false;
@@ -639,7 +653,7 @@ const getTokenizers = ({
/**
* Accepts a comment token and converts it into `comment-parser` AST.
* @param {{value: string}} commentNode
* @param {string} [indent=""] Whitespace
* @param {string} [indent] Whitespace
* @returns {import('./index.js').JsdocBlockWithInline}
*/
const parseComment = (commentNode, indent = '') => {
@@ -651,6 +665,7 @@ const parseComment = (commentNode, indent = '') => {
return parseInlineTags(block);
};
/* eslint-disable jsdoc/imports-as-dependencies -- https://github.com/gajus/eslint-plugin-jsdoc/issues/1114 */
/**
* Obtained originally from {@link https://github.com/eslint/eslint/blob/master/lib/util/source-code.js#L313}.
*
@@ -695,8 +710,8 @@ const isCommentToken = token => {
* @returns {import('@typescript-eslint/types').TSESTree.Decorator|undefined}
*/
const getDecorator = node => {
var _node$declaration, _node$declaration$dec, _node$decorators, _node$parent, _node$parent$decorato;
return (node === null || node === void 0 ? void 0 : (_node$declaration = node.declaration) === null || _node$declaration === void 0 ? void 0 : (_node$declaration$dec = _node$declaration.decorators) === null || _node$declaration$dec === void 0 ? void 0 : _node$declaration$dec[0]) || (node === null || node === void 0 ? void 0 : (_node$decorators = node.decorators) === null || _node$decorators === void 0 ? void 0 : _node$decorators[0]) || (node === null || node === void 0 ? void 0 : (_node$parent = node.parent) === null || _node$parent === void 0 ? void 0 : (_node$parent$decorato = _node$parent.decorators) === null || _node$parent$decorato === void 0 ? void 0 : _node$parent$decorato[0]);
var _node$declaration, _node$decorators, _node$parent;
return (node === null || node === void 0 || (_node$declaration = node.declaration) === null || _node$declaration === void 0 || (_node$declaration = _node$declaration.decorators) === null || _node$declaration === void 0 ? void 0 : _node$declaration[0]) || (node === null || node === void 0 || (_node$decorators = node.decorators) === null || _node$decorators === void 0 ? void 0 : _node$decorators[0]) || (node === null || node === void 0 || (_node$parent = node.parent) === null || _node$parent === void 0 || (_node$parent = _node$parent.decorators) === null || _node$parent === void 0 ? void 0 : _node$parent[0]);
};
/**
@@ -1137,7 +1152,7 @@ exports.jsdocVisitorKeys = jsdocVisitorKeys;
exports.parseComment = parseComment;
exports.toCamelCase = toCamelCase;
Object.keys(jsdocTypePrattParser).forEach(function (k) {
if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
enumerable: true,
get: function () { return jsdocTypePrattParser[k]; }
});
+20 -20
View File
@@ -1,6 +1,6 @@
{
"name": "@es-joy/jsdoccomment",
"version": "0.39.4",
"version": "0.40.1",
"author": "Brett Zamir <brettz9@yahoo.com>",
"contributors": [],
"description": "Maintained replacement for ESLint's deprecated SourceCode#getJSDocComment along with other jsdoc utilities",
@@ -43,46 +43,46 @@
"node": ">=16"
},
"dependencies": {
"comment-parser": "1.3.1",
"comment-parser": "1.4.0",
"esquery": "^1.5.0",
"jsdoc-type-pratt-parser": "~4.0.0"
},
"devDependencies": {
"@babel/core": "^7.21.8",
"@babel/core": "^7.22.9",
"@babel/plugin-syntax-class-properties": "^7.12.13",
"@babel/preset-env": "^7.21.5",
"@babel/preset-env": "^7.22.9",
"@brettz9/eslint-plugin": "^1.0.4",
"@rollup/plugin-babel": "^6.0.3",
"@types/chai": "^4.3.5",
"@types/eslint": "^8.37.0",
"@types/esquery": "^1.0.2",
"@types/eslint": "^8.44.1",
"@types/esquery": "^1.5.0",
"@types/estraverse": "^5.1.2",
"@types/estree": "^1.0.1",
"@types/mocha": "^10.0.1",
"@typescript-eslint/types": "^5.59.5",
"c8": "^7.13.0",
"@typescript-eslint/types": "^6.2.1",
"c8": "^8.0.1",
"chai": "^4.3.7",
"eslint": "^8.40.0",
"eslint-config-ash-nazg": "34.12.0",
"eslint-config-standard": "^17.0.0",
"eslint": "^8.46.0",
"eslint-config-ash-nazg": "34.15.0",
"eslint-config-standard": "^17.1.0",
"eslint-plugin-array-func": "^3.1.8",
"eslint-plugin-compat": "^4.1.4",
"eslint-plugin-eslint-comments": "^3.2.0",
"eslint-plugin-html": "^7.1.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-jsdoc": "^44.2.2",
"eslint-plugin-markdown": "^3.0.0",
"eslint-plugin-n": "^15.7.0",
"eslint-plugin-import": "^2.28.0",
"eslint-plugin-jsdoc": "^46.4.5",
"eslint-plugin-markdown": "^3.0.1",
"eslint-plugin-n": "^16.0.1",
"eslint-plugin-no-unsanitized": "^4.0.2",
"eslint-plugin-no-use-extend-native": "^0.5.0",
"eslint-plugin-promise": "^6.1.1",
"eslint-plugin-sonarjs": "^0.19.0",
"eslint-plugin-unicorn": "^47.0.0",
"espree": "^9.5.2",
"eslint-plugin-sonarjs": "^0.20.0",
"eslint-plugin-unicorn": "^48.0.1",
"espree": "^9.6.1",
"estraverse": "^5.3.0",
"mocha": "^10.2.0",
"rollup": "^3.21.6",
"typescript": "^5.0.4"
"rollup": "^3.27.2",
"typescript": "^5.1.6"
},
"scripts": {
"tsc": "tsc",
@@ -31,7 +31,7 @@ const commentHandler = (settings) => {
return esquery.matches(/** @type {import('estree').Node} */ (
_ast
), selector, null, {
), selector, undefined, {
visitorKeys: {
...jsdocTypePrattParserVisitorKeys,
...jsdocVisitorKeys
@@ -128,7 +128,7 @@ const inlineTagToAST = ({text, tag, format, namepathOrURL}) => ({
* @param {import('./index.js').JsdocBlockWithInline} jsdoc
* @param {import('jsdoc-type-pratt-parser').ParseMode} mode
* @param {object} opts
* @param {boolean} [opts.throwOnTypeParsingErrors=false]
* @param {boolean} [opts.throwOnTypeParsingErrors]
* @returns {JsdocBlock}
*/
const commentParserToESTree = (jsdoc, mode, {
@@ -1,3 +1,4 @@
/* eslint-disable jsdoc/imports-as-dependencies -- https://github.com/gajus/eslint-plugin-jsdoc/issues/1114 */
/**
* Obtained originally from {@link https://github.com/eslint/eslint/blob/master/lib/util/source-code.js#L313}.
*
@@ -45,6 +45,19 @@ const preserveTypeTokenizer = typeTokenizer('preserve');
const preserveDescriptionTokenizer = descriptionTokenizer('preserve');
const plainNameTokenizer = nameTokenizer();
/**
* Can't import `comment-parser/es6/parser/tokenizers/index.js`,
* so we redefine here.
* @typedef {(spec: import('comment-parser').Spec) =>
* import('comment-parser').Spec} CommentParserTokenizer
*/
/**
* @param {object} [cfg]
* @param {string[]} [cfg.noTypes]
* @param {string[]} [cfg.noNames]
* @returns {CommentParserTokenizer[]}
*/
const getTokenizers = ({
noTypes = defaultNoTypes,
noNames = defaultNoNames
@@ -130,7 +143,7 @@ const getTokenizers = ({
/**
* Accepts a comment token and converts it into `comment-parser` AST.
* @param {{value: string}} commentNode
* @param {string} [indent=""] Whitespace
* @param {string} [indent] Whitespace
* @returns {import('./index.js').JsdocBlockWithInline}
*/
const parseComment = (commentNode, indent = '') => {
@@ -1,4 +1,3 @@
/**
* @param {RegExpMatchArray & {
* indices: {
@@ -1,7 +1,7 @@
{
"compilerOptions": {
"lib": ["es2022"],
"moduleResolution": "node",
"moduleResolution": "NodeNext",
"module": "NodeNext",
"allowJs": true,
"checkJs": true,
+8 -2
View File
@@ -4153,14 +4153,20 @@ function translateESLintRC(eslintrcConfig, {
if (environments.has(envName)) {
// built-in environments should be defined first
configs.unshift(...translateESLintRC(environments.get(envName), {
configs.unshift(...translateESLintRC({
criteria: eslintrcConfig.criteria,
...environments.get(envName)
}, {
resolveConfigRelativeTo,
resolvePluginsRelativeTo
}));
} else if (pluginEnvironments.has(envName)) {
// if the environment comes from a plugin, it should come after the plugin config
configs.push(...translateESLintRC(pluginEnvironments.get(envName), {
configs.push(...translateESLintRC({
criteria: eslintrcConfig.criteria,
...pluginEnvironments.get(envName)
}, {
resolveConfigRelativeTo,
resolvePluginsRelativeTo
}));
@@ -168,14 +168,20 @@ function translateESLintRC(eslintrcConfig, {
if (environments.has(envName)) {
// built-in environments should be defined first
configs.unshift(...translateESLintRC(environments.get(envName), {
configs.unshift(...translateESLintRC({
criteria: eslintrcConfig.criteria,
...environments.get(envName)
}, {
resolveConfigRelativeTo,
resolvePluginsRelativeTo
}));
} else if (pluginEnvironments.has(envName)) {
// if the environment comes from a plugin, it should come after the plugin config
configs.push(...translateESLintRC(pluginEnvironments.get(envName), {
configs.push(...translateESLintRC({
criteria: eslintrcConfig.criteria,
...pluginEnvironments.get(envName)
}, {
resolveConfigRelativeTo,
resolvePluginsRelativeTo
}));
+9 -9
View File
@@ -1,6 +1,6 @@
{
"name": "@eslint/eslintrc",
"version": "2.1.1",
"version": "2.1.2",
"description": "The legacy ESLintRC config file format for ESLint",
"type": "module",
"main": "./dist/eslintrc.cjs",
@@ -26,16 +26,16 @@
"access": "public"
},
"scripts": {
"prepare": "npm run build",
"build": "rollup -c",
"lint": "eslint . --report-unused-disable-directives",
"fix": "npm run lint -- --fix",
"test": "mocha -R progress -c 'tests/lib/*.cjs' && c8 mocha -R progress -c 'tests/lib/**/*.js'",
"generate-release": "eslint-generate-release",
"generate-alpharelease": "eslint-generate-prerelease alpha",
"generate-betarelease": "eslint-generate-prerelease beta",
"generate-rcrelease": "eslint-generate-prerelease rc",
"publish-release": "eslint-publish-release"
"lint:fix": "npm run lint -- --fix",
"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 -R progress -c 'tests/lib/*.cjs' && c8 mocha -R progress -c 'tests/lib/**/*.js'"
},
"repository": "eslint/eslintrc",
"funding": "https://opencollective.com/eslint",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@eslint/js",
"version": "8.46.0",
"version": "8.47.0",
"description": "ESLint JavaScript language implementation",
"main": "./src/index.js",
"scripts": {},
@@ -1,6 +1,6 @@
{
"name": "@jridgewell/resolve-uri",
"version": "3.1.0",
"version": "3.1.1",
"description": "Resolve a URI relative to an optional base URI",
"keywords": [
"resolve",
@@ -13,7 +13,7 @@
"repository": "https://github.com/jridgewell/resolve-uri",
"main": "dist/resolve-uri.umd.js",
"module": "dist/resolve-uri.mjs",
"typings": "dist/types/resolve-uri.d.ts",
"types": "dist/types/resolve-uri.d.ts",
"exports": {
".": [
{
@@ -1,164 +0,0 @@
const comma = ','.charCodeAt(0);
const semicolon = ';'.charCodeAt(0);
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
const intToChar = new Uint8Array(64); // 64 possible chars.
const charToInt = new Uint8Array(128); // z is 122 in ASCII
for (let i = 0; i < chars.length; i++) {
const c = chars.charCodeAt(i);
intToChar[i] = c;
charToInt[c] = i;
}
// Provide a fallback for older environments.
const td = typeof TextDecoder !== 'undefined'
? /* #__PURE__ */ new TextDecoder()
: typeof Buffer !== 'undefined'
? {
decode(buf) {
const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
return out.toString();
},
}
: {
decode(buf) {
let out = '';
for (let i = 0; i < buf.length; i++) {
out += String.fromCharCode(buf[i]);
}
return out;
},
};
function decode(mappings) {
const state = new Int32Array(5);
const decoded = [];
let index = 0;
do {
const semi = indexOf(mappings, index);
const line = [];
let sorted = true;
let lastCol = 0;
state[0] = 0;
for (let i = index; i < semi; i++) {
let seg;
i = decodeInteger(mappings, i, state, 0); // genColumn
const col = state[0];
if (col < lastCol)
sorted = false;
lastCol = col;
if (hasMoreVlq(mappings, i, semi)) {
i = decodeInteger(mappings, i, state, 1); // sourcesIndex
i = decodeInteger(mappings, i, state, 2); // sourceLine
i = decodeInteger(mappings, i, state, 3); // sourceColumn
if (hasMoreVlq(mappings, i, semi)) {
i = decodeInteger(mappings, i, state, 4); // namesIndex
seg = [col, state[1], state[2], state[3], state[4]];
}
else {
seg = [col, state[1], state[2], state[3]];
}
}
else {
seg = [col];
}
line.push(seg);
}
if (!sorted)
sort(line);
decoded.push(line);
index = semi + 1;
} while (index <= mappings.length);
return decoded;
}
function indexOf(mappings, index) {
const idx = mappings.indexOf(';', index);
return idx === -1 ? mappings.length : idx;
}
function decodeInteger(mappings, pos, state, j) {
let value = 0;
let shift = 0;
let integer = 0;
do {
const c = mappings.charCodeAt(pos++);
integer = charToInt[c];
value |= (integer & 31) << shift;
shift += 5;
} while (integer & 32);
const shouldNegate = value & 1;
value >>>= 1;
if (shouldNegate) {
value = -0x80000000 | -value;
}
state[j] += value;
return pos;
}
function hasMoreVlq(mappings, i, length) {
if (i >= length)
return false;
return mappings.charCodeAt(i) !== comma;
}
function sort(line) {
line.sort(sortComparator);
}
function sortComparator(a, b) {
return a[0] - b[0];
}
function encode(decoded) {
const state = new Int32Array(5);
const bufLength = 1024 * 16;
const subLength = bufLength - 36;
const buf = new Uint8Array(bufLength);
const sub = buf.subarray(0, subLength);
let pos = 0;
let out = '';
for (let i = 0; i < decoded.length; i++) {
const line = decoded[i];
if (i > 0) {
if (pos === bufLength) {
out += td.decode(buf);
pos = 0;
}
buf[pos++] = semicolon;
}
if (line.length === 0)
continue;
state[0] = 0;
for (let j = 0; j < line.length; j++) {
const segment = line[j];
// We can push up to 5 ints, each int can take at most 7 chars, and we
// may push a comma.
if (pos > subLength) {
out += td.decode(sub);
buf.copyWithin(0, subLength, pos);
pos -= subLength;
}
if (j > 0)
buf[pos++] = comma;
pos = encodeInteger(buf, pos, state, segment, 0); // genColumn
if (segment.length === 1)
continue;
pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex
pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine
pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn
if (segment.length === 4)
continue;
pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex
}
}
return out + td.decode(buf.subarray(0, pos));
}
function encodeInteger(buf, pos, state, segment, j) {
const next = segment[j];
let num = next - state[j];
state[j] = next;
num = num < 0 ? (-num << 1) | 1 : num << 1;
do {
let clamped = num & 0b011111;
num >>>= 5;
if (num > 0)
clamped |= 0b100000;
buf[pos++] = intToChar[clamped];
} while (num > 0);
return pos;
}
export { decode, encode };
//# sourceMappingURL=sourcemap-codec.mjs.map
@@ -1,175 +0,0 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.sourcemapCodec = {}));
})(this, (function (exports) { 'use strict';
const comma = ','.charCodeAt(0);
const semicolon = ';'.charCodeAt(0);
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
const intToChar = new Uint8Array(64); // 64 possible chars.
const charToInt = new Uint8Array(128); // z is 122 in ASCII
for (let i = 0; i < chars.length; i++) {
const c = chars.charCodeAt(i);
intToChar[i] = c;
charToInt[c] = i;
}
// Provide a fallback for older environments.
const td = typeof TextDecoder !== 'undefined'
? /* #__PURE__ */ new TextDecoder()
: typeof Buffer !== 'undefined'
? {
decode(buf) {
const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
return out.toString();
},
}
: {
decode(buf) {
let out = '';
for (let i = 0; i < buf.length; i++) {
out += String.fromCharCode(buf[i]);
}
return out;
},
};
function decode(mappings) {
const state = new Int32Array(5);
const decoded = [];
let index = 0;
do {
const semi = indexOf(mappings, index);
const line = [];
let sorted = true;
let lastCol = 0;
state[0] = 0;
for (let i = index; i < semi; i++) {
let seg;
i = decodeInteger(mappings, i, state, 0); // genColumn
const col = state[0];
if (col < lastCol)
sorted = false;
lastCol = col;
if (hasMoreVlq(mappings, i, semi)) {
i = decodeInteger(mappings, i, state, 1); // sourcesIndex
i = decodeInteger(mappings, i, state, 2); // sourceLine
i = decodeInteger(mappings, i, state, 3); // sourceColumn
if (hasMoreVlq(mappings, i, semi)) {
i = decodeInteger(mappings, i, state, 4); // namesIndex
seg = [col, state[1], state[2], state[3], state[4]];
}
else {
seg = [col, state[1], state[2], state[3]];
}
}
else {
seg = [col];
}
line.push(seg);
}
if (!sorted)
sort(line);
decoded.push(line);
index = semi + 1;
} while (index <= mappings.length);
return decoded;
}
function indexOf(mappings, index) {
const idx = mappings.indexOf(';', index);
return idx === -1 ? mappings.length : idx;
}
function decodeInteger(mappings, pos, state, j) {
let value = 0;
let shift = 0;
let integer = 0;
do {
const c = mappings.charCodeAt(pos++);
integer = charToInt[c];
value |= (integer & 31) << shift;
shift += 5;
} while (integer & 32);
const shouldNegate = value & 1;
value >>>= 1;
if (shouldNegate) {
value = -0x80000000 | -value;
}
state[j] += value;
return pos;
}
function hasMoreVlq(mappings, i, length) {
if (i >= length)
return false;
return mappings.charCodeAt(i) !== comma;
}
function sort(line) {
line.sort(sortComparator);
}
function sortComparator(a, b) {
return a[0] - b[0];
}
function encode(decoded) {
const state = new Int32Array(5);
const bufLength = 1024 * 16;
const subLength = bufLength - 36;
const buf = new Uint8Array(bufLength);
const sub = buf.subarray(0, subLength);
let pos = 0;
let out = '';
for (let i = 0; i < decoded.length; i++) {
const line = decoded[i];
if (i > 0) {
if (pos === bufLength) {
out += td.decode(buf);
pos = 0;
}
buf[pos++] = semicolon;
}
if (line.length === 0)
continue;
state[0] = 0;
for (let j = 0; j < line.length; j++) {
const segment = line[j];
// We can push up to 5 ints, each int can take at most 7 chars, and we
// may push a comma.
if (pos > subLength) {
out += td.decode(sub);
buf.copyWithin(0, subLength, pos);
pos -= subLength;
}
if (j > 0)
buf[pos++] = comma;
pos = encodeInteger(buf, pos, state, segment, 0); // genColumn
if (segment.length === 1)
continue;
pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex
pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine
pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn
if (segment.length === 4)
continue;
pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex
}
}
return out + td.decode(buf.subarray(0, pos));
}
function encodeInteger(buf, pos, state, segment, j) {
const next = segment[j];
let num = next - state[j];
state[j] = next;
num = num < 0 ? (-num << 1) | 1 : num << 1;
do {
let clamped = num & 0b011111;
num >>>= 5;
if (num > 0)
clamped |= 0b100000;
buf[pos++] = intToChar[clamped];
} while (num > 0);
return pos;
}
exports.decode = decode;
exports.encode = encode;
Object.defineProperty(exports, '__esModule', { value: true });
}));
//# sourceMappingURL=sourcemap-codec.umd.js.map
@@ -1,75 +0,0 @@
{
"name": "@jridgewell/sourcemap-codec",
"version": "1.4.14",
"description": "Encode/decode sourcemap mappings",
"keywords": [
"sourcemap",
"vlq"
],
"main": "dist/sourcemap-codec.umd.js",
"module": "dist/sourcemap-codec.mjs",
"typings": "dist/types/sourcemap-codec.d.ts",
"files": [
"dist",
"src"
],
"exports": {
".": [
{
"types": "./dist/types/sourcemap-codec.d.ts",
"browser": "./dist/sourcemap-codec.umd.js",
"import": "./dist/sourcemap-codec.mjs",
"require": "./dist/sourcemap-codec.umd.js"
},
"./dist/sourcemap-codec.umd.js"
],
"./package.json": "./package.json"
},
"scripts": {
"benchmark": "run-s build:rollup benchmark:*",
"benchmark:install": "cd benchmark && npm install",
"benchmark:only": "node --expose-gc benchmark/index.js",
"build": "run-s -n build:*",
"build:rollup": "rollup -c rollup.config.js",
"build:ts": "tsc --project tsconfig.build.json",
"lint": "run-s -n lint:*",
"lint:prettier": "npm run test:lint:prettier -- --write",
"lint:ts": "npm run test:lint:ts -- --fix",
"prebuild": "rm -rf dist",
"prepublishOnly": "npm run preversion",
"preversion": "run-s test build",
"pretest": "run-s build:rollup",
"test": "run-s -n test:lint test:only",
"test:debug": "mocha --inspect-brk",
"test:lint": "run-s -n test:lint:*",
"test:lint:prettier": "prettier --check '{src,test}/**/*.ts'",
"test:lint:ts": "eslint '{src,test}/**/*.ts'",
"test:only": "mocha",
"test:coverage": "c8 mocha",
"test:watch": "mocha --watch"
},
"repository": {
"type": "git",
"url": "git+https://github.com/jridgewell/sourcemap-codec.git"
},
"author": "Rich Harris",
"license": "MIT",
"devDependencies": {
"@rollup/plugin-typescript": "8.3.0",
"@types/node": "17.0.15",
"@typescript-eslint/eslint-plugin": "5.10.0",
"@typescript-eslint/parser": "5.10.0",
"benchmark": "2.1.4",
"c8": "7.11.2",
"eslint": "8.7.0",
"eslint-config-prettier": "8.3.0",
"mocha": "9.2.0",
"npm-run-all": "4.1.5",
"prettier": "2.5.1",
"rollup": "2.64.0",
"source-map": "0.6.1",
"source-map-js": "1.0.2",
"sourcemap-codec": "1.4.8",
"typescript": "4.5.4"
}
}
Loaded 100 of 702 files, more files were not shown because too many files have changed in this diff. Show more