tools: add babel-eslint

Create tools/update-babel-eslint.sh script and execute it to do the
first installation of the package.
Update tools/license-builder.sh and execute it to add babel-eslint's
license to our LICENSE file.

PR-URL: https://github.com/nodejs/node/pull/17820
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
This commit is contained in:
Michaël Zasso committed 2018-01-11 09:50:47 +01:00
1 parent 7a52c51e81
commit b043a70201
1318 files changed
+93356

No files matched your search

+26
View File
@@ -1084,6 +1084,32 @@ The externally maintained libraries used by Node.js are:
THE SOFTWARE.
"""
- babel-eslint, located at tools/node_modules/babel-eslint, is licensed as follows:
"""
Copyright (c) 2014-2016 Sebastian McKenzie <sebmck@gmail.com>
MIT License
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.
"""
- gtest, located at deps/gtest, is licensed as follows:
"""
Copyright 2008, Google Inc.
+1
View File
@@ -78,6 +78,7 @@ addlicense "marked" "tools/doc/node_modules/marked" \
addlicense "cpplint.py" "tools/cpplint.py" \
"$(sed -e '/^$/,$d' -e 's/^#$//' -e 's/^# //' ${rootdir}/tools/cpplint.py | tail -n +3)"
addlicense "ESLint" "tools/node_modules/eslint" "$(cat ${rootdir}/tools/node_modules/eslint/LICENSE)"
addlicense "babel-eslint" "tools/node_modules/babel-eslint" "$(cat ${rootdir}/tools/node_modules/babel-eslint/LICENSE)"
addlicense "gtest" "deps/gtest" "$(cat ${rootdir}/deps/gtest/LICENSE)"
# nghttp2
+22
View File
@@ -0,0 +1,22 @@
Copyright (c) 2014-2016 Sebastian McKenzie <sebmck@gmail.com>
MIT License
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.
+102
View File
@@ -0,0 +1,102 @@
# babel-eslint [![npm](https://img.shields.io/npm/v/babel-eslint.svg)](https://www.npmjs.com/package/babel-eslint) [![travis](https://img.shields.io/travis/babel/babel-eslint/master.svg)](https://travis-ci.org/babel/babel-eslint) [![npm-downloads](https://img.shields.io/npm/dm/babel-eslint.svg)](https://www.npmjs.com/package/babel-eslint)
**babel-eslint** allows you to lint **ALL** valid Babel code with the fantastic
[ESLint](https://github.com/eslint/eslint).
### Why Use babel-eslint
You only need to use babel-eslint if you are using types (Flow) or experimental features not supported in ESLint itself yet. Otherwise try the default parser (you don't have to use it just because you are using Babel).
---
> If there is an issue, first check if it can be reproduced with the regular parser or with the latest versions of `eslint` and `babel-eslint`!
For questions and support please visit the [`#discussion`](https://babeljs.slack.com/messages/discussion/) babel slack channel (sign up [here](https://github.com/babel/notes/issues/38)) or eslint [gitter](https://gitter.im/eslint/eslint)!
> Note that the `ecmaFeatures` config property may still be required for ESLint to work properly with features not in ECMAScript 5 by default. Examples are `globalReturn` and `modules`).
## Known Issues
Flow:
> Check out [eslint-plugin-flowtype](https://github.com/gajus/eslint-plugin-flowtype): An `eslint` plugin that makes flow type annotations global variables and marks declarations as used. Solves the problem of false positives with `no-undef` and `no-unused-vars`.
- `no-undef` for global flow types: `ReactElement`, `ReactClass` [#130](https://github.com/babel/babel-eslint/issues/130#issuecomment-111215076)
- Workaround: define types as globals in `.eslintrc` or define types and import them `import type ReactElement from './types'`
- `no-unused-vars/no-undef` with Flow declarations (`declare module A {}`) [#132](https://github.com/babel/babel-eslint/issues/132#issuecomment-112815926)
Modules/strict mode
- `no-unused-vars: [2, {vars: local}]` [#136](https://github.com/babel/babel-eslint/issues/136)
Please check out [eslint-plugin-react](https://github.com/yannickcr/eslint-plugin-react) for React/JSX issues
- `no-unused-vars` with jsx
Please check out [eslint-plugin-babel](https://github.com/babel/eslint-plugin-babel) for other issues
## How does it work?
ESLint allows custom parsers. This is great but some of the syntax nodes that Babel supports
aren't supported by ESLint. When using this plugin, ESLint is monkeypatched and your code is
transformed into code that ESLint can understand. All location info such as line numbers,
columns is also retained so you can track down errors with ease.
Basically `babel-eslint` exports an [`index.js`](/index.js) that a linter can use.
It just needs to export a `parse` method that takes in a string of code and outputs an AST.
## Usage
### Supported ESLint versions
ESLint | babel-eslint
------------ | -------------
3.x | >= 6.x
2.x | >= 6.x
1.x | >= 5.x
### Install
Ensure that you have substituted the correct version lock for `eslint` and `babel-eslint` into this command:
```sh
$ npm install eslint@3.x babel-eslint@7 --save-dev
# or
$ yarn add eslint@3.x babel-eslint@7 -D
```
### Setup
**.eslintrc**
```json
{
"parser": "babel-eslint",
"rules": {
"strict": 0
}
}
```
Check out the [ESLint docs](http://eslint.org/docs/rules/) for all possible rules.
### Configuration
`sourceType` can be set to `'module'`(default) or `'script'` if your code isn't using ECMAScript modules.
`allowImportExportEverywhere` can be set to true to allow import and export declarations to appear anywhere a statement is allowed if your build environment supports that. By default, import and export declarations can only appear at a program's top level.
`codeFrame` can be set to false to disable the code frame in the reporter. This is useful since some eslint formatters don't play well with it.
**.eslintrc**
```json
{
"parser": "babel-eslint",
"parserOptions": {
"sourceType": "module",
"allowImportExportEverywhere": false,
"codeFrame": false
}
}
```
### Run
```sh
$ eslint your-files-here
```
+338
View File
@@ -0,0 +1,338 @@
"use strict";
const t = require("@babel/types");
const escope = require("eslint-scope");
const Definition = require("eslint-scope/lib/definition").Definition;
const OriginalPatternVisitor = require("eslint-scope/lib/pattern-visitor");
const OriginalReferencer = require("eslint-scope/lib/referencer");
const fallback = require("eslint-visitor-keys").getKeys;
const childVisitorKeys = require("./visitor-keys");
const flowFlippedAliasKeys = t.FLIPPED_ALIAS_KEYS.Flow.concat([
"ArrayPattern",
"ClassDeclaration",
"ClassExpression",
"FunctionDeclaration",
"FunctionExpression",
"Identifier",
"ObjectPattern",
"RestElement",
]);
const visitorKeysMap = Object.keys(t.VISITOR_KEYS).reduce(function(acc, key) {
const value = t.VISITOR_KEYS[key];
if (flowFlippedAliasKeys.indexOf(value) === -1) {
acc[key] = value;
}
return acc;
}, {});
const propertyTypes = {
// loops
callProperties: { type: "loop", values: ["value"] },
indexers: { type: "loop", values: ["key", "value"] },
properties: { type: "loop", values: ["argument", "value"] },
types: { type: "loop" },
params: { type: "loop" },
// single property
argument: { type: "single" },
elementType: { type: "single" },
qualification: { type: "single" },
rest: { type: "single" },
returnType: { type: "single" },
// others
typeAnnotation: { type: "typeAnnotation" },
typeParameters: { type: "typeParameters" },
id: { type: "id" },
};
class PatternVisitor extends OriginalPatternVisitor {
ArrayPattern(node) {
node.elements.forEach(this.visit, this);
}
ObjectPattern(node) {
node.properties.forEach(this.visit, this);
}
}
class Referencer extends OriginalReferencer {
// inherits.
visitPattern(node, options, callback) {
if (!node) {
return;
}
// Visit type annotations.
this._checkIdentifierOrVisit(node.typeAnnotation);
if (t.isAssignmentPattern(node)) {
this._checkIdentifierOrVisit(node.left.typeAnnotation);
}
// Overwrite `super.visitPattern(node, options, callback)` in order to not visit `ArrayPattern#typeAnnotation` and `ObjectPattern#typeAnnotation`.
if (typeof options === "function") {
callback = options;
options = { processRightHandNodes: false };
}
const visitor = new PatternVisitor(this.options, node, callback);
visitor.visit(node);
// Process the right hand nodes recursively.
if (options.processRightHandNodes) {
visitor.rightHandNodes.forEach(this.visit, this);
}
}
// inherits.
visitClass(node) {
// Decorators.
this._visitArray(node.decorators);
// Flow type parameters.
const typeParamScope = this._nestTypeParamScope(node);
// Flow super types.
this._visitTypeAnnotation(node.implements);
this._visitTypeAnnotation(
node.superTypeParameters && node.superTypeParameters.params
);
// Basic.
super.visitClass(node);
// Close the type parameter scope.
if (typeParamScope) {
this.close(node);
}
}
// inherits.
visitFunction(node) {
const typeParamScope = this._nestTypeParamScope(node);
// Flow return types.
this._checkIdentifierOrVisit(node.returnType);
// Basic.
super.visitFunction(node);
// Close the type parameter scope.
if (typeParamScope) {
this.close(node);
}
}
// inherits.
visitProperty(node) {
if (node.value && node.value.type === "TypeCastExpression") {
this._visitTypeAnnotation(node.value);
}
this._visitArray(node.decorators);
super.visitProperty(node);
}
InterfaceDeclaration(node) {
this._createScopeVariable(node, node.id);
const typeParamScope = this._nestTypeParamScope(node);
// TODO: Handle mixins
this._visitArray(node.extends);
this.visit(node.body);
if (typeParamScope) {
this.close(node);
}
}
TypeAlias(node) {
this._createScopeVariable(node, node.id);
const typeParamScope = this._nestTypeParamScope(node);
this.visit(node.right);
if (typeParamScope) {
this.close(node);
}
}
ClassProperty(node) {
this._visitClassProperty(node);
}
ClassPrivateProperty(node) {
this._visitClassProperty(node);
}
DeclareModule(node) {
this._visitDeclareX(node);
}
DeclareFunction(node) {
this._visitDeclareX(node);
}
DeclareVariable(node) {
this._visitDeclareX(node);
}
DeclareClass(node) {
this._visitDeclareX(node);
}
_visitClassProperty(node) {
this._visitTypeAnnotation(node.typeAnnotation);
this.visitProperty(node);
}
_visitDeclareX(node) {
if (node.id) {
this._createScopeVariable(node, node.id);
}
const typeParamScope = this._nestTypeParamScope(node);
if (typeParamScope) {
this.close(node);
}
}
_createScopeVariable(node, name) {
this.currentScope().variableScope.__define(
name,
new Definition("Variable", name, node, null, null, null)
);
}
_nestTypeParamScope(node) {
if (!node.typeParameters) {
return null;
}
const parentScope = this.scopeManager.__currentScope;
const scope = new escope.Scope(
this.scopeManager,
"type-parameters",
parentScope,
node,
false
);
this.scopeManager.__nestScope(scope);
for (let j = 0; j < node.typeParameters.params.length; j++) {
const name = node.typeParameters.params[j];
scope.__define(name, new Definition("TypeParameter", name, name));
if (name.typeAnnotation) {
this._checkIdentifierOrVisit(name);
}
}
scope.__define = function() {
return parentScope.__define.apply(parentScope, arguments);
};
return scope;
}
_visitTypeAnnotation(node) {
if (!node) {
return;
}
if (Array.isArray(node)) {
node.forEach(this._visitTypeAnnotation, this);
return;
}
// get property to check (params, id, etc...)
const visitorValues = visitorKeysMap[node.type];
if (!visitorValues) {
return;
}
// can have multiple properties
for (let i = 0; i < visitorValues.length; i++) {
const visitorValue = visitorValues[i];
const propertyType = propertyTypes[visitorValue];
const nodeProperty = node[visitorValue];
// check if property or type is defined
if (propertyType == null || nodeProperty == null) {
continue;
}
if (propertyType.type === "loop") {
for (let j = 0; j < nodeProperty.length; j++) {
if (Array.isArray(propertyType.values)) {
for (let k = 0; k < propertyType.values.length; k++) {
const loopPropertyNode = nodeProperty[j][propertyType.values[k]];
if (loopPropertyNode) {
this._checkIdentifierOrVisit(loopPropertyNode);
}
}
} else {
this._checkIdentifierOrVisit(nodeProperty[j]);
}
}
} else if (propertyType.type === "single") {
this._checkIdentifierOrVisit(nodeProperty);
} else if (propertyType.type === "typeAnnotation") {
this._visitTypeAnnotation(node.typeAnnotation);
} else if (propertyType.type === "typeParameters") {
for (let l = 0; l < node.typeParameters.params.length; l++) {
this._checkIdentifierOrVisit(node.typeParameters.params[l]);
}
} else if (propertyType.type === "id") {
if (node.id.type === "Identifier") {
this._checkIdentifierOrVisit(node.id);
} else {
this._visitTypeAnnotation(node.id);
}
}
}
}
_checkIdentifierOrVisit(node) {
if (node && node.typeAnnotation) {
this._visitTypeAnnotation(node.typeAnnotation);
} else if (node && node.type === "Identifier") {
this.visit(node);
} else {
this._visitTypeAnnotation(node);
}
}
_visitArray(nodeList) {
if (nodeList) {
for (const node of nodeList) {
this.visit(node);
}
}
}
}
module.exports = function(ast, parserOptions) {
const options = {
ignoreEval: true,
optimistic: false,
directive: false,
nodejsScope:
ast.sourceType === "script" &&
(parserOptions.ecmaFeatures &&
parserOptions.ecmaFeatures.globalReturn) === true,
impliedStrict: false,
sourceType: ast.sourceType,
ecmaVersion: parserOptions.ecmaVersion || 2018,
fallback,
};
if (OriginalReferencer._babelEslintPatched) {
require("./patch-eslint-scope")(parserOptions);
return escope.analyze(ast, options);
}
options.childVisitorKeys = childVisitorKeys;
const scopeManager = new escope.ScopeManager(options);
const referencer = new Referencer(options, scopeManager);
referencer.visit(ast);
return scopeManager;
};
@@ -0,0 +1,59 @@
"use strict";
// comment fixes
module.exports = function(ast, comments, tokens) {
if (comments.length) {
var firstComment = comments[0];
var lastComment = comments[comments.length - 1];
// fixup program start
if (!tokens.length) {
// if no tokens, the program starts at the end of the last comment
ast.start = lastComment.end;
ast.loc.start.line = lastComment.loc.end.line;
ast.loc.start.column = lastComment.loc.end.column;
if (ast.leadingComments === null && ast.innerComments.length) {
ast.leadingComments = ast.innerComments;
}
} else if (firstComment.start < tokens[0].start) {
// if there are comments before the first token, the program starts at the first token
var token = tokens[0];
// ast.start = token.start;
// ast.loc.start.line = token.loc.start.line;
// ast.loc.start.column = token.loc.start.column;
// estraverse do not put leading comments on first node when the comment
// appear before the first token
if (ast.body.length) {
var node = ast.body[0];
node.leadingComments = [];
var firstTokenStart = token.start;
var len = comments.length;
for (var i = 0; i < len && comments[i].start < firstTokenStart; i++) {
node.leadingComments.push(comments[i]);
}
}
}
// fixup program end
if (tokens.length) {
var lastToken = tokens[tokens.length - 1];
if (lastComment.end > lastToken.end) {
// If there is a comment after the last token, the program ends at the
// last token and not the comment
// ast.end = lastToken.end;
ast.range[1] = lastToken.end;
ast.loc.end.line = lastToken.loc.end.line;
ast.loc.end.column = lastToken.loc.end.column;
}
}
} else {
if (!tokens.length) {
ast.loc.start.line = 1;
ast.loc.end.line = 1;
}
}
if (ast.body && ast.body.length > 0) {
ast.loc.start.line = ast.body[0].loc.start.line;
ast.range[0] = ast.body[0].start;
}
};
@@ -0,0 +1,17 @@
"use strict";
module.exports = function(comments) {
for (var i = 0; i < comments.length; i++) {
var comment = comments[i];
if (comment.type === "CommentBlock") {
comment.type = "Block";
} else if (comment.type === "CommentLine") {
comment.type = "Line";
}
// sometimes comments don't get ranges computed,
// even with options.ranges === true
if (!comment.range) {
comment.range = [comment.start, comment.end];
}
}
};
@@ -0,0 +1,99 @@
"use strict";
module.exports = function(tokens, tt) {
var startingToken = 0;
var currentToken = 0;
var numBraces = 0; // track use of {}
var numBackQuotes = 0; // track number of nested templates
function isBackQuote(token) {
return tokens[token].type === tt.backQuote;
}
function isTemplateStarter(token) {
return (
isBackQuote(token) ||
// only can be a template starter when in a template already
(tokens[token].type === tt.braceR && numBackQuotes > 0)
);
}
function isTemplateEnder(token) {
return isBackQuote(token) || tokens[token].type === tt.dollarBraceL;
}
// append the values between start and end
function createTemplateValue(start, end) {
var value = "";
while (start <= end) {
if (tokens[start].value) {
value += tokens[start].value;
} else if (tokens[start].type !== tt.template) {
value += tokens[start].type.label;
}
start++;
}
return value;
}
// create Template token
function replaceWithTemplateType(start, end) {
var templateToken = {
type: "Template",
value: createTemplateValue(start, end),
start: tokens[start].start,
end: tokens[end].end,
loc: {
start: tokens[start].loc.start,
end: tokens[end].loc.end,
},
};
// put new token in place of old tokens
tokens.splice(start, end - start + 1, templateToken);
}
function trackNumBraces(token) {
if (tokens[token].type === tt.braceL) {
numBraces++;
} else if (tokens[token].type === tt.braceR) {
numBraces--;
}
}
while (startingToken < tokens.length) {
// template start: check if ` or }
if (isTemplateStarter(startingToken) && numBraces === 0) {
if (isBackQuote(startingToken)) {
numBackQuotes++;
}
currentToken = startingToken + 1;
// check if token after template start is "template"
if (
currentToken >= tokens.length - 1 ||
tokens[currentToken].type !== tt.template
) {
break;
}
// template end: find ` or ${
while (!isTemplateEnder(currentToken)) {
if (currentToken >= tokens.length - 1) {
break;
}
currentToken++;
}
if (isBackQuote(currentToken)) {
numBackQuotes--;
}
// template start and end found: create new token
replaceWithTemplateType(startingToken, currentToken);
} else if (numBackQuotes > 0) {
trackNumBraces(startingToken);
}
startingToken++;
}
};
+35
View File
@@ -0,0 +1,35 @@
"use strict";
var attachComments = require("./attachComments");
var convertComments = require("./convertComments");
var toTokens = require("./toTokens");
var toAST = require("./toAST");
module.exports = function(ast, traverse, tt, code) {
// remove EOF token, eslint doesn't use this for anything and it interferes
// with some rules see https://github.com/babel/babel-eslint/issues/2
// todo: find a more elegant way to do this
ast.tokens.pop();
// convert tokens
ast.tokens = toTokens(ast.tokens, tt, code);
// add comments
convertComments(ast.comments);
// transform esprima and acorn divergent nodes
toAST(ast, traverse, code);
// ast.program.tokens = ast.tokens;
// ast.program.comments = ast.comments;
// ast = ast.program;
// remove File
ast.type = "Program";
ast.sourceType = ast.program.sourceType;
ast.directives = ast.program.directives;
ast.body = ast.program.body;
delete ast.program;
attachComments(ast, ast.comments, ast.tokens);
};
+118
View File
@@ -0,0 +1,118 @@
"use strict";
var t = require("@babel/types");
var convertComments = require("./convertComments");
module.exports = function(ast, traverse, code) {
var state = { source: code };
// Monkey patch visitor keys in order to be able to traverse the estree nodes
t.VISITOR_KEYS.Property = t.VISITOR_KEYS.ObjectProperty;
t.VISITOR_KEYS.MethodDefinition = [
"key",
"value",
"decorators",
"returnType",
"typeParameters",
];
traverse(ast, astTransformVisitor, null, state);
delete t.VISITOR_KEYS.Property;
delete t.VISITOR_KEYS.MethodDefinition;
};
var astTransformVisitor = {
noScope: true,
enter(path) {
var node = path.node;
// private var to track original node type
node._babelType = node.type;
if (node.innerComments) {
node.trailingComments = node.innerComments;
delete node.innerComments;
}
if (node.trailingComments) {
convertComments(node.trailingComments);
}
if (node.leadingComments) {
convertComments(node.leadingComments);
}
},
exit(path) {
var node = path.node;
if (path.isJSXText()) {
node.type = "Literal";
}
if (
path.isRestElement() &&
path.parent &&
path.parent.type === "ObjectPattern"
) {
node.type = "ExperimentalRestProperty";
}
if (
path.isSpreadElement() &&
path.parent &&
path.parent.type === "ObjectExpression"
) {
node.type = "ExperimentalSpreadProperty";
}
if (path.isTypeParameter()) {
node.type = "Identifier";
node.typeAnnotation = node.bound;
delete node.bound;
}
// flow: prevent "no-undef"
// for "Component" in: "let x: React.Component"
if (path.isQualifiedTypeIdentifier()) {
delete node.id;
}
// for "b" in: "var a: { b: Foo }"
if (path.isObjectTypeProperty()) {
delete node.key;
}
// for "indexer" in: "var a: {[indexer: string]: number}"
if (path.isObjectTypeIndexer()) {
delete node.id;
}
// for "param" in: "var a: { func(param: Foo): Bar };"
if (path.isFunctionTypeParam()) {
delete node.name;
}
// modules
if (path.isImportDeclaration()) {
delete node.isType;
}
// template string range fixes
if (path.isTemplateLiteral()) {
for (var j = 0; j < node.quasis.length; j++) {
var q = node.quasis[j];
q.range[0] -= 1;
if (q.tail) {
q.range[1] += 1;
} else {
q.range[1] += 2;
}
q.loc.start.column -= 1;
if (q.tail) {
q.loc.end.column += 1;
} else {
q.loc.end.column += 2;
}
}
}
},
};
+80
View File
@@ -0,0 +1,80 @@
"use strict";
module.exports = function(token, tt, source) {
var type = token.type;
token.range = [token.start, token.end];
if (type === tt.name) {
token.type = "Identifier";
} else if (
type === tt.semi ||
type === tt.comma ||
type === tt.parenL ||
type === tt.parenR ||
type === tt.braceL ||
type === tt.braceR ||
type === tt.slash ||
type === tt.dot ||
type === tt.bracketL ||
type === tt.bracketR ||
type === tt.ellipsis ||
type === tt.arrow ||
type === tt.star ||
type === tt.incDec ||
type === tt.colon ||
type === tt.question ||
type === tt.template ||
type === tt.backQuote ||
type === tt.dollarBraceL ||
type === tt.at ||
type === tt.logicalOR ||
type === tt.logicalAND ||
type === tt.bitwiseOR ||
type === tt.bitwiseXOR ||
type === tt.bitwiseAND ||
type === tt.equality ||
type === tt.relational ||
type === tt.bitShift ||
type === tt.plusMin ||
type === tt.modulo ||
type === tt.exponent ||
type === tt.prefix ||
type === tt.doubleColon ||
type.isAssign
) {
token.type = "Punctuator";
if (!token.value) token.value = type.label;
} else if (type === tt.jsxTagStart) {
token.type = "Punctuator";
token.value = "<";
} else if (type === tt.jsxTagEnd) {
token.type = "Punctuator";
token.value = ">";
} else if (type === tt.jsxName) {
token.type = "JSXIdentifier";
} else if (type === tt.jsxText) {
token.type = "JSXText";
} else if (type.keyword === "null") {
token.type = "Null";
} else if (type.keyword === "false" || type.keyword === "true") {
token.type = "Boolean";
} else if (type.keyword) {
token.type = "Keyword";
} else if (type === tt.num) {
token.type = "Numeric";
token.value = source.slice(token.start, token.end);
} else if (type === tt.string) {
token.type = "String";
token.value = source.slice(token.start, token.end);
} else if (type === tt.regexp) {
token.type = "RegularExpression";
var value = token.value;
token.regex = {
pattern: value.pattern,
flags: value.flags,
};
token.value = `/${value.pattern}/${value.flags}`;
}
return token;
};
+19
View File
@@ -0,0 +1,19 @@
"use strict";
var convertTemplateType = require("./convertTemplateType");
var toToken = require("./toToken");
module.exports = function(tokens, tt, code) {
// transform tokens to type "Template"
convertTemplateType(tokens, tt);
var transformedTokens = [];
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (token.type !== "CommentLine" && token.type !== "CommentBlock") {
transformedTokens.push(toToken(token, tt, code));
}
}
return transformedTokens;
};
+22
View File
@@ -0,0 +1,22 @@
"use strict";
exports.parse = function(code, options) {
return exports.parseForESLint(code, options).ast;
};
exports.parseForESLint = function(code, options) {
options = options || {};
options.ecmaVersion = options.ecmaVersion || 2018;
options.sourceType = options.sourceType || "module";
options.allowImportExportEverywhere =
options.allowImportExportEverywhere || false;
if (options.eslintVisitorKeys && options.eslintScopeManager) {
return require("./parse-with-scope")(code, options);
}
return { ast: require("./parse-with-patch")(code, options) };
};
exports.parseNoPatch = function(code, options) {
return require("./parse")(code, options);
};
+9
View File
@@ -0,0 +1,9 @@
"use strict";
var parse = require("./parse");
var patchEscope = require("./patch-eslint-scope");
module.exports = function(code, options) {
patchEscope(options);
return parse(code, options);
};
+12
View File
@@ -0,0 +1,12 @@
"use strict";
const visitorKeys = require("./visitor-keys");
const analyzeScope = require("./analyze-scope");
const parse = require("./parse");
module.exports = function(code, options) {
const ast = parse(code, options);
const scopeManager = analyzeScope(ast, options);
return { ast, scopeManager, visitorKeys };
};
+87
View File
@@ -0,0 +1,87 @@
"use strict";
var babylonToEspree = require("./babylon-to-espree");
var parse = require("babylon").parse;
var tt = require("babylon").tokTypes;
var traverse = require("@babel/traverse").default;
var codeFrameColumns = require("@babel/code-frame").codeFrameColumns;
module.exports = function(code, options) {
var opts = {
codeFrame: options.hasOwnProperty("codeFrame") ? options.codeFrame : true,
sourceType: options.sourceType,
allowImportExportEverywhere: options.allowImportExportEverywhere, // consistent with espree
allowReturnOutsideFunction: true,
allowSuperOutsideMethod: true,
ranges: true,
tokens: true,
plugins: [
"flow",
"jsx",
"estree",
"asyncFunctions",
"asyncGenerators",
"classConstructorCall",
"classProperties",
"decorators",
"doExpressions",
"exponentiationOperator",
"exportDefaultFrom",
"exportNamespaceFrom",
"functionBind",
"functionSent",
"objectRestSpread",
"trailingFunctionCommas",
"dynamicImport",
"numericSeparator",
"optionalChaining",
"importMeta",
"classPrivateProperties",
"bigInt",
"optionalCatchBinding",
"throwExpressions",
"pipelineOperator",
"nullishCoalescingOperator",
],
};
var ast;
try {
ast = parse(code, opts);
} catch (err) {
if (err instanceof SyntaxError) {
err.lineNumber = err.loc.line;
err.column = err.loc.column;
if (opts.codeFrame) {
err.lineNumber = err.loc.line;
err.column = err.loc.column + 1;
// remove trailing "(LINE:COLUMN)" acorn message and add in esprima syntax error message start
err.message =
"Line " +
err.lineNumber +
": " +
err.message.replace(/ \((\d+):(\d+)\)$/, "") +
// add codeframe
"\n\n" +
codeFrameColumns(
code,
{
start: {
line: err.lineNumber,
column: err.column,
},
},
{ highlightCode: true }
);
}
}
throw err;
}
babylonToEspree(ast, traverse, tt, code);
return ast;
};
+370
View File
@@ -0,0 +1,370 @@
"use strict";
var Module = require("module");
var path = require("path");
var t = require("@babel/types");
function getModules() {
try {
// avoid importing a local copy of eslint, try to find a peer dependency
var eslintLoc = Module._resolveFilename("eslint", module.parent);
} catch (err) {
try {
// avoids breaking in jest where module.parent is undefined
eslintLoc = require.resolve("eslint");
} catch (err) {
throw new ReferenceError("couldn't resolve eslint");
}
}
// get modules relative to what eslint will load
var eslintMod = new Module(eslintLoc);
eslintMod.filename = eslintLoc;
eslintMod.paths = Module._nodeModulePaths(path.dirname(eslintLoc));
try {
var escope = eslintMod.require("eslint-scope");
var Definition = eslintMod.require("eslint-scope/lib/definition")
.Definition;
var referencer = eslintMod.require("eslint-scope/lib/referencer");
} catch (err) {
escope = eslintMod.require("escope");
Definition = eslintMod.require("escope/lib/definition").Definition;
referencer = eslintMod.require("escope/lib/referencer");
}
var estraverse = eslintMod.require("estraverse");
if (referencer.__esModule) referencer = referencer.default;
return {
Definition,
escope,
estraverse,
referencer,
};
}
function monkeypatch(modules) {
var Definition = modules.Definition;
var escope = modules.escope;
var estraverse = modules.estraverse;
var referencer = modules.referencer;
Object.assign(estraverse.VisitorKeys, t.VISITOR_KEYS);
estraverse.VisitorKeys.MethodDefinition.push("decorators");
estraverse.VisitorKeys.Property.push("decorators");
// if there are decorators, then visit each
function visitDecorators(node) {
if (!node.decorators) {
return;
}
for (var i = 0; i < node.decorators.length; i++) {
if (node.decorators[i].expression) {
this.visit(node.decorators[i]);
}
}
}
// iterate through part of t.VISITOR_KEYS
var flowFlippedAliasKeys = t.FLIPPED_ALIAS_KEYS.Flow.concat([
"ArrayPattern",
"ClassDeclaration",
"ClassExpression",
"FunctionDeclaration",
"FunctionExpression",
"Identifier",
"ObjectPattern",
"RestElement",
]);
var visitorKeysMap = Object.keys(t.VISITOR_KEYS).reduce(function(acc, key) {
var value = t.VISITOR_KEYS[key];
if (flowFlippedAliasKeys.indexOf(value) === -1) {
acc[key] = value;
}
return acc;
}, {});
var propertyTypes = {
// loops
callProperties: { type: "loop", values: ["value"] },
indexers: { type: "loop", values: ["key", "value"] },
properties: { type: "loop", values: ["argument", "value"] },
types: { type: "loop" },
params: { type: "loop" },
// single property
argument: { type: "single" },
elementType: { type: "single" },
qualification: { type: "single" },
rest: { type: "single" },
returnType: { type: "single" },
// others
typeAnnotation: { type: "typeAnnotation" },
typeParameters: { type: "typeParameters" },
id: { type: "id" },
};
function visitTypeAnnotation(node) {
// get property to check (params, id, etc...)
var visitorValues = visitorKeysMap[node.type];
if (!visitorValues) {
return;
}
// can have multiple properties
for (var i = 0; i < visitorValues.length; i++) {
var visitorValue = visitorValues[i];
var propertyType = propertyTypes[visitorValue];
var nodeProperty = node[visitorValue];
// check if property or type is defined
if (propertyType == null || nodeProperty == null) {
continue;
}
if (propertyType.type === "loop") {
for (var j = 0; j < nodeProperty.length; j++) {
if (Array.isArray(propertyType.values)) {
for (var k = 0; k < propertyType.values.length; k++) {
var loopPropertyNode = nodeProperty[j][propertyType.values[k]];
if (loopPropertyNode) {
checkIdentifierOrVisit.call(this, loopPropertyNode);
}
}
} else {
checkIdentifierOrVisit.call(this, nodeProperty[j]);
}
}
} else if (propertyType.type === "single") {
checkIdentifierOrVisit.call(this, nodeProperty);
} else if (propertyType.type === "typeAnnotation") {
visitTypeAnnotation.call(this, node.typeAnnotation);
} else if (propertyType.type === "typeParameters") {
for (var l = 0; l < node.typeParameters.params.length; l++) {
checkIdentifierOrVisit.call(this, node.typeParameters.params[l]);
}
} else if (propertyType.type === "id") {
if (node.id.type === "Identifier") {
checkIdentifierOrVisit.call(this, node.id);
} else {
visitTypeAnnotation.call(this, node.id);
}
}
}
}
function checkIdentifierOrVisit(node) {
if (node.typeAnnotation) {
visitTypeAnnotation.call(this, node.typeAnnotation);
} else if (node.type === "Identifier") {
this.visit(node);
} else {
visitTypeAnnotation.call(this, node);
}
}
function nestTypeParamScope(manager, node) {
var parentScope = manager.__currentScope;
var scope = new escope.Scope(
manager,
"type-parameters",
parentScope,
node,
false
);
manager.__nestScope(scope);
for (var j = 0; j < node.typeParameters.params.length; j++) {
var name = node.typeParameters.params[j];
scope.__define(name, new Definition("TypeParameter", name, name));
if (name.typeAnnotation) {
checkIdentifierOrVisit.call(this, name);
}
}
scope.__define = function() {
return parentScope.__define.apply(parentScope, arguments);
};
return scope;
}
// visit decorators that are in: ClassDeclaration / ClassExpression
var visitClass = referencer.prototype.visitClass;
referencer.prototype.visitClass = function(node) {
visitDecorators.call(this, node);
var typeParamScope;
if (node.typeParameters) {
typeParamScope = nestTypeParamScope.call(this, this.scopeManager, node);
}
// visit flow type: ClassImplements
if (node.implements) {
for (var i = 0; i < node.implements.length; i++) {
checkIdentifierOrVisit.call(this, node.implements[i]);
}
}
if (node.superTypeParameters) {
for (var k = 0; k < node.superTypeParameters.params.length; k++) {
checkIdentifierOrVisit.call(this, node.superTypeParameters.params[k]);
}
}
visitClass.call(this, node);
if (typeParamScope) {
this.close(node);
}
};
// visit decorators that are in: Property / MethodDefinition
var visitProperty = referencer.prototype.visitProperty;
referencer.prototype.visitProperty = function(node) {
if (node.value && node.value.type === "TypeCastExpression") {
visitTypeAnnotation.call(this, node.value);
}
visitDecorators.call(this, node);
visitProperty.call(this, node);
};
function visitClassProperty(node) {
if (node.typeAnnotation) {
visitTypeAnnotation.call(this, node.typeAnnotation);
}
this.visitProperty(node);
}
// visit ClassProperty as a Property.
referencer.prototype.ClassProperty = visitClassProperty;
// visit ClassPrivateProperty as a Property.
referencer.prototype.ClassPrivateProperty = visitClassProperty;
// visit flow type in FunctionDeclaration, FunctionExpression, ArrowFunctionExpression
var visitFunction = referencer.prototype.visitFunction;
referencer.prototype.visitFunction = function(node) {
var typeParamScope;
if (node.typeParameters) {
typeParamScope = nestTypeParamScope.call(this, this.scopeManager, node);
}
if (node.returnType) {
checkIdentifierOrVisit.call(this, node.returnType);
}
// only visit if function parameters have types
if (node.params) {
for (var i = 0; i < node.params.length; i++) {
var param = node.params[i];
if (param.typeAnnotation) {
checkIdentifierOrVisit.call(this, param);
} else if (t.isAssignmentPattern(param)) {
if (param.left.typeAnnotation) {
checkIdentifierOrVisit.call(this, param.left);
}
}
}
}
// set ArrayPattern/ObjectPattern visitor keys back to their original. otherwise
// escope will traverse into them and include the identifiers within as declarations
estraverse.VisitorKeys.ObjectPattern = ["properties"];
estraverse.VisitorKeys.ArrayPattern = ["elements"];
visitFunction.call(this, node);
// set them back to normal...
estraverse.VisitorKeys.ObjectPattern = t.VISITOR_KEYS.ObjectPattern;
estraverse.VisitorKeys.ArrayPattern = t.VISITOR_KEYS.ArrayPattern;
if (typeParamScope) {
this.close(node);
}
};
// visit flow type in VariableDeclaration
var variableDeclaration = referencer.prototype.VariableDeclaration;
referencer.prototype.VariableDeclaration = function(node) {
if (node.declarations) {
for (var i = 0; i < node.declarations.length; i++) {
var id = node.declarations[i].id;
var typeAnnotation = id.typeAnnotation;
if (typeAnnotation) {
checkIdentifierOrVisit.call(this, typeAnnotation);
}
}
}
variableDeclaration.call(this, node);
};
function createScopeVariable(node, name) {
this.currentScope().variableScope.__define(
name,
new Definition("Variable", name, node, null, null, null)
);
}
referencer.prototype.InterfaceDeclaration = function(node) {
createScopeVariable.call(this, node, node.id);
var typeParamScope;
if (node.typeParameters) {
typeParamScope = nestTypeParamScope.call(this, this.scopeManager, node);
}
// TODO: Handle mixins
for (var i = 0; i < node.extends.length; i++) {
visitTypeAnnotation.call(this, node.extends[i]);
}
visitTypeAnnotation.call(this, node.body);
if (typeParamScope) {
this.close(node);
}
};
referencer.prototype.TypeAlias = function(node) {
createScopeVariable.call(this, node, node.id);
var typeParamScope;
if (node.typeParameters) {
typeParamScope = nestTypeParamScope.call(this, this.scopeManager, node);
}
if (node.right) {
visitTypeAnnotation.call(this, node.right);
}
if (typeParamScope) {
this.close(node);
}
};
referencer.prototype.DeclareModule = referencer.prototype.DeclareFunction = referencer.prototype.DeclareVariable = referencer.prototype.DeclareClass = function(
node
) {
if (node.id) {
createScopeVariable.call(this, node, node.id);
}
var typeParamScope;
if (node.typeParameters) {
typeParamScope = nestTypeParamScope.call(this, this.scopeManager, node);
}
if (typeParamScope) {
this.close(node);
}
};
referencer._babelEslintPatched = true;
}
// To patch for each call.
var escope = null;
var escopeAnalyze = null;
module.exports = function(parserOptions) {
// Patch `Referencer.prototype` once.
if (!escope) {
const modules = getModules();
monkeypatch(modules);
// Store to patch for each call.
escope = modules.escope;
escopeAnalyze = modules.escope.analyze;
}
// Patch `escope.analyze` based on the current parserOptions.
escope.analyze = function(ast, opts) {
opts = opts || {};
opts.ecmaVersion = parserOptions.ecmaVersion;
opts.sourceType = parserOptions.sourceType;
opts.nodejsScope =
ast.sourceType === "script" &&
(parserOptions.ecmaFeatures &&
parserOptions.ecmaFeatures.globalReturn) === true;
return escopeAnalyze.call(this, ast, opts);
};
};
+15
View File
@@ -0,0 +1,15 @@
"use strict";
const BABEL_VISITOR_KEYS = require("@babel/types").VISITOR_KEYS;
const ESLINT_VISITOR_KEYS = require("eslint-visitor-keys").KEYS;
module.exports = Object.assign(
{
Literal: ESLINT_VISITOR_KEYS.Literal,
MethodDefinition: ["decorators"].concat(
ESLINT_VISITOR_KEYS.MethodDefinition
),
Property: ["decorators"].concat(ESLINT_VISITOR_KEYS.Property),
},
BABEL_VISITOR_KEYS
);
@@ -0,0 +1,126 @@
# @babel/code-frame
> Generate errors that contain a code frame that point to source locations.
## Install
```sh
npm install --save-dev @babel/code-frame
```
## Usage
```js
import { codeFrameColumns } from '@babel/code-frame';
const rawLines = `class Foo {
constructor()
}`;
const location = { start: { line: 2, column: 16 } };
const result = codeFrameColumns(rawLines, location, { /* options */ });
console.log(result);
```
```
1 | class Foo {
> 2 | constructor()
| ^
3 | }
```
If the column number is not known, you may omit it.
You can also pass an `end` hash in `location`.
```js
import { codeFrameColumns } from '@babel/code-frame';
const rawLines = `class Foo {
constructor() {
console.log("hello");
}
}`;
const location = { start: { line: 2, column: 17 }, end: { line: 4, column: 3 } };
const result = codeFrameColumns(rawLines, location, { /* options */ });
console.log(result);
```
```
1 | class Foo {
> 2 | constructor() {
| ^
> 3 | console.log("hello");
| ^^^^^^^^^^^^^^^^^^^^^^^^^
> 4 | }
| ^^^
5 | };
```
## Options
### `highlightCode`
`boolean`, defaults to `false`.
Toggles syntax highlighting the code as JavaScript for terminals.
### `linesAbove`
`number`, defaults to `2`.
Adjust the number of lines to show above the error.
### `linesBelow`
`number`, defaults to `3`.
Adjust the number of lines to show below the error.
### `forceColor`
`boolean`, defaults to `false`.
Enable this to forcibly syntax highlight the code as JavaScript (for non-terminals); overrides `highlightCode`.
## Upgrading from prior versions
Prior to version 7, the only API exposed by this module was for a single line and optional column pointer. The old API will now log a deprecation warning.
The new API takes a `location` object, similar to what is available in an AST.
This is an example of the deprecated (but still available) API:
```js
import codeFrame from '@babel/code-frame';
const rawLines = `class Foo {
constructor()
}`;
const lineNumber = 2;
const colNumber = 16;
const result = codeFrame(rawLines, lineNumber, colNumber, { /* options */ });
console.log(result);
```
To get the same highlighting using the new API:
```js
import { codeFrameColumns } from '@babel/code-frame';
const rawLines = `class Foo {
constructor() {
console.log("hello");
}
}`;
const location = { start: { line: 2, column: 16 } };
const result = codeFrameColumns(rawLines, location, { /* options */ });
console.log(result);
```
@@ -0,0 +1,232 @@
"use strict";
exports.__esModule = true;
exports.codeFrameColumns = codeFrameColumns;
exports.default = _default;
var _jsTokens = _interopRequireWildcard(require("js-tokens"));
var _esutils = _interopRequireDefault(require("esutils"));
var _chalk = _interopRequireDefault(require("chalk"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
var deprecationWarningShown = false;
function getDefs(chalk) {
return {
keyword: chalk.cyan,
capitalized: chalk.yellow,
jsx_tag: chalk.yellow,
punctuator: chalk.yellow,
number: chalk.magenta,
string: chalk.green,
regex: chalk.magenta,
comment: chalk.grey,
invalid: chalk.white.bgRed.bold,
gutter: chalk.grey,
marker: chalk.red.bold
};
}
var NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
var JSX_TAG = /^[a-z][\w-]*$/i;
var BRACKET = /^[()[\]{}]$/;
function getTokenType(match) {
var _match$slice = match.slice(-2),
offset = _match$slice[0],
text = _match$slice[1];
var token = (0, _jsTokens.matchToToken)(match);
if (token.type === "name") {
if (_esutils.default.keyword.isReservedWordES6(token.value)) {
return "keyword";
}
if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) {
return "jsx_tag";
}
if (token.value[0] !== token.value[0].toLowerCase()) {
return "capitalized";
}
}
if (token.type === "punctuator" && BRACKET.test(token.value)) {
return "bracket";
}
if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
return "punctuator";
}
return token.type;
}
function highlight(defs, text) {
return text.replace(_jsTokens.default, function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var type = getTokenType(args);
var colorize = defs[type];
if (colorize) {
return args[0].split(NEWLINE).map(function (str) {
return colorize(str);
}).join("\n");
} else {
return args[0];
}
});
}
function getMarkerLines(loc, source, opts) {
var startLoc = Object.assign({}, {
column: 0,
line: -1
}, loc.start);
var endLoc = Object.assign({}, startLoc, loc.end);
var linesAbove = opts.linesAbove || 2;
var linesBelow = opts.linesBelow || 3;
var startLine = startLoc.line;
var startColumn = startLoc.column;
var endLine = endLoc.line;
var endColumn = endLoc.column;
var start = Math.max(startLine - (linesAbove + 1), 0);
var end = Math.min(source.length, endLine + linesBelow);
if (startLine === -1) {
start = 0;
}
if (endLine === -1) {
end = source.length;
}
var lineDiff = endLine - startLine;
var markerLines = {};
if (lineDiff) {
for (var i = 0; i <= lineDiff; i++) {
var lineNumber = i + startLine;
if (!startColumn) {
markerLines[lineNumber] = true;
} else if (i === 0) {
var sourceLength = source[lineNumber - 1].length;
markerLines[lineNumber] = [startColumn, sourceLength - startColumn];
} else if (i === lineDiff) {
markerLines[lineNumber] = [0, endColumn];
} else {
var _sourceLength = source[lineNumber - i].length;
markerLines[lineNumber] = [0, _sourceLength];
}
}
} else {
if (startColumn === endColumn) {
if (startColumn) {
markerLines[startLine] = [startColumn, 0];
} else {
markerLines[startLine] = true;
}
} else {
markerLines[startLine] = [startColumn, endColumn - startColumn];
}
}
return {
start: start,
end: end,
markerLines: markerLines
};
}
function codeFrameColumns(rawLines, loc, opts) {
if (opts === void 0) {
opts = {};
}
var highlighted = opts.highlightCode && _chalk.default.supportsColor || opts.forceColor;
var chalk = _chalk.default;
if (opts.forceColor) {
chalk = new _chalk.default.constructor({
enabled: true
});
}
var maybeHighlight = function maybeHighlight(chalkFn, string) {
return highlighted ? chalkFn(string) : string;
};
var defs = getDefs(chalk);
if (highlighted) rawLines = highlight(defs, rawLines);
var lines = rawLines.split(NEWLINE);
var _getMarkerLines = getMarkerLines(loc, lines, opts),
start = _getMarkerLines.start,
end = _getMarkerLines.end,
markerLines = _getMarkerLines.markerLines;
var numberMaxWidth = String(end).length;
var frame = lines.slice(start, end).map(function (line, index) {
var number = start + 1 + index;
var paddedNumber = (" " + number).slice(-numberMaxWidth);
var gutter = " " + paddedNumber + " | ";
var hasMarker = markerLines[number];
if (hasMarker) {
var markerLine = "";
if (Array.isArray(hasMarker)) {
var markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
var numberOfMarkers = hasMarker[1] || 1;
markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
}
return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join("");
} else {
return " " + maybeHighlight(defs.gutter, gutter) + line;
}
}).join("\n");
if (highlighted) {
return chalk.reset(frame);
} else {
return frame;
}
}
function _default(rawLines, lineNumber, colNumber, opts) {
if (opts === void 0) {
opts = {};
}
if (!deprecationWarningShown) {
deprecationWarningShown = true;
var deprecationError = new Error("Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.");
deprecationError.name = "DeprecationWarning";
if (process.emitWarning) {
process.emitWarning(deprecationError);
} else {
console.warn(deprecationError);
}
}
colNumber = Math.max(colNumber, 0);
var location = {
start: {
column: colNumber,
line: lineNumber
}
};
return codeFrameColumns(rawLines, location, opts);
}
@@ -0,0 +1,52 @@
{
"_from": "@babel/code-frame@7.0.0-beta.36",
"_id": "@babel/code-frame@7.0.0-beta.36",
"_inBundle": false,
"_integrity": "sha512-sW77BFwJ48YvQp3Gzz5xtAUiXuYOL2aMJKDwiaY3OcvdqBFurtYfOpSa4QrNyDxmOGRFSYzUpabU2m9QrlWE7w==",
"_location": "/babel-eslint/@babel/code-frame",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@babel/code-frame@7.0.0-beta.36",
"name": "@babel/code-frame",
"escapedName": "@babel%2fcode-frame",
"scope": "@babel",
"rawSpec": "7.0.0-beta.36",
"saveSpec": null,
"fetchSpec": "7.0.0-beta.36"
},
"_requiredBy": [
"/babel-eslint",
"/babel-eslint/@babel/template",
"/babel-eslint/@babel/traverse"
],
"_resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0-beta.36.tgz",
"_shasum": "2349d7ec04b3a06945ae173280ef8579b63728e4",
"_spec": "@babel/code-frame@7.0.0-beta.36",
"_where": "/home/mzasso/git/nodejs/node/tools/babel-eslint-tmp/node_modules/babel-eslint",
"author": {
"name": "Sebastian McKenzie",
"email": "sebmck@gmail.com"
},
"bundleDependencies": false,
"dependencies": {
"chalk": "^2.0.0",
"esutils": "^2.0.2",
"js-tokens": "^3.0.0"
},
"deprecated": false,
"description": "Generate errors that contain a code frame that point to source locations.",
"devDependencies": {
"strip-ansi": "^4.0.0"
},
"homepage": "https://babeljs.io/",
"license": "MIT",
"main": "lib/index.js",
"name": "@babel/code-frame",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-code-frame"
},
"version": "7.0.0-beta.36"
}
@@ -0,0 +1,5 @@
# @babel/helper-function-name
## Usage
TODO
@@ -0,0 +1,129 @@
"use strict";
exports.__esModule = true;
exports.default = _default;
var _helperGetFunctionArity = _interopRequireDefault(require("@babel/helper-get-function-arity"));
var _template2 = _interopRequireDefault(require("@babel/template"));
var t = _interopRequireWildcard(require("@babel/types"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var buildPropertyMethodAssignmentWrapper = (0, _template2.default)("\n (function (FUNCTION_KEY) {\n function FUNCTION_ID() {\n return FUNCTION_KEY.apply(this, arguments);\n }\n\n FUNCTION_ID.toString = function () {\n return FUNCTION_KEY.toString();\n }\n\n return FUNCTION_ID;\n })(FUNCTION)\n");
var buildGeneratorPropertyMethodAssignmentWrapper = (0, _template2.default)("\n (function (FUNCTION_KEY) {\n function* FUNCTION_ID() {\n return yield* FUNCTION_KEY.apply(this, arguments);\n }\n\n FUNCTION_ID.toString = function () {\n return FUNCTION_KEY.toString();\n };\n\n return FUNCTION_ID;\n })(FUNCTION)\n");
var visitor = {
"ReferencedIdentifier|BindingIdentifier": function ReferencedIdentifierBindingIdentifier(path, state) {
if (path.node.name !== state.name) return;
var localDeclar = path.scope.getBindingIdentifier(state.name);
if (localDeclar !== state.outerDeclar) return;
state.selfReference = true;
path.stop();
}
};
function wrap(state, method, id, scope) {
if (state.selfReference) {
if (scope.hasBinding(id.name) && !scope.hasGlobal(id.name)) {
scope.rename(id.name);
} else {
if (!t.isFunction(method)) return;
var build = buildPropertyMethodAssignmentWrapper;
if (method.generator) {
build = buildGeneratorPropertyMethodAssignmentWrapper;
}
var _template = build({
FUNCTION: method,
FUNCTION_ID: id,
FUNCTION_KEY: scope.generateUidIdentifier(id.name)
}).expression;
var params = _template.callee.body.body[0].params;
for (var i = 0, len = (0, _helperGetFunctionArity.default)(method); i < len; i++) {
params.push(scope.generateUidIdentifier("x"));
}
return _template;
}
}
method.id = id;
scope.getProgramParent().references[id.name] = true;
}
function visit(node, name, scope) {
var state = {
selfAssignment: false,
selfReference: false,
outerDeclar: scope.getBindingIdentifier(name),
references: [],
name: name
};
var binding = scope.getOwnBinding(name);
if (binding) {
if (binding.kind === "param") {
state.selfReference = true;
} else {}
} else if (state.outerDeclar || scope.hasGlobal(name)) {
scope.traverse(node, visitor, state);
}
return state;
}
function _default(_ref, localBinding) {
var node = _ref.node,
parent = _ref.parent,
scope = _ref.scope,
id = _ref.id;
if (localBinding === void 0) {
localBinding = false;
}
if (node.id) return;
if ((t.isObjectProperty(parent) || t.isObjectMethod(parent, {
kind: "method"
})) && (!parent.computed || t.isLiteral(parent.key))) {
id = parent.key;
} else if (t.isVariableDeclarator(parent)) {
id = parent.id;
if (t.isIdentifier(id) && !localBinding) {
var binding = scope.parent.getBinding(id.name);
if (binding && binding.constant && scope.getBinding(id.name) === binding) {
node.id = id;
node.id[t.NOT_LOCAL_BINDING] = true;
return;
}
}
} else if (t.isAssignmentExpression(parent)) {
id = parent.left;
} else if (!id) {
return;
}
var name;
if (id && t.isLiteral(id)) {
name = id.value;
} else if (id && t.isIdentifier(id)) {
name = id.name;
} else {
return;
}
name = t.toBindingIdentifierName(name);
id = t.identifier(name);
id[t.NOT_LOCAL_BINDING] = true;
var state = visit(node, name, scope);
return wrap(state, node, id, scope) || node;
}
@@ -0,0 +1,42 @@
{
"_from": "@babel/helper-function-name@7.0.0-beta.36",
"_id": "@babel/helper-function-name@7.0.0-beta.36",
"_inBundle": false,
"_integrity": "sha512-/SGPOyifPf20iTrMN+WdlY2MbKa7/o4j7B/4IAsdOusASp2icT+Wcdjf4tjJHaXNX8Pe9bpgVxLNxhRvcf8E5w==",
"_location": "/babel-eslint/@babel/helper-function-name",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@babel/helper-function-name@7.0.0-beta.36",
"name": "@babel/helper-function-name",
"escapedName": "@babel%2fhelper-function-name",
"scope": "@babel",
"rawSpec": "7.0.0-beta.36",
"saveSpec": null,
"fetchSpec": "7.0.0-beta.36"
},
"_requiredBy": [
"/babel-eslint/@babel/traverse"
],
"_resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.0.0-beta.36.tgz",
"_shasum": "366e3bc35147721b69009f803907c4d53212e88d",
"_spec": "@babel/helper-function-name@7.0.0-beta.36",
"_where": "/home/mzasso/git/nodejs/node/tools/babel-eslint-tmp/node_modules/babel-eslint/node_modules/@babel/traverse",
"bundleDependencies": false,
"dependencies": {
"@babel/helper-get-function-arity": "7.0.0-beta.36",
"@babel/template": "7.0.0-beta.36",
"@babel/types": "7.0.0-beta.36"
},
"deprecated": false,
"description": "Helper function to change the property 'name' of every function",
"license": "MIT",
"main": "lib/index.js",
"name": "@babel/helper-function-name",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-helper-function-name"
},
"version": "7.0.0-beta.36"
}
@@ -0,0 +1,21 @@
# @babel/helper-get-function-arity
Function that returns the number of arguments that a function takes.
* Examples of what is considered an argument can be found at [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length)
## Usage
```javascript
import getFunctionArity from "@babel/helper-get-function-arity";
function wrap(state, method, id, scope) {
// ...
if (!t.isFunction(method)) {
return false;
}
const argumentsLength = getFunctionArity(method);
// ...
}
```
@@ -0,0 +1,22 @@
"use strict";
exports.__esModule = true;
exports.default = _default;
var t = _interopRequireWildcard(require("@babel/types"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _default(node) {
var params = node.params;
for (var i = 0; i < params.length; i++) {
var param = params[i];
if (t.isAssignmentPattern(param) || t.isRestElement(param)) {
return i;
}
}
return params.length;
}
@@ -0,0 +1,40 @@
{
"_from": "@babel/helper-get-function-arity@7.0.0-beta.36",
"_id": "@babel/helper-get-function-arity@7.0.0-beta.36",
"_inBundle": false,
"_integrity": "sha512-vPPcx2vsSoDbcyWr9S3nd0FM3B4hEXnt0p1oKpwa08GwK0fSRxa98MyaRGf8suk8frdQlG1P3mDrz5p/Rr3pbA==",
"_location": "/babel-eslint/@babel/helper-get-function-arity",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@babel/helper-get-function-arity@7.0.0-beta.36",
"name": "@babel/helper-get-function-arity",
"escapedName": "@babel%2fhelper-get-function-arity",
"scope": "@babel",
"rawSpec": "7.0.0-beta.36",
"saveSpec": null,
"fetchSpec": "7.0.0-beta.36"
},
"_requiredBy": [
"/babel-eslint/@babel/helper-function-name"
],
"_resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.0.0-beta.36.tgz",
"_shasum": "f5383bac9a96b274828b10d98900e84ee43e32b8",
"_spec": "@babel/helper-get-function-arity@7.0.0-beta.36",
"_where": "/home/mzasso/git/nodejs/node/tools/babel-eslint-tmp/node_modules/babel-eslint/node_modules/@babel/helper-function-name",
"bundleDependencies": false,
"dependencies": {
"@babel/types": "7.0.0-beta.36"
},
"deprecated": false,
"description": "Helper function to get function arity",
"license": "MIT",
"main": "lib/index.js",
"name": "@babel/helper-get-function-arity",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-helper-get-function-arity"
},
"version": "7.0.0-beta.36"
}
+172
View File
@@ -0,0 +1,172 @@
# @babel/template
> Generate an AST from a string template or template literal.
In computer science, this is known as an implementation of quasiquotes.
## Install
```sh
npm install --save-dev @babel/template
```
## String Usage
```js
import template from "@babel/template";
import generate from "@babel/generator";
import * as t from "@babel/types";
const buildRequire = template(`
var IMPORT_NAME = require(SOURCE);
`);
const ast = buildRequire({
IMPORT_NAME: t.identifier("myModule"),
SOURCE: t.stringLiteral("my-module")
});
console.log(generate(ast).code);
```
```js
const myModule = require("my-module");
```
### `.ast`
If no placeholders are in use and you just want a simple way to parse a
string into an AST, you can use the `.ast` version of the template.
```js
const ast = template.ast(`
var myModule = require("my-module");
`);
```
which will parse and return the AST directly.
## Template Literal Usage
```js
import template from "@babel/template";
import generate from "@babel/generator";
import * as t from "@babel/types";
const fn = template`
var IMPORT_NAME = require('${"my-module"}');
`);
const ast = fn({
IMPORT_NAME: t.identifier("myModule");
});
console.log(generate(ast).code);
```
Note that placeholders can be passed directly as part of the template literal
in order to make things as readable as possible, or they can be passed into
the template function.
### `.ast`
If no placeholders are in use and you just want a simple way to parse a
string into an AST, you can use the `.ast` version of the template.
```js
const name = "my-module";
const mod = "myModule";
const ast = template.ast`
var ${mod} = require("${name}");
`;
```
which will parse and return the AST directly. Note that unlike the string-based
version mentioned earlier, since this is a template literal, it is still
valid to perform replacements using template literal replacements.
## AST results
The `@babel/template` API exposes a few flexible APIs to make it as easy as
possible to create ASTs with an expected structure. Each of these also has
the `.ast` property mentioned above.
### `template`
`template` returns either a single statement, or an array of
statements, depending on the parsed result.
### `template.smart`
This is the same as the default `template` API, returning either a single
node, or an array of nodes, depending on the parsed result.
### `template.statement`
`template.statement("foo;")()` returns a single statement node, and throw
an exception if the result is anything but a single statement.
### `template.statements`
`template.statements("foo;foo;")()` returns an array of statement nodes.
### `template.expression`
`template.expression("foo")()` returns the expression node.
### `template.program`
`template.program("foo;")()` returns the `Program` node for the template.
## API
### `template(code, [opts])`
#### code
Type: `string`
#### options
`@babel/template` accepts all of the options from [babylon](https://github.com/babel/babel/tree/master/packages/babylon), and specifies
some defaults of its own:
* `allowReturnOutsideFunction` is set to `true` by default.
* `allowSuperOutsideMethod` is set to `true` by default.
* `sourceType` is set to `module` by default.
##### placeholderWhitelist
Type: `Set<string>`
Default: `undefined`
A set of placeholder names to automatically accept. Items in this list do
not need to match the given placeholder pattern.
##### placeholderPattern
Type: `RegExp | false`
Default: `/^[_$A-Z0-9]+$/`
A pattern to search for when looking for Identifier and StringLiteral
nodes that should be considered placeholders.
'false' will disable placeholder searching entirely, leaving only the
'placeholderWhitelist' value to find placeholders.
##### preserveComments
Type: `boolean`
Default: `false`
Set this to `true` to preserve any comments from the `code` parameter.
#### Return value
By default `@babel/template` returns a `function` which is invoked with an
optional object of replacements. See the usage section for an example.
When using `.ast`, the AST will be returned directly.
[babylon]: https://github.com/babel/babylon#options
@@ -0,0 +1,89 @@
"use strict";
exports.__esModule = true;
exports.default = createTemplateBuilder;
var _options = require("./options");
var _string = _interopRequireDefault(require("./string"));
var _literal = _interopRequireDefault(require("./literal"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var NO_PLACEHOLDER = (0, _options.validate)({
placeholderPattern: false
});
function createTemplateBuilder(formatter, defaultOpts) {
var templateFnCache = new WeakMap();
var templateAstCache = new WeakMap();
var cachedOpts = defaultOpts || (0, _options.validate)(null);
return Object.assign(function (tpl) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (typeof tpl === "string") {
if (args.length > 1) throw new Error("Unexpected extra params.");
return extendedTrace((0, _string.default)(formatter, tpl, (0, _options.merge)(cachedOpts, (0, _options.validate)(args[0]))));
} else if (Array.isArray(tpl)) {
var builder = templateFnCache.get(tpl);
if (!builder) {
builder = (0, _literal.default)(formatter, tpl, cachedOpts);
templateFnCache.set(tpl, builder);
}
return extendedTrace(builder(args));
} else if (typeof tpl === "object" && tpl) {
if (args.length > 0) throw new Error("Unexpected extra params.");
return createTemplateBuilder(formatter, (0, _options.merge)(cachedOpts, (0, _options.validate)(tpl)));
}
throw new Error("Unexpected template param " + typeof tpl);
}, {
ast: function ast(tpl) {
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
if (typeof tpl === "string") {
if (args.length > 1) throw new Error("Unexpected extra params.");
return (0, _string.default)(formatter, tpl, (0, _options.merge)((0, _options.merge)(cachedOpts, (0, _options.validate)(args[0])), NO_PLACEHOLDER))();
} else if (Array.isArray(tpl)) {
var builder = templateAstCache.get(tpl);
if (!builder) {
builder = (0, _literal.default)(formatter, tpl, (0, _options.merge)(cachedOpts, NO_PLACEHOLDER));
templateAstCache.set(tpl, builder);
}
return builder(args)();
}
throw new Error("Unexpected template param " + typeof tpl);
}
});
}
function extendedTrace(fn) {
var rootStack = "";
try {
throw new Error();
} catch (error) {
if (error.stack) {
rootStack = error.stack.split("\n").slice(3).join("\n");
}
}
return function (arg) {
try {
return fn(arg);
} catch (err) {
err.stack += "\n =============\n" + rootStack;
throw err;
}
};
}
@@ -0,0 +1,73 @@
"use strict";
exports.__esModule = true;
exports.program = exports.expression = exports.statement = exports.statements = exports.smart = void 0;
function makeStatementFormatter(fn) {
return {
code: function code(str) {
return "/* @babel/template */;\n" + str;
},
validate: function validate() {},
unwrap: function unwrap(ast) {
return fn(ast.program.body.slice(1));
}
};
}
var smart = makeStatementFormatter(function (body) {
if (body.length > 1) {
return body;
} else {
return body[0];
}
});
exports.smart = smart;
var statements = makeStatementFormatter(function (body) {
return body;
});
exports.statements = statements;
var statement = makeStatementFormatter(function (body) {
if (body.length === 0) {
throw new Error("Found nothing to return.");
}
if (body.length > 1) {
throw new Error("Found multiple statements but wanted one");
}
return body[0];
});
exports.statement = statement;
var expression = {
code: function code(str) {
return "(\n" + str + "\n)";
},
validate: function validate(ast) {
var program = ast.program;
if (program.body.length > 1) {
throw new Error("Found multiple statements but wanted one");
}
var expression = program.body[0].expression;
if (expression.start === 0) {
throw new Error("Parse result included parens.");
}
},
unwrap: function unwrap(ast) {
return ast.program.body[0].expression;
}
};
exports.expression = expression;
var program = {
code: function code(str) {
return str;
},
validate: function validate() {},
unwrap: function unwrap(ast) {
return ast.program;
}
};
exports.program = program;
@@ -0,0 +1,34 @@
"use strict";
exports.__esModule = true;
exports.default = exports.program = exports.expression = exports.statements = exports.statement = exports.smart = void 0;
var formatters = _interopRequireWildcard(require("./formatters"));
var _builder = _interopRequireDefault(require("./builder"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
var smart = (0, _builder.default)(formatters.smart);
exports.smart = smart;
var statement = (0, _builder.default)(formatters.statement);
exports.statement = statement;
var statements = (0, _builder.default)(formatters.statements);
exports.statements = statements;
var expression = (0, _builder.default)(formatters.expression);
exports.expression = expression;
var program = (0, _builder.default)(formatters.program);
exports.program = program;
var _default = Object.assign(smart.bind(undefined), {
smart: smart,
statement: statement,
statements: statements,
expression: expression,
program: program,
ast: smart.ast
});
exports.default = _default;
@@ -0,0 +1,81 @@
"use strict";
exports.__esModule = true;
exports.default = literalTemplate;
var _options = require("./options");
var _parse = _interopRequireDefault(require("./parse"));
var _populate = _interopRequireDefault(require("./populate"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function literalTemplate(formatter, tpl, opts) {
var _buildLiteralData = buildLiteralData(formatter, tpl, opts),
metadata = _buildLiteralData.metadata,
names = _buildLiteralData.names;
return function (arg) {
var defaultReplacements = arg.reduce(function (acc, replacement, i) {
acc[names[i]] = replacement;
return acc;
}, {});
return function (arg) {
var replacements = (0, _options.normalizeReplacements)(arg);
if (replacements) {
Object.keys(replacements).forEach(function (key) {
if (Object.prototype.hasOwnProperty.call(defaultReplacements, key)) {
throw new Error("Unexpected replacement overlap.");
}
});
}
return formatter.unwrap((0, _populate.default)(metadata, replacements ? Object.assign(replacements, defaultReplacements) : defaultReplacements));
};
};
}
function buildLiteralData(formatter, tpl, opts) {
var names;
var nameSet;
var metadata;
var prefix = "";
do {
prefix += "$";
var result = buildTemplateCode(tpl, prefix);
names = result.names;
nameSet = new Set(names);
metadata = (0, _parse.default)(formatter, formatter.code(result.code), {
parser: opts.parser,
placeholderWhitelist: new Set(result.names.concat(opts.placeholderWhitelist ? Array.from(opts.placeholderWhitelist) : [])),
placeholderPattern: opts.placeholderPattern,
preserveComments: opts.preserveComments
});
} while (metadata.placeholders.some(function (placeholder) {
return placeholder.isDuplicate && nameSet.has(placeholder.name);
}));
return {
metadata: metadata,
names: names
};
}
function buildTemplateCode(tpl, prefix) {
var names = [];
var code = tpl[0];
for (var i = 1; i < tpl.length; i++) {
var value = "" + prefix + (i - 1);
names.push(value);
code += value + tpl[i];
}
return {
names: names,
code: code
};
}
@@ -0,0 +1,67 @@
"use strict";
exports.__esModule = true;
exports.merge = merge;
exports.validate = validate;
exports.normalizeReplacements = normalizeReplacements;
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function merge(a, b) {
var _b$placeholderWhiteli = b.placeholderWhitelist,
placeholderWhitelist = _b$placeholderWhiteli === void 0 ? a.placeholderWhitelist : _b$placeholderWhiteli,
_b$placeholderPattern = b.placeholderPattern,
placeholderPattern = _b$placeholderPattern === void 0 ? a.placeholderPattern : _b$placeholderPattern,
_b$preserveComments = b.preserveComments,
preserveComments = _b$preserveComments === void 0 ? a.preserveComments : _b$preserveComments;
return {
parser: Object.assign({}, a.parser, b.parser),
placeholderWhitelist: placeholderWhitelist,
placeholderPattern: placeholderPattern,
preserveComments: preserveComments
};
}
function validate(opts) {
if (opts != null && typeof opts !== "object") {
throw new Error("Unknown template options.");
}
var _ref = opts || {},
placeholderWhitelist = _ref.placeholderWhitelist,
placeholderPattern = _ref.placeholderPattern,
preserveComments = _ref.preserveComments,
parser = _objectWithoutProperties(_ref, ["placeholderWhitelist", "placeholderPattern", "preserveComments"]);
if (placeholderWhitelist != null && !(placeholderWhitelist instanceof Set)) {
throw new Error("'.placeholderWhitelist' must be a Set, null, or undefined");
}
if (placeholderPattern != null && !(placeholderPattern instanceof RegExp) && placeholderPattern !== false) {
throw new Error("'.placeholderPattern' must be a RegExp, false, null, or undefined");
}
if (preserveComments != null && typeof preserveComments !== "boolean") {
throw new Error("'.preserveComments' must be a boolean, null, or undefined");
}
return {
parser: parser,
placeholderWhitelist: placeholderWhitelist || undefined,
placeholderPattern: placeholderPattern == null ? undefined : placeholderPattern,
preserveComments: preserveComments == null ? false : preserveComments
};
}
function normalizeReplacements(replacements) {
if (Array.isArray(replacements)) {
return replacements.reduce(function (acc, replacement, i) {
acc["$" + i] = replacement;
return acc;
}, {});
} else if (typeof replacements === "object" || replacements == null) {
return replacements || undefined;
}
throw new Error("Template replacements must be an array, object, null, or undefined");
}
@@ -0,0 +1,130 @@
"use strict";
exports.__esModule = true;
exports.default = parseAndBuildMetadata;
var t = _interopRequireWildcard(require("@babel/types"));
var _babylon = require("babylon");
var _codeFrame = require("@babel/code-frame");
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
var PATTERN = /^[_$A-Z0-9]+$/;
function parseAndBuildMetadata(formatter, code, opts) {
var ast = parseWithCodeFrame(code, opts.parser);
var placeholderWhitelist = opts.placeholderWhitelist,
_opts$placeholderPatt = opts.placeholderPattern,
placeholderPattern = _opts$placeholderPatt === void 0 ? PATTERN : _opts$placeholderPatt,
preserveComments = opts.preserveComments;
t.removePropertiesDeep(ast, {
preserveComments: preserveComments
});
formatter.validate(ast);
var placeholders = [];
var placeholderNames = new Set();
t.traverse(ast, placeholderVisitorHandler, {
placeholders: placeholders,
placeholderNames: placeholderNames,
placeholderWhitelist: placeholderWhitelist,
placeholderPattern: placeholderPattern
});
return {
ast: ast,
placeholders: placeholders,
placeholderNames: placeholderNames
};
}
function placeholderVisitorHandler(node, ancestors, state) {
var name;
if (t.isIdentifier(node)) {
name = node.name;
} else if (t.isStringLiteral(node)) {
name = node.value;
} else {
return;
}
if ((!state.placeholderPattern || !state.placeholderPattern.test(name)) && (!state.placeholderWhitelist || !state.placeholderWhitelist.has(name))) {
return;
}
ancestors = ancestors.slice();
var _ancestors = ancestors[ancestors.length - 1],
parent = _ancestors.node,
key = _ancestors.key;
var type;
if (t.isStringLiteral(node)) {
type = "string";
} else if (t.isNewExpression(parent) && key === "arguments" || t.isCallExpression(parent) && key === "arguments" || t.isFunction(parent) && key === "params") {
type = "param";
} else if (t.isExpressionStatement(parent)) {
type = "statement";
ancestors = ancestors.slice(0, -1);
} else {
type = "other";
}
state.placeholders.push({
name: name,
type: type,
resolve: function resolve(ast) {
return resolveAncestors(ast, ancestors);
},
isDuplicate: state.placeholderNames.has(name)
});
state.placeholderNames.add(name);
}
function resolveAncestors(ast, ancestors) {
var parent = ast;
for (var i = 0; i < ancestors.length - 1; i++) {
var _ancestors$i = ancestors[i],
_key = _ancestors$i.key,
_index = _ancestors$i.index;
if (_index === undefined) {
parent = parent[_key];
} else {
parent = parent[_key][_index];
}
}
var _ancestors2 = ancestors[ancestors.length - 1],
key = _ancestors2.key,
index = _ancestors2.index;
return {
parent: parent,
key: key,
index: index
};
}
function parseWithCodeFrame(code, parserOpts) {
parserOpts = Object.assign({
allowReturnOutsideFunction: true,
allowSuperOutsideMethod: true,
sourceType: "module"
}, parserOpts);
try {
return (0, _babylon.parse)(code, parserOpts);
} catch (err) {
var loc = err.loc;
if (loc) {
err.loc = null;
err.message += "\n" + (0, _codeFrame.codeFrameColumns)(code, {
start: loc
});
}
throw err;
}
}
@@ -0,0 +1,120 @@
"use strict";
exports.__esModule = true;
exports.default = populatePlaceholders;
var t = _interopRequireWildcard(require("@babel/types"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function populatePlaceholders(metadata, replacements) {
var ast = t.cloneDeep(metadata.ast);
if (replacements) {
metadata.placeholders.forEach(function (placeholder) {
if (!Object.prototype.hasOwnProperty.call(replacements, placeholder.name)) {
throw new Error("No substitution given for \"" + placeholder.name + "\"");
}
});
Object.keys(replacements).forEach(function (key) {
if (!metadata.placeholderNames.has(key)) {
throw new Error("Unknown substitution \"" + key + "\" given");
}
});
}
metadata.placeholders.slice().reverse().forEach(function (placeholder) {
try {
applyReplacement(placeholder, ast, replacements && replacements[placeholder.name] || null);
} catch (e) {
e.message = "babel-template placeholder \"" + placeholder.name + "\": " + e.message;
throw e;
}
});
return ast;
}
function applyReplacement(placeholder, ast, replacement) {
if (placeholder.isDuplicate) {
if (Array.isArray(replacement)) {
replacement = replacement.map(function (node) {
return t.cloneDeep(node);
});
} else if (typeof replacement === "object") {
replacement = t.cloneDeep(replacement);
}
}
var _placeholder$resolve = placeholder.resolve(ast),
parent = _placeholder$resolve.parent,
key = _placeholder$resolve.key,
index = _placeholder$resolve.index;
if (placeholder.type === "string") {
if (typeof replacement === "string") {
replacement = t.stringLiteral(replacement);
}
if (!replacement || !t.isStringLiteral(replacement)) {
throw new Error("Expected string substitution");
}
} else if (placeholder.type === "statement") {
if (index === undefined) {
if (!replacement) {
replacement = t.emptyStatement();
} else if (Array.isArray(replacement)) {
replacement = t.blockStatement(replacement);
} else if (typeof replacement === "string") {
replacement = t.expressionStatement(t.identifier(replacement));
} else if (!t.isStatement(replacement)) {
replacement = t.expressionStatement(replacement);
}
} else {
if (replacement && !Array.isArray(replacement)) {
if (typeof replacement === "string") {
replacement = t.identifier(replacement);
}
if (!t.isStatement(replacement)) {
replacement = t.expressionStatement(replacement);
}
}
}
} else if (placeholder.type === "param") {
if (typeof replacement === "string") {
replacement = t.identifier(replacement);
}
if (index === undefined) throw new Error("Assertion failure.");
} else {
if (typeof replacement === "string") {
replacement = t.identifier(replacement);
}
if (Array.isArray(replacement)) {
throw new Error("Cannot replace single expression with an array.");
}
}
if (index === undefined) {
t.validate(parent, key, replacement);
parent[key] = replacement;
} else {
var items = parent[key].slice();
if (placeholder.type === "statement" || placeholder.type === "param") {
if (replacement == null) {
items.splice(index, 1);
} else if (Array.isArray(replacement)) {
items.splice.apply(items, [index, 1].concat(replacement));
} else {
items[index] = replacement;
}
} else {
items[index] = replacement;
}
t.validate(parent, key, items);
parent[key] = items;
}
}
@@ -0,0 +1,22 @@
"use strict";
exports.__esModule = true;
exports.default = stringTemplate;
var _options = require("./options");
var _parse = _interopRequireDefault(require("./parse"));
var _populate = _interopRequireDefault(require("./populate"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function stringTemplate(formatter, code, opts) {
code = formatter.code(code);
var metadata;
return function (arg) {
var replacements = (0, _options.normalizeReplacements)(arg);
if (!metadata) metadata = (0, _parse.default)(formatter, code, opts);
return formatter.unwrap((0, _populate.default)(metadata, replacements));
};
}
@@ -0,0 +1,48 @@
{
"_from": "@babel/template@7.0.0-beta.36",
"_id": "@babel/template@7.0.0-beta.36",
"_inBundle": false,
"_integrity": "sha512-mUBi90WRyZ9iVvlWLEdeo8gn/tROyJdjKNC4W5xJTSZL+9MS89rTJSqiaJKXIkxk/YRDL/g/8snrG/O0xl33uA==",
"_location": "/babel-eslint/@babel/template",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@babel/template@7.0.0-beta.36",
"name": "@babel/template",
"escapedName": "@babel%2ftemplate",
"scope": "@babel",
"rawSpec": "7.0.0-beta.36",
"saveSpec": null,
"fetchSpec": "7.0.0-beta.36"
},
"_requiredBy": [
"/babel-eslint/@babel/helper-function-name"
],
"_resolved": "https://registry.npmjs.org/@babel/template/-/template-7.0.0-beta.36.tgz",
"_shasum": "02e903de5d68bd7899bce3c5b5447e59529abb00",
"_spec": "@babel/template@7.0.0-beta.36",
"_where": "/home/mzasso/git/nodejs/node/tools/babel-eslint-tmp/node_modules/babel-eslint/node_modules/@babel/helper-function-name",
"author": {
"name": "Sebastian McKenzie",
"email": "sebmck@gmail.com"
},
"bundleDependencies": false,
"dependencies": {
"@babel/code-frame": "7.0.0-beta.36",
"@babel/types": "7.0.0-beta.36",
"babylon": "7.0.0-beta.36",
"lodash": "^4.2.0"
},
"deprecated": false,
"description": "Generate an AST from a string template.",
"homepage": "https://babeljs.io/",
"license": "MIT",
"main": "lib/index.js",
"name": "@babel/template",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-template"
},
"version": "7.0.0-beta.36"
}
+33
View File
@@ -0,0 +1,33 @@
# @babel/traverse
> @babel/traverse maintains the overall tree state, and is responsible for replacing, removing, and adding nodes.
## Install
```sh
$ npm install --save @babel/traverse
```
## Usage
We can use it alongside Babylon to traverse and update nodes:
```js
import * as babylon from "babylon";
import traverse from "@babel/traverse";
const code = `function square(n) {
return n * n;
}`;
const ast = babylon.parse(code);
traverse(ast, {
enter(path) {
if (path.isIdentifier({ name: "n" })) {
path.node.name = "x";
}
}
});
```
[:book: **Read the full docs here**](https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-traverse)
@@ -0,0 +1,24 @@
"use strict";
exports.__esModule = true;
exports.clear = clear;
exports.clearPath = clearPath;
exports.clearScope = clearScope;
exports.scope = exports.path = void 0;
var path = new WeakMap();
exports.path = path;
var scope = new WeakMap();
exports.scope = scope;
function clear() {
clearPath();
clearScope();
}
function clearPath() {
exports.path = path = new WeakMap();
}
function clearScope() {
exports.scope = scope = new WeakMap();
}
@@ -0,0 +1,187 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _path4 = _interopRequireDefault(require("./path"));
var t = _interopRequireWildcard(require("@babel/types"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var testing = process.env.NODE_ENV === "test";
var TraversalContext = function () {
function TraversalContext(scope, opts, state, parentPath) {
this.parentPath = void 0;
this.scope = void 0;
this.state = void 0;
this.opts = void 0;
this.queue = null;
this.parentPath = parentPath;
this.scope = scope;
this.state = state;
this.opts = opts;
}
var _proto = TraversalContext.prototype;
_proto.shouldVisit = function shouldVisit(node) {
var opts = this.opts;
if (opts.enter || opts.exit) return true;
if (opts[node.type]) return true;
var keys = t.VISITOR_KEYS[node.type];
if (!keys || !keys.length) return false;
for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var _key = _ref;
if (node[_key]) return true;
}
return false;
};
_proto.create = function create(node, obj, key, listKey) {
return _path4.default.get({
parentPath: this.parentPath,
parent: node,
container: obj,
key: key,
listKey: listKey
});
};
_proto.maybeQueue = function maybeQueue(path, notPriority) {
if (this.trap) {
throw new Error("Infinite cycle detected");
}
if (this.queue) {
if (notPriority) {
this.queue.push(path);
} else {
this.priorityQueue.push(path);
}
}
};
_proto.visitMultiple = function visitMultiple(container, parent, listKey) {
if (container.length === 0) return false;
var queue = [];
for (var key = 0; key < container.length; key++) {
var node = container[key];
if (node && this.shouldVisit(node)) {
queue.push(this.create(parent, container, key, listKey));
}
}
return this.visitQueue(queue);
};
_proto.visitSingle = function visitSingle(node, key) {
if (this.shouldVisit(node[key])) {
return this.visitQueue([this.create(node, node, key)]);
} else {
return false;
}
};
_proto.visitQueue = function visitQueue(queue) {
this.queue = queue;
this.priorityQueue = [];
var visited = [];
var stop = false;
for (var _iterator2 = queue, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var _path2 = _ref2;
_path2.resync();
if (_path2.contexts.length === 0 || _path2.contexts[_path2.contexts.length - 1] !== this) {
_path2.pushContext(this);
}
if (_path2.key === null) continue;
if (testing && queue.length >= 10000) {
this.trap = true;
}
if (visited.indexOf(_path2.node) >= 0) continue;
visited.push(_path2.node);
if (_path2.visit()) {
stop = true;
break;
}
if (this.priorityQueue.length) {
stop = this.visitQueue(this.priorityQueue);
this.priorityQueue = [];
this.queue = queue;
if (stop) break;
}
}
for (var _iterator3 = queue, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var _path3 = _ref3;
_path3.popContext();
}
this.queue = null;
return stop;
};
_proto.visit = function visit(node, key) {
var nodes = node[key];
if (!nodes) return false;
if (Array.isArray(nodes)) {
return this.visitMultiple(nodes, node, key);
} else {
return this.visitSingle(node, key);
}
};
return TraversalContext;
}();
exports.default = TraversalContext;
@@ -0,0 +1,10 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var Hub = function Hub(file) {
this.file = file;
};
exports.default = Hub;
@@ -0,0 +1,112 @@
"use strict";
exports.__esModule = true;
exports.default = traverse;
exports.visitors = exports.Hub = exports.Scope = exports.NodePath = void 0;
var _context = _interopRequireDefault(require("./context"));
var visitors = _interopRequireWildcard(require("./visitors"));
exports.visitors = visitors;
var _includes = _interopRequireDefault(require("lodash/includes"));
var t = _interopRequireWildcard(require("@babel/types"));
var cache = _interopRequireWildcard(require("./cache"));
var _path = _interopRequireDefault(require("./path"));
exports.NodePath = _path.default;
var _scope = _interopRequireDefault(require("./scope"));
exports.Scope = _scope.default;
var _hub = _interopRequireDefault(require("./hub"));
exports.Hub = _hub.default;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function traverse(parent, opts, scope, state, parentPath) {
if (!parent) return;
if (!opts) opts = {};
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.");
}
}
visitors.explode(opts);
traverse.node(parent, opts, scope, state, parentPath);
}
traverse.visitors = visitors;
traverse.verify = visitors.verify;
traverse.explode = visitors.explode;
traverse.cheap = function (node, enter) {
return t.traverseFast(node, enter);
};
traverse.node = function (node, opts, scope, state, parentPath, skipKeys) {
var keys = t.VISITOR_KEYS[node.type];
if (!keys) return;
var context = new _context.default(scope, opts, state, parentPath);
for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var _key = _ref;
if (skipKeys && skipKeys[_key]) continue;
if (context.visit(node, _key)) return;
}
};
traverse.clearNode = function (node, opts) {
t.removeProperties(node, opts);
cache.path.delete(node);
};
traverse.removeProperties = function (tree, opts) {
t.traverseFast(tree, traverse.clearNode, opts);
return tree;
};
function hasBlacklistedType(path, state) {
if (path.node.type === state.type) {
state.has = true;
path.stop();
}
}
traverse.hasType = function (tree, type, blacklistTypes) {
if ((0, _includes.default)(blacklistTypes, tree.type)) return false;
if (tree.type === type) return true;
var state = {
has: false,
type: type
};
traverse(tree, {
noScope: true,
blacklist: blacklistTypes,
enter: hasBlacklistedType
}, null, state);
return state.has;
};
traverse.cache = cache;
@@ -0,0 +1,192 @@
"use strict";
exports.__esModule = true;
exports.findParent = findParent;
exports.find = find;
exports.getFunctionParent = getFunctionParent;
exports.getStatementParent = getStatementParent;
exports.getEarliestCommonAncestorFrom = getEarliestCommonAncestorFrom;
exports.getDeepestCommonAncestorFrom = getDeepestCommonAncestorFrom;
exports.getAncestry = getAncestry;
exports.isAncestor = isAncestor;
exports.isDescendant = isDescendant;
exports.inType = inType;
var t = _interopRequireWildcard(require("@babel/types"));
var _index = _interopRequireDefault(require("./index"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function findParent(callback) {
var path = this;
while (path = path.parentPath) {
if (callback(path)) return path;
}
return null;
}
function find(callback) {
var path = this;
do {
if (callback(path)) return path;
} while (path = path.parentPath);
return null;
}
function getFunctionParent() {
return this.findParent(function (p) {
return p.isFunction();
});
}
function getStatementParent() {
var path = this;
do {
if (!path.parentPath || Array.isArray(path.container) && path.isStatement()) {
break;
} else {
path = path.parentPath;
}
} while (path);
if (path && (path.isProgram() || path.isFile())) {
throw new Error("File/Program node, we can't possibly find a statement parent to this");
}
return path;
}
function getEarliestCommonAncestorFrom(paths) {
return this.getDeepestCommonAncestorFrom(paths, function (deepest, i, ancestries) {
var earliest;
var keys = t.VISITOR_KEYS[deepest.type];
var _arr = ancestries;
for (var _i = 0; _i < _arr.length; _i++) {
var ancestry = _arr[_i];
var path = ancestry[i + 1];
if (!earliest) {
earliest = path;
continue;
}
if (path.listKey && earliest.listKey === path.listKey) {
if (path.key < earliest.key) {
earliest = path;
continue;
}
}
var earliestKeyIndex = keys.indexOf(earliest.parentKey);
var currentKeyIndex = keys.indexOf(path.parentKey);
if (earliestKeyIndex > currentKeyIndex) {
earliest = path;
}
}
return earliest;
});
}
function getDeepestCommonAncestorFrom(paths, filter) {
var _this = this;
if (!paths.length) {
return this;
}
if (paths.length === 1) {
return paths[0];
}
var minDepth = Infinity;
var lastCommonIndex, lastCommon;
var ancestries = paths.map(function (path) {
var ancestry = [];
do {
ancestry.unshift(path);
} while ((path = path.parentPath) && path !== _this);
if (ancestry.length < minDepth) {
minDepth = ancestry.length;
}
return ancestry;
});
var first = ancestries[0];
depthLoop: for (var i = 0; i < minDepth; i++) {
var shouldMatch = first[i];
var _arr2 = ancestries;
for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
var ancestry = _arr2[_i2];
if (ancestry[i] !== shouldMatch) {
break depthLoop;
}
}
lastCommonIndex = i;
lastCommon = shouldMatch;
}
if (lastCommon) {
if (filter) {
return filter(lastCommon, lastCommonIndex, ancestries);
} else {
return lastCommon;
}
} else {
throw new Error("Couldn't find intersection");
}
}
function getAncestry() {
var path = this;
var paths = [];
do {
paths.push(path);
} while (path = path.parentPath);
return paths;
}
function isAncestor(maybeDescendant) {
return maybeDescendant.isDescendant(this);
}
function isDescendant(maybeAncestor) {
return !!this.findParent(function (parent) {
return parent === maybeAncestor;
});
}
function inType() {
var path = this;
while (path) {
var _arr3 = arguments;
for (var _i3 = 0; _i3 < _arr3.length; _i3++) {
var type = _arr3[_i3];
if (path.node.type === type) return true;
}
path = path.parentPath;
}
return false;
}
@@ -0,0 +1,37 @@
"use strict";
exports.__esModule = true;
exports.shareCommentsWithSiblings = shareCommentsWithSiblings;
exports.addComment = addComment;
exports.addComments = addComments;
var t = _interopRequireWildcard(require("@babel/types"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function shareCommentsWithSiblings() {
if (typeof this.key === "string") return;
var node = this.node;
if (!node) return;
var trailing = node.trailingComments;
var leading = node.leadingComments;
if (!trailing && !leading) return;
var prev = this.getSibling(this.key - 1);
var next = this.getSibling(this.key + 1);
var hasPrev = Boolean(prev.node);
var hasNext = Boolean(next.node);
if (hasPrev && hasNext) {} else if (hasPrev) {
prev.addComments("trailing", trailing);
} else if (hasNext) {
next.addComments("leading", leading);
}
}
function addComment(type, content, line) {
t.addComment(this.node, type, content, line);
}
function addComments(type, comments) {
t.addComments(this.node, type, comments);
}
@@ -0,0 +1,273 @@
"use strict";
exports.__esModule = true;
exports.call = call;
exports._call = _call;
exports.isBlacklisted = isBlacklisted;
exports.visit = visit;
exports.skip = skip;
exports.skipKey = skipKey;
exports.stop = stop;
exports.setScope = setScope;
exports.setContext = setContext;
exports.resync = resync;
exports._resyncParent = _resyncParent;
exports._resyncKey = _resyncKey;
exports._resyncList = _resyncList;
exports._resyncRemoved = _resyncRemoved;
exports.popContext = popContext;
exports.pushContext = pushContext;
exports.setup = setup;
exports.setKey = setKey;
exports.requeue = requeue;
exports._getQueueContexts = _getQueueContexts;
var _index = _interopRequireDefault(require("../index"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function call(key) {
var opts = this.opts;
this.debug(key);
if (this.node) {
if (this._call(opts[key])) return true;
}
if (this.node) {
return this._call(opts[this.node.type] && opts[this.node.type][key]);
}
return false;
}
function _call(fns) {
if (!fns) return false;
for (var _iterator = fns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var _fn = _ref;
if (!_fn) continue;
var node = this.node;
if (!node) return true;
var ret = _fn.call(this.state, this, this.state);
if (ret && typeof ret === "object" && typeof ret.then === "function") {
throw new Error("You appear to be using an plugin with an async traversay visitors, " + "which your current version of Babel does not support." + "If you're using a published plugin, you may need to upgrade " + "your @babel/core version.");
}
if (ret) {
throw new Error("Unexpected return value from visitor method " + _fn);
}
if (this.node !== node) return true;
if (this.shouldStop || this.shouldSkip || this.removed) return true;
}
return false;
}
function isBlacklisted() {
var blacklist = this.opts.blacklist;
return blacklist && blacklist.indexOf(this.node.type) > -1;
}
function visit() {
if (!this.node) {
return false;
}
if (this.isBlacklisted()) {
return false;
}
if (this.opts.shouldSkip && this.opts.shouldSkip(this)) {
return false;
}
if (this.call("enter") || this.shouldSkip) {
this.debug("Skip...");
return this.shouldStop;
}
this.debug("Recursing into...");
_index.default.node(this.node, this.opts, this.scope, this.state, this, this.skipKeys);
this.call("exit");
return this.shouldStop;
}
function skip() {
this.shouldSkip = true;
}
function skipKey(key) {
this.skipKeys[key] = true;
}
function stop() {
this.shouldStop = true;
this.shouldSkip = true;
}
function setScope() {
if (this.opts && this.opts.noScope) return;
var path = this.parentPath;
var target;
while (path && !target) {
if (path.opts && path.opts.noScope) return;
target = path.scope;
path = path.parentPath;
}
this.scope = this.getScope(target);
if (this.scope) this.scope.init();
}
function setContext(context) {
this.shouldSkip = false;
this.shouldStop = false;
this.removed = false;
this.skipKeys = {};
if (context) {
this.context = context;
this.state = context.state;
this.opts = context.opts;
}
this.setScope();
return this;
}
function resync() {
if (this.removed) return;
this._resyncParent();
this._resyncList();
this._resyncKey();
}
function _resyncParent() {
if (this.parentPath) {
this.parent = this.parentPath.node;
}
}
function _resyncKey() {
if (!this.container) return;
if (this.node === this.container[this.key]) return;
if (Array.isArray(this.container)) {
for (var i = 0; i < this.container.length; i++) {
if (this.container[i] === this.node) {
return this.setKey(i);
}
}
} else {
for (var key in this.container) {
if (this.container[key] === this.node) {
return this.setKey(key);
}
}
}
this.key = null;
}
function _resyncList() {
if (!this.parent || !this.inList) return;
var newContainer = this.parent[this.listKey];
if (this.container === newContainer) return;
this.container = newContainer || null;
}
function _resyncRemoved() {
if (this.key == null || !this.container || this.container[this.key] !== this.node) {
this._markRemoved();
}
}
function popContext() {
this.contexts.pop();
if (this.contexts.length > 0) {
this.setContext(this.contexts[this.contexts.length - 1]);
} else {
this.setContext(undefined);
}
}
function pushContext(context) {
this.contexts.push(context);
this.setContext(context);
}
function setup(parentPath, container, listKey, key) {
this.inList = !!listKey;
this.listKey = listKey;
this.parentKey = listKey || key;
this.container = container;
this.parentPath = parentPath || this.parentPath;
this.setKey(key);
}
function setKey(key) {
this.key = key;
this.node = this.container[this.key];
this.type = this.node && this.node.type;
}
function requeue(pathToQueue) {
if (pathToQueue === void 0) {
pathToQueue = this;
}
if (pathToQueue.removed) return;
var contexts = this.contexts;
for (var _iterator2 = contexts, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var _context = _ref2;
_context.maybeQueue(pathToQueue);
}
}
function _getQueueContexts() {
var path = this;
var contexts = this.contexts;
while (!contexts.length) {
path = path.parentPath;
if (!path) break;
contexts = path.contexts;
}
return contexts;
}
@@ -0,0 +1,446 @@
"use strict";
exports.__esModule = true;
exports.toComputedKey = toComputedKey;
exports.ensureBlock = ensureBlock;
exports.arrowFunctionToShadowed = arrowFunctionToShadowed;
exports.unwrapFunctionEnvironment = unwrapFunctionEnvironment;
exports.arrowFunctionToExpression = arrowFunctionToExpression;
var t = _interopRequireWildcard(require("@babel/types"));
var _helperFunctionName = _interopRequireDefault(require("@babel/helper-function-name"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function toComputedKey() {
var node = this.node;
var key;
if (this.isMemberExpression()) {
key = node.property;
} else if (this.isProperty() || this.isMethod()) {
key = node.key;
} else {
throw new ReferenceError("todo");
}
if (!node.computed) {
if (t.isIdentifier(key)) key = t.stringLiteral(key.name);
}
return key;
}
function ensureBlock() {
var body = this.get("body");
var bodyNode = body.node;
if (Array.isArray(body)) {
throw new Error("Can't convert array path to a block statement");
}
if (!bodyNode) {
throw new Error("Can't convert node without a body");
}
if (body.isBlockStatement()) {
return bodyNode;
}
var statements = [];
var stringPath = "body";
var key;
var listKey;
if (body.isStatement()) {
listKey = "body";
key = 0;
statements.push(body.node);
} else {
stringPath += ".body.0";
if (this.isFunction()) {
key = "argument";
statements.push(t.returnStatement(body.node));
} else {
key = "expression";
statements.push(t.expressionStatement(body.node));
}
}
this.node.body = t.blockStatement(statements);
var parentPath = this.get(stringPath);
body.setup(parentPath, listKey ? parentPath.node[listKey] : parentPath.node, listKey, key);
return this.node;
}
function arrowFunctionToShadowed() {
if (!this.isArrowFunctionExpression()) return;
this.arrowFunctionToExpression();
}
function unwrapFunctionEnvironment() {
if (!this.isArrowFunctionExpression() && !this.isFunctionExpression() && !this.isFunctionDeclaration()) {
throw this.buildCodeFrameError("Can only unwrap the environment of a function.");
}
hoistFunctionEnvironment(this);
}
function arrowFunctionToExpression(_temp) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$allowInsertArrow = _ref.allowInsertArrow,
allowInsertArrow = _ref$allowInsertArrow === void 0 ? true : _ref$allowInsertArrow,
_ref$specCompliant = _ref.specCompliant,
specCompliant = _ref$specCompliant === void 0 ? false : _ref$specCompliant;
if (!this.isArrowFunctionExpression()) {
throw this.buildCodeFrameError("Cannot convert non-arrow function to a function expression.");
}
var thisBinding = hoistFunctionEnvironment(this, specCompliant, allowInsertArrow);
this.ensureBlock();
this.node.type = "FunctionExpression";
if (specCompliant) {
var checkBinding = thisBinding ? null : this.parentPath.scope.generateUidIdentifier("arrowCheckId");
if (checkBinding) {
this.parentPath.scope.push({
id: checkBinding,
init: t.objectExpression([])
});
}
this.get("body").unshiftContainer("body", t.expressionStatement(t.callExpression(this.hub.file.addHelper("newArrowCheck"), [t.thisExpression(), checkBinding ? t.identifier(checkBinding.name) : t.identifier(thisBinding)])));
this.replaceWith(t.callExpression(t.memberExpression((0, _helperFunctionName.default)(this, true) || this.node, t.identifier("bind")), [checkBinding ? t.identifier(checkBinding.name) : t.thisExpression()]));
}
}
function hoistFunctionEnvironment(fnPath, specCompliant, allowInsertArrow) {
if (specCompliant === void 0) {
specCompliant = false;
}
if (allowInsertArrow === void 0) {
allowInsertArrow = true;
}
var thisEnvFn = fnPath.findParent(function (p) {
return p.isFunction() && !p.isArrowFunctionExpression() || p.isProgram() || p.isClassProperty({
static: false
});
});
var inConstructor = thisEnvFn && thisEnvFn.node.kind === "constructor";
if (thisEnvFn.isClassProperty()) {
throw fnPath.buildCodeFrameError("Unable to transform arrow inside class property");
}
var _getScopeInformation = getScopeInformation(fnPath),
thisPaths = _getScopeInformation.thisPaths,
argumentsPaths = _getScopeInformation.argumentsPaths,
newTargetPaths = _getScopeInformation.newTargetPaths,
superProps = _getScopeInformation.superProps,
superCalls = _getScopeInformation.superCalls;
if (inConstructor && superCalls.length > 0) {
if (!allowInsertArrow) {
throw superCalls[0].buildCodeFrameError("Unable to handle nested super() usage in arrow");
}
var allSuperCalls = [];
thisEnvFn.traverse({
Function: function Function(child) {
if (child.isArrowFunctionExpression()) return;
child.skip();
},
ClassProperty: function ClassProperty(child) {
if (child.node.static) return;
child.skip();
},
CallExpression: function CallExpression(child) {
if (!child.get("callee").isSuper()) return;
allSuperCalls.push(child);
}
});
var superBinding = getSuperBinding(thisEnvFn);
allSuperCalls.forEach(function (superCall) {
return superCall.get("callee").replaceWith(t.identifier(superBinding));
});
}
var thisBinding;
if (thisPaths.length > 0 || specCompliant) {
thisBinding = getThisBinding(thisEnvFn, inConstructor);
if (!specCompliant || inConstructor && hasSuperClass(thisEnvFn)) {
thisPaths.forEach(function (thisChild) {
thisChild.replaceWith(thisChild.isJSX() ? t.jsxIdentifier(thisBinding) : t.identifier(thisBinding));
});
if (specCompliant) thisBinding = null;
}
}
if (argumentsPaths.length > 0) {
var argumentsBinding = getBinding(thisEnvFn, "arguments", function () {
return t.identifier("arguments");
});
argumentsPaths.forEach(function (argumentsChild) {
argumentsChild.replaceWith(t.identifier(argumentsBinding));
});
}
if (newTargetPaths.length > 0) {
var newTargetBinding = getBinding(thisEnvFn, "newtarget", function () {
return t.metaProperty(t.identifier("new"), t.identifier("target"));
});
newTargetPaths.forEach(function (argumentsChild) {
argumentsChild.replaceWith(t.identifier(newTargetBinding));
});
}
if (superProps.length > 0) {
if (!allowInsertArrow) {
throw superProps[0].buildCodeFrameError("Unable to handle nested super.prop usage");
}
var flatSuperProps = superProps.reduce(function (acc, superProp) {
return acc.concat(standardizeSuperProperty(superProp));
}, []);
flatSuperProps.forEach(function (superProp) {
var key = superProp.node.computed ? "" : superProp.get("property").node.name;
if (superProp.parentPath.isCallExpression({
callee: superProp.node
})) {
var _superBinding = getSuperPropCallBinding(thisEnvFn, key);
if (superProp.node.computed) {
var prop = superProp.get("property").node;
superProp.replaceWith(t.identifier(_superBinding));
superProp.parentPath.node.arguments.unshift(prop);
} else {
superProp.replaceWith(t.identifier(_superBinding));
}
} else {
var isAssignment = superProp.parentPath.isAssignmentExpression({
left: superProp.node
});
var _superBinding2 = getSuperPropBinding(thisEnvFn, isAssignment, key);
var args = [];
if (superProp.node.computed) {
args.push(superProp.get("property").node);
}
if (isAssignment) {
var value = superProp.parentPath.node.right;
args.push(value);
superProp.parentPath.replaceWith(t.callExpression(t.identifier(_superBinding2), args));
} else {
superProp.replaceWith(t.callExpression(t.identifier(_superBinding2), args));
}
}
});
}
return thisBinding;
}
function standardizeSuperProperty(superProp) {
if (superProp.parentPath.isAssignmentExpression() && superProp.parentPath.node.operator !== "=") {
var assignmentPath = superProp.parentPath;
var op = assignmentPath.node.operator.slice(0, -1);
var value = assignmentPath.node.right;
assignmentPath.node.operator = "=";
if (superProp.node.computed) {
var tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
assignmentPath.get("left").replaceWith(t.memberExpression(superProp.node.object, t.assignmentExpression("=", tmp, superProp.node.property), true));
assignmentPath.get("right").replaceWith(t.binaryExpression(op, t.memberExpression(superProp.node.object, t.identifier(tmp.name), true), value));
} else {
assignmentPath.get("left").replaceWith(t.memberExpression(superProp.node.object, superProp.node.property));
assignmentPath.get("right").replaceWith(t.binaryExpression(op, t.memberExpression(superProp.node.object, t.identifier(superProp.node.property.name)), value));
}
return [assignmentPath.get("left"), assignmentPath.get("right").get("left")];
} else if (superProp.parentPath.isUpdateExpression()) {
var updateExpr = superProp.parentPath;
var _tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
var computedKey = superProp.node.computed ? superProp.scope.generateDeclaredUidIdentifier("prop") : null;
var parts = [t.assignmentExpression("=", _tmp, t.memberExpression(superProp.node.object, computedKey ? t.assignmentExpression("=", computedKey, superProp.node.property) : superProp.node.property, superProp.node.computed)), t.assignmentExpression("=", t.memberExpression(superProp.node.object, computedKey ? t.identifier(computedKey.name) : superProp.node.property, superProp.node.computed), t.binaryExpression("+", t.identifier(_tmp.name), t.numericLiteral(1)))];
if (!superProp.parentPath.node.prefix) {
parts.push(t.identifier(_tmp.name));
}
updateExpr.replaceWith(t.sequenceExpression(parts));
var left = updateExpr.get("expressions.0.right");
var right = updateExpr.get("expressions.1.left");
return [left, right];
}
return [superProp];
}
function hasSuperClass(thisEnvFn) {
return thisEnvFn.isClassMethod() && !!thisEnvFn.parentPath.parentPath.node.superClass;
}
function getThisBinding(thisEnvFn, inConstructor) {
return getBinding(thisEnvFn, "this", function (thisBinding) {
if (!inConstructor || !hasSuperClass(thisEnvFn)) return t.thisExpression();
var supers = new WeakSet();
thisEnvFn.traverse({
Function: function Function(child) {
if (child.isArrowFunctionExpression()) return;
child.skip();
},
ClassProperty: function ClassProperty(child) {
if (child.node.static) return;
child.skip();
},
CallExpression: function CallExpression(child) {
if (!child.get("callee").isSuper()) return;
if (supers.has(child.node)) return;
supers.add(child.node);
child.replaceWith(t.assignmentExpression("=", t.identifier(thisBinding), child.node));
}
});
});
}
function getSuperBinding(thisEnvFn) {
return getBinding(thisEnvFn, "supercall", function () {
var argsBinding = thisEnvFn.scope.generateUidIdentifier("args");
return t.arrowFunctionExpression([t.restElement(argsBinding)], t.callExpression(t.super(), [t.spreadElement(t.identifier(argsBinding.name))]));
});
}
function getSuperPropCallBinding(thisEnvFn, propName) {
return getBinding(thisEnvFn, "superprop_call:" + (propName || ""), function () {
var argsBinding = thisEnvFn.scope.generateUidIdentifier("args");
var argsList = [t.restElement(argsBinding)];
var fnBody;
if (propName) {
fnBody = t.callExpression(t.memberExpression(t.super(), t.identifier(propName)), [t.spreadElement(t.identifier(argsBinding.name))]);
} else {
var method = thisEnvFn.scope.generateUidIdentifier("prop");
argsList.unshift(method);
fnBody = t.callExpression(t.memberExpression(t.super(), t.identifier(method.name), true), [t.spreadElement(t.identifier(argsBinding.name))]);
}
return t.arrowFunctionExpression(argsList, fnBody);
});
}
function getSuperPropBinding(thisEnvFn, isAssignment, propName) {
var op = isAssignment ? "set" : "get";
return getBinding(thisEnvFn, "superprop_" + op + ":" + (propName || ""), function () {
var argsList = [];
var fnBody;
if (propName) {
fnBody = t.memberExpression(t.super(), t.identifier(propName));
} else {
var method = thisEnvFn.scope.generateUidIdentifier("prop");
argsList.unshift(method);
fnBody = t.memberExpression(t.super(), t.identifier(method.name), true);
}
if (isAssignment) {
var valueIdent = thisEnvFn.scope.generateUidIdentifier("value");
argsList.push(valueIdent);
fnBody = t.assignmentExpression("=", fnBody, t.identifier(valueIdent.name));
}
return t.arrowFunctionExpression(argsList, fnBody);
});
}
function getBinding(thisEnvFn, key, init) {
var cacheKey = "binding:" + key;
var data = thisEnvFn.getData(cacheKey);
if (!data) {
var id = thisEnvFn.scope.generateUidIdentifier(key);
data = id.name;
thisEnvFn.setData(cacheKey, data);
thisEnvFn.scope.push({
id: id,
init: init(data)
});
}
return data;
}
function getScopeInformation(fnPath) {
var thisPaths = [];
var argumentsPaths = [];
var newTargetPaths = [];
var superProps = [];
var superCalls = [];
fnPath.traverse({
ClassProperty: function ClassProperty(child) {
if (child.node.static) return;
child.skip();
},
Function: function Function(child) {
if (child.isArrowFunctionExpression()) return;
child.skip();
},
ThisExpression: function ThisExpression(child) {
thisPaths.push(child);
},
JSXIdentifier: function JSXIdentifier(child) {
if (child.node.name !== "this") return;
if (!child.parentPath.isJSXMemberExpression({
object: child.node
}) && !child.parentPath.isJSXOpeningElement({
name: child.node
})) {
return;
}
thisPaths.push(child);
},
CallExpression: function CallExpression(child) {
if (child.get("callee").isSuper()) superCalls.push(child);
},
MemberExpression: function MemberExpression(child) {
if (child.get("object").isSuper()) superProps.push(child);
},
ReferencedIdentifier: function ReferencedIdentifier(child) {
if (child.node.name !== "arguments") return;
argumentsPaths.push(child);
},
MetaProperty: function MetaProperty(child) {
if (!child.get("meta").isIdentifier({
name: "new"
})) return;
if (!child.get("property").isIdentifier({
name: "target"
})) return;
newTargetPaths.push(child);
}
});
return {
thisPaths: thisPaths,
argumentsPaths: argumentsPaths,
newTargetPaths: newTargetPaths,
superProps: superProps,
superCalls: superCalls
};
}
@@ -0,0 +1,451 @@
"use strict";
exports.__esModule = true;
exports.evaluateTruthy = evaluateTruthy;
exports.evaluate = evaluate;
var VALID_CALLEES = ["String", "Number", "Math"];
var INVALID_METHODS = ["random"];
function evaluateTruthy() {
var res = this.evaluate();
if (res.confident) return !!res.value;
}
function deopt(path, state) {
if (!state.confident) return;
state.deoptPath = path;
state.confident = false;
}
function evaluateCached(path, state) {
var node = path.node;
var seen = state.seen;
if (seen.has(node)) {
var existing = seen.get(node);
if (existing.resolved) {
return existing.value;
} else {
deopt(path, state);
return;
}
} else {
var item = {
resolved: false
};
seen.set(node, item);
var val = _evaluate(path, state);
if (state.confident) {
item.resolved = true;
item.value = val;
}
return val;
}
}
function _evaluate(path, state) {
if (!state.confident) return;
var node = path.node;
if (path.isSequenceExpression()) {
var exprs = path.get("expressions");
return evaluateCached(exprs[exprs.length - 1], state);
}
if (path.isStringLiteral() || path.isNumericLiteral() || path.isBooleanLiteral()) {
return node.value;
}
if (path.isNullLiteral()) {
return null;
}
if (path.isTemplateLiteral()) {
return evaluateQuasis(path, node.quasis, state);
}
if (path.isTaggedTemplateExpression() && path.get("tag").isMemberExpression()) {
var object = path.get("tag.object");
var name = object.node.name;
var property = path.get("tag.property");
if (object.isIdentifier() && name === "String" && !path.scope.getBinding(name, true) && property.isIdentifier && property.node.name === "raw") {
return evaluateQuasis(path, node.quasi.quasis, state, true);
}
}
if (path.isConditionalExpression()) {
var testResult = evaluateCached(path.get("test"), state);
if (!state.confident) return;
if (testResult) {
return evaluateCached(path.get("consequent"), state);
} else {
return evaluateCached(path.get("alternate"), state);
}
}
if (path.isExpressionWrapper()) {
return evaluateCached(path.get("expression"), state);
}
if (path.isMemberExpression() && !path.parentPath.isCallExpression({
callee: node
})) {
var _property = path.get("property");
var _object = path.get("object");
if (_object.isLiteral() && _property.isIdentifier()) {
var value = _object.node.value;
var type = typeof value;
if (type === "number" || type === "string") {
return value[_property.node.name];
}
}
}
if (path.isReferencedIdentifier()) {
var binding = path.scope.getBinding(node.name);
if (binding && binding.constantViolations.length > 0) {
return deopt(binding.path, state);
}
if (binding && path.node.start < binding.path.node.end) {
return deopt(binding.path, state);
}
if (binding && binding.hasValue) {
return binding.value;
} else {
if (node.name === "undefined") {
return binding ? deopt(binding.path, state) : undefined;
} else if (node.name === "Infinity") {
return binding ? deopt(binding.path, state) : Infinity;
} else if (node.name === "NaN") {
return binding ? deopt(binding.path, state) : NaN;
}
var resolved = path.resolve();
if (resolved === path) {
return deopt(path, state);
} else {
return evaluateCached(resolved, state);
}
}
}
if (path.isUnaryExpression({
prefix: true
})) {
if (node.operator === "void") {
return undefined;
}
var argument = path.get("argument");
if (node.operator === "typeof" && (argument.isFunction() || argument.isClass())) {
return "function";
}
var arg = evaluateCached(argument, state);
if (!state.confident) return;
switch (node.operator) {
case "!":
return !arg;
case "+":
return +arg;
case "-":
return -arg;
case "~":
return ~arg;
case "typeof":
return typeof arg;
}
}
if (path.isArrayExpression()) {
var arr = [];
var elems = path.get("elements");
for (var _iterator = elems, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var _elem = _ref;
var elemValue = _elem.evaluate();
if (elemValue.confident) {
arr.push(elemValue.value);
} else {
return deopt(_elem, state);
}
}
return arr;
}
if (path.isObjectExpression()) {
var obj = {};
var props = path.get("properties");
for (var _iterator2 = props, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var _prop = _ref2;
if (_prop.isObjectMethod() || _prop.isSpreadElement()) {
return deopt(_prop, state);
}
var keyPath = _prop.get("key");
var key = keyPath;
if (_prop.node.computed) {
key = key.evaluate();
if (!key.confident) {
return deopt(keyPath, state);
}
key = key.value;
} else if (key.isIdentifier()) {
key = key.node.name;
} else {
key = key.node.value;
}
var valuePath = _prop.get("value");
var _value2 = valuePath.evaluate();
if (!_value2.confident) {
return deopt(valuePath, state);
}
_value2 = _value2.value;
obj[key] = _value2;
}
return obj;
}
if (path.isLogicalExpression()) {
var wasConfident = state.confident;
var left = evaluateCached(path.get("left"), state);
var leftConfident = state.confident;
state.confident = wasConfident;
var right = evaluateCached(path.get("right"), state);
var rightConfident = state.confident;
state.confident = leftConfident && rightConfident;
switch (node.operator) {
case "||":
if (left && leftConfident) {
state.confident = true;
return left;
}
if (!state.confident) return;
return left || right;
case "&&":
if (!left && leftConfident || !right && rightConfident) {
state.confident = true;
}
if (!state.confident) return;
return left && right;
}
}
if (path.isBinaryExpression()) {
var _left = evaluateCached(path.get("left"), state);
if (!state.confident) return;
var _right = evaluateCached(path.get("right"), state);
if (!state.confident) return;
switch (node.operator) {
case "-":
return _left - _right;
case "+":
return _left + _right;
case "/":
return _left / _right;
case "*":
return _left * _right;
case "%":
return _left % _right;
case "**":
return Math.pow(_left, _right);
case "<":
return _left < _right;
case ">":
return _left > _right;
case "<=":
return _left <= _right;
case ">=":
return _left >= _right;
case "==":
return _left == _right;
case "!=":
return _left != _right;
case "===":
return _left === _right;
case "!==":
return _left !== _right;
case "|":
return _left | _right;
case "&":
return _left & _right;
case "^":
return _left ^ _right;
case "<<":
return _left << _right;
case ">>":
return _left >> _right;
case ">>>":
return _left >>> _right;
}
}
if (path.isCallExpression()) {
var callee = path.get("callee");
var context;
var func;
if (callee.isIdentifier() && !path.scope.getBinding(callee.node.name, true) && VALID_CALLEES.indexOf(callee.node.name) >= 0) {
func = global[node.callee.name];
}
if (callee.isMemberExpression()) {
var _object2 = callee.get("object");
var _property2 = callee.get("property");
if (_object2.isIdentifier() && _property2.isIdentifier() && VALID_CALLEES.indexOf(_object2.node.name) >= 0 && INVALID_METHODS.indexOf(_property2.node.name) < 0) {
context = global[_object2.node.name];
func = context[_property2.node.name];
}
if (_object2.isLiteral() && _property2.isIdentifier()) {
var _type = typeof _object2.node.value;
if (_type === "string" || _type === "number") {
context = _object2.node.value;
func = context[_property2.node.name];
}
}
}
if (func) {
var args = path.get("arguments").map(function (arg) {
return evaluateCached(arg, state);
});
if (!state.confident) return;
return func.apply(context, args);
}
}
deopt(path, state);
}
function evaluateQuasis(path, quasis, state, raw) {
if (raw === void 0) {
raw = false;
}
var str = "";
var i = 0;
var exprs = path.get("expressions");
for (var _iterator3 = quasis, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var _elem2 = _ref3;
if (!state.confident) break;
str += raw ? _elem2.value.raw : _elem2.value.cooked;
var expr = exprs[i++];
if (expr) str += String(evaluateCached(expr, state));
}
if (!state.confident) return;
return str;
}
function evaluate() {
var state = {
confident: true,
deoptPath: null,
seen: new Map()
};
var value = evaluateCached(this, state);
if (!state.confident) value = undefined;
return {
confident: state.confident,
deopt: state.deoptPath,
value: value
};
}
@@ -0,0 +1,244 @@
"use strict";
exports.__esModule = true;
exports.getOpposite = getOpposite;
exports.getCompletionRecords = getCompletionRecords;
exports.getSibling = getSibling;
exports.getPrevSibling = getPrevSibling;
exports.getNextSibling = getNextSibling;
exports.getAllNextSiblings = getAllNextSiblings;
exports.getAllPrevSiblings = getAllPrevSiblings;
exports.get = get;
exports._getKey = _getKey;
exports._getPattern = _getPattern;
exports.getBindingIdentifiers = getBindingIdentifiers;
exports.getOuterBindingIdentifiers = getOuterBindingIdentifiers;
exports.getBindingIdentifierPaths = getBindingIdentifierPaths;
exports.getOuterBindingIdentifierPaths = getOuterBindingIdentifierPaths;
var _index = _interopRequireDefault(require("./index"));
var t = _interopRequireWildcard(require("@babel/types"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getOpposite() {
if (this.key === "left") {
return this.getSibling("right");
} else if (this.key === "right") {
return this.getSibling("left");
}
}
function addCompletionRecords(path, paths) {
if (path) return paths.concat(path.getCompletionRecords());
return paths;
}
function getCompletionRecords() {
var paths = [];
if (this.isIfStatement()) {
paths = addCompletionRecords(this.get("consequent"), paths);
paths = addCompletionRecords(this.get("alternate"), paths);
} else if (this.isDoExpression() || this.isFor() || this.isWhile()) {
paths = addCompletionRecords(this.get("body"), paths);
} else if (this.isProgram() || this.isBlockStatement()) {
paths = addCompletionRecords(this.get("body").pop(), paths);
} else if (this.isFunction()) {
return this.get("body").getCompletionRecords();
} else if (this.isTryStatement()) {
paths = addCompletionRecords(this.get("block"), paths);
paths = addCompletionRecords(this.get("handler"), paths);
paths = addCompletionRecords(this.get("finalizer"), paths);
} else if (this.isCatchClause()) {
paths = addCompletionRecords(this.get("body"), paths);
} else {
paths.push(this);
}
return paths;
}
function getSibling(key) {
return _index.default.get({
parentPath: this.parentPath,
parent: this.parent,
container: this.container,
listKey: this.listKey,
key: key
});
}
function getPrevSibling() {
return this.getSibling(this.key - 1);
}
function getNextSibling() {
return this.getSibling(this.key + 1);
}
function getAllNextSiblings() {
var _key = this.key;
var sibling = this.getSibling(++_key);
var siblings = [];
while (sibling.node) {
siblings.push(sibling);
sibling = this.getSibling(++_key);
}
return siblings;
}
function getAllPrevSiblings() {
var _key = this.key;
var sibling = this.getSibling(--_key);
var siblings = [];
while (sibling.node) {
siblings.push(sibling);
sibling = this.getSibling(--_key);
}
return siblings;
}
function get(key, context) {
if (context === true) context = this.context;
var parts = key.split(".");
if (parts.length === 1) {
return this._getKey(key, context);
} else {
return this._getPattern(parts, context);
}
}
function _getKey(key, context) {
var _this = this;
var node = this.node;
var container = node[key];
if (Array.isArray(container)) {
return container.map(function (_, i) {
return _index.default.get({
listKey: key,
parentPath: _this,
parent: node,
container: container,
key: i
}).setContext(context);
});
} else {
return _index.default.get({
parentPath: this,
parent: node,
container: node,
key: key
}).setContext(context);
}
}
function _getPattern(parts, context) {
var path = this;
var _arr = parts;
for (var _i = 0; _i < _arr.length; _i++) {
var part = _arr[_i];
if (part === ".") {
path = path.parentPath;
} else {
if (Array.isArray(path)) {
path = path[part];
} else {
path = path.get(part, context);
}
}
}
return path;
}
function getBindingIdentifiers(duplicates) {
return t.getBindingIdentifiers(this.node, duplicates);
}
function getOuterBindingIdentifiers(duplicates) {
return t.getOuterBindingIdentifiers(this.node, duplicates);
}
function getBindingIdentifierPaths(duplicates, outerOnly) {
if (duplicates === void 0) {
duplicates = false;
}
if (outerOnly === void 0) {
outerOnly = false;
}
var path = this;
var search = [].concat(path);
var ids = Object.create(null);
while (search.length) {
var id = search.shift();
if (!id) continue;
if (!id.node) continue;
var keys = t.getBindingIdentifiers.keys[id.node.type];
if (id.isIdentifier()) {
if (duplicates) {
var _ids = ids[id.node.name] = ids[id.node.name] || [];
_ids.push(id);
} else {
ids[id.node.name] = id;
}
continue;
}
if (id.isExportDeclaration()) {
var declaration = id.get("declaration");
if (declaration.isDeclaration()) {
search.push(declaration);
}
continue;
}
if (outerOnly) {
if (id.isFunctionDeclaration()) {
search.push(id.get("id"));
continue;
}
if (id.isFunctionExpression()) {
continue;
}
}
if (keys) {
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var child = id.get(key);
if (Array.isArray(child) || child.node) {
search = search.concat(child);
}
}
}
}
return ids;
}
function getOuterBindingIdentifierPaths(duplicates) {
return this.getBindingIdentifierPaths(duplicates, true);
}
@@ -0,0 +1,228 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var virtualTypes = _interopRequireWildcard(require("./lib/virtual-types"));
var _debug2 = _interopRequireDefault(require("debug"));
var _invariant = _interopRequireDefault(require("invariant"));
var _index = _interopRequireDefault(require("../index"));
var _scope = _interopRequireDefault(require("../scope"));
var t = _interopRequireWildcard(require("@babel/types"));
var _cache = require("../cache");
var NodePath_ancestry = _interopRequireWildcard(require("./ancestry"));
var NodePath_inference = _interopRequireWildcard(require("./inference"));
var NodePath_replacement = _interopRequireWildcard(require("./replacement"));
var NodePath_evaluation = _interopRequireWildcard(require("./evaluation"));
var NodePath_conversion = _interopRequireWildcard(require("./conversion"));
var NodePath_introspection = _interopRequireWildcard(require("./introspection"));
var NodePath_context = _interopRequireWildcard(require("./context"));
var NodePath_removal = _interopRequireWildcard(require("./removal"));
var NodePath_modification = _interopRequireWildcard(require("./modification"));
var NodePath_family = _interopRequireWildcard(require("./family"));
var NodePath_comments = _interopRequireWildcard(require("./comments"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
var _debug = (0, _debug2.default)("babel");
var NodePath = function () {
function NodePath(hub, parent) {
this.parent = void 0;
this.hub = void 0;
this.contexts = void 0;
this.data = void 0;
this.shouldSkip = void 0;
this.shouldStop = void 0;
this.removed = void 0;
this.state = void 0;
this.opts = void 0;
this.skipKeys = void 0;
this.parentPath = void 0;
this.context = void 0;
this.container = void 0;
this.listKey = void 0;
this.inList = void 0;
this.parentKey = void 0;
this.key = void 0;
this.node = void 0;
this.scope = void 0;
this.type = void 0;
this.typeAnnotation = void 0;
this.parent = parent;
this.hub = hub;
this.contexts = [];
this.data = {};
this.shouldSkip = false;
this.shouldStop = false;
this.removed = false;
this.state = null;
this.opts = null;
this.skipKeys = null;
this.parentPath = null;
this.context = null;
this.container = null;
this.listKey = null;
this.inList = false;
this.parentKey = null;
this.key = null;
this.node = null;
this.scope = null;
this.type = null;
this.typeAnnotation = null;
}
NodePath.get = function get(_ref) {
var hub = _ref.hub,
parentPath = _ref.parentPath,
parent = _ref.parent,
container = _ref.container,
listKey = _ref.listKey,
key = _ref.key;
if (!hub && parentPath) {
hub = parentPath.hub;
}
(0, _invariant.default)(parent, "To get a node path the parent needs to exist");
var targetNode = container[key];
var paths = _cache.path.get(parent) || [];
if (!_cache.path.has(parent)) {
_cache.path.set(parent, paths);
}
var path;
for (var i = 0; i < paths.length; i++) {
var pathCheck = paths[i];
if (pathCheck.node === targetNode) {
path = pathCheck;
break;
}
}
if (!path) {
path = new NodePath(hub, parent);
paths.push(path);
}
path.setup(parentPath, container, listKey, key);
return path;
};
var _proto = NodePath.prototype;
_proto.getScope = function getScope(scope) {
return this.isScope() ? new _scope.default(this) : scope;
};
_proto.setData = function setData(key, val) {
return this.data[key] = val;
};
_proto.getData = function getData(key, def) {
var val = this.data[key];
if (!val && def) val = this.data[key] = def;
return val;
};
_proto.buildCodeFrameError = function buildCodeFrameError(msg, Error) {
if (Error === void 0) {
Error = SyntaxError;
}
return this.hub.file.buildCodeFrameError(this.node, msg, Error);
};
_proto.traverse = function traverse(visitor, state) {
(0, _index.default)(this.node, visitor, this.scope, state, this);
};
_proto.set = function set(key, node) {
t.validate(this.node, key, node);
this.node[key] = node;
};
_proto.getPathLocation = function getPathLocation() {
var parts = [];
var path = this;
do {
var key = path.key;
if (path.inList) key = path.listKey + "[" + key + "]";
parts.unshift(key);
} while (path = path.parentPath);
return parts.join(".");
};
_proto.debug = function debug(message) {
if (!_debug.enabled) return;
_debug(this.getPathLocation() + " " + this.type + ": " + message);
};
return NodePath;
}();
exports.default = NodePath;
Object.assign(NodePath.prototype, NodePath_ancestry, NodePath_inference, NodePath_replacement, NodePath_evaluation, NodePath_conversion, NodePath_introspection, NodePath_context, NodePath_removal, NodePath_modification, NodePath_family, NodePath_comments);
var _loop = function _loop(type) {
var typeKey = "is" + type;
NodePath.prototype[typeKey] = function (opts) {
return t[typeKey](this.node, opts);
};
NodePath.prototype["assert" + type] = function (opts) {
if (!this[typeKey](opts)) {
throw new TypeError("Expected node path of type " + type);
}
};
};
var _arr = t.TYPES;
for (var _i = 0; _i < _arr.length; _i++) {
var type = _arr[_i];
_loop(type);
}
var _loop2 = function _loop2(type) {
if (type[0] === "_") return "continue";
if (t.TYPES.indexOf(type) < 0) t.TYPES.push(type);
var virtualType = virtualTypes[type];
NodePath.prototype["is" + type] = function (opts) {
return virtualType.checkPath(this, opts);
};
};
for (var type in virtualTypes) {
var _ret = _loop2(type);
if (_ret === "continue") continue;
}
@@ -0,0 +1,126 @@
"use strict";
exports.__esModule = true;
exports.getTypeAnnotation = getTypeAnnotation;
exports._getTypeAnnotation = _getTypeAnnotation;
exports.isBaseType = isBaseType;
exports.couldBeBaseType = couldBeBaseType;
exports.baseTypeStrictlyMatches = baseTypeStrictlyMatches;
exports.isGenericType = isGenericType;
var inferers = _interopRequireWildcard(require("./inferers"));
var t = _interopRequireWildcard(require("@babel/types"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function getTypeAnnotation() {
if (this.typeAnnotation) return this.typeAnnotation;
var type = this._getTypeAnnotation() || t.anyTypeAnnotation();
if (t.isTypeAnnotation(type)) type = type.typeAnnotation;
return this.typeAnnotation = type;
}
function _getTypeAnnotation() {
var node = this.node;
if (!node) {
if (this.key === "init" && this.parentPath.isVariableDeclarator()) {
var declar = this.parentPath.parentPath;
var declarParent = declar.parentPath;
if (declar.key === "left" && declarParent.isForInStatement()) {
return t.stringTypeAnnotation();
}
if (declar.key === "left" && declarParent.isForOfStatement()) {
return t.anyTypeAnnotation();
}
return t.voidTypeAnnotation();
} else {
return;
}
}
if (node.typeAnnotation) {
return node.typeAnnotation;
}
var inferer = inferers[node.type];
if (inferer) {
return inferer.call(this, node);
}
inferer = inferers[this.parentPath.type];
if (inferer && inferer.validParent) {
return this.parentPath.getTypeAnnotation();
}
}
function isBaseType(baseName, soft) {
return _isBaseType(baseName, this.getTypeAnnotation(), soft);
}
function _isBaseType(baseName, type, soft) {
if (baseName === "string") {
return t.isStringTypeAnnotation(type);
} else if (baseName === "number") {
return t.isNumberTypeAnnotation(type);
} else if (baseName === "boolean") {
return t.isBooleanTypeAnnotation(type);
} else if (baseName === "any") {
return t.isAnyTypeAnnotation(type);
} else if (baseName === "mixed") {
return t.isMixedTypeAnnotation(type);
} else if (baseName === "empty") {
return t.isEmptyTypeAnnotation(type);
} else if (baseName === "void") {
return t.isVoidTypeAnnotation(type);
} else {
if (soft) {
return false;
} else {
throw new Error("Unknown base type " + baseName);
}
}
}
function couldBeBaseType(name) {
var type = this.getTypeAnnotation();
if (t.isAnyTypeAnnotation(type)) return true;
if (t.isUnionTypeAnnotation(type)) {
var _arr = type.types;
for (var _i = 0; _i < _arr.length; _i++) {
var type2 = _arr[_i];
if (t.isAnyTypeAnnotation(type2) || _isBaseType(name, type2, true)) {
return true;
}
}
return false;
} else {
return _isBaseType(name, type, true);
}
}
function baseTypeStrictlyMatches(right) {
var left = this.getTypeAnnotation();
right = right.getTypeAnnotation();
if (!t.isAnyTypeAnnotation(left) && t.isFlowBaseAnnotation(left)) {
return right.type === left.type;
}
}
function isGenericType(genericName) {
var type = this.getTypeAnnotation();
return t.isGenericTypeAnnotation(type) && t.isIdentifier(type.id, {
name: genericName
});
}
@@ -0,0 +1,175 @@
"use strict";
exports.__esModule = true;
exports.default = _default;
var t = _interopRequireWildcard(require("@babel/types"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _default(node) {
if (!this.isReferenced()) return;
var binding = this.scope.getBinding(node.name);
if (binding) {
if (binding.identifier.typeAnnotation) {
return binding.identifier.typeAnnotation;
} else {
return getTypeAnnotationBindingConstantViolations(binding, this, node.name);
}
}
if (node.name === "undefined") {
return t.voidTypeAnnotation();
} else if (node.name === "NaN" || node.name === "Infinity") {
return t.numberTypeAnnotation();
} else if (node.name === "arguments") {}
}
function getTypeAnnotationBindingConstantViolations(binding, path, name) {
var types = [];
var functionConstantViolations = [];
var constantViolations = getConstantViolationsBefore(binding, path, functionConstantViolations);
var testType = getConditionalAnnotation(binding, path, name);
if (testType) {
var testConstantViolations = getConstantViolationsBefore(binding, testType.ifStatement);
constantViolations = constantViolations.filter(function (path) {
return testConstantViolations.indexOf(path) < 0;
});
types.push(testType.typeAnnotation);
}
if (constantViolations.length) {
constantViolations = constantViolations.concat(functionConstantViolations);
var _arr = constantViolations;
for (var _i = 0; _i < _arr.length; _i++) {
var violation = _arr[_i];
types.push(violation.getTypeAnnotation());
}
}
if (types.length) {
return t.createUnionTypeAnnotation(types);
}
}
function getConstantViolationsBefore(binding, path, functions) {
var violations = binding.constantViolations.slice();
violations.unshift(binding.path);
return violations.filter(function (violation) {
violation = violation.resolve();
var status = violation._guessExecutionStatusRelativeTo(path);
if (functions && status === "function") functions.push(violation);
return status === "before";
});
}
function inferAnnotationFromBinaryExpression(name, path) {
var operator = path.node.operator;
var right = path.get("right").resolve();
var left = path.get("left").resolve();
var target;
if (left.isIdentifier({
name: name
})) {
target = right;
} else if (right.isIdentifier({
name: name
})) {
target = left;
}
if (target) {
if (operator === "===") {
return target.getTypeAnnotation();
}
if (t.BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) {
return t.numberTypeAnnotation();
}
return;
}
if (operator !== "===" && operator !== "==") return;
var typeofPath;
var typePath;
if (left.isUnaryExpression({
operator: "typeof"
})) {
typeofPath = left;
typePath = right;
} else if (right.isUnaryExpression({
operator: "typeof"
})) {
typeofPath = right;
typePath = left;
}
if (!typeofPath) return;
if (!typeofPath.get("argument").isIdentifier({
name: name
})) return;
typePath = typePath.resolve();
if (!typePath.isLiteral()) return;
var typeValue = typePath.node.value;
if (typeof typeValue !== "string") return;
return t.createTypeAnnotationBasedOnTypeof(typeValue);
}
function getParentConditionalPath(binding, path, name) {
var parentPath;
while (parentPath = path.parentPath) {
if (parentPath.isIfStatement() || parentPath.isConditionalExpression()) {
if (path.key === "test") {
return;
}
return parentPath;
}
if (parentPath.isFunction()) {
if (parentPath.parentPath.scope.getBinding(name) !== binding) return;
}
path = parentPath;
}
}
function getConditionalAnnotation(binding, path, name) {
var ifStatement = getParentConditionalPath(binding, path, name);
if (!ifStatement) return;
var test = ifStatement.get("test");
var paths = [test];
var types = [];
for (var i = 0; i < paths.length; i++) {
var _path = paths[i];
if (_path.isLogicalExpression()) {
if (_path.node.operator === "&&") {
paths.push(_path.get("left"));
paths.push(_path.get("right"));
}
} else if (_path.isBinaryExpression()) {
var type = inferAnnotationFromBinaryExpression(name, _path);
if (type) types.push(type);
}
}
if (types.length) {
return {
typeAnnotation: t.createUnionTypeAnnotation(types),
ifStatement: ifStatement
};
}
return getConditionalAnnotation(ifStatement, name);
}
@@ -0,0 +1,207 @@
"use strict";
exports.__esModule = true;
exports.VariableDeclarator = VariableDeclarator;
exports.TypeCastExpression = TypeCastExpression;
exports.NewExpression = NewExpression;
exports.TemplateLiteral = TemplateLiteral;
exports.UnaryExpression = UnaryExpression;
exports.BinaryExpression = BinaryExpression;
exports.LogicalExpression = LogicalExpression;
exports.ConditionalExpression = ConditionalExpression;
exports.SequenceExpression = SequenceExpression;
exports.AssignmentExpression = AssignmentExpression;
exports.UpdateExpression = UpdateExpression;
exports.StringLiteral = StringLiteral;
exports.NumericLiteral = NumericLiteral;
exports.BooleanLiteral = BooleanLiteral;
exports.NullLiteral = NullLiteral;
exports.RegExpLiteral = RegExpLiteral;
exports.ObjectExpression = ObjectExpression;
exports.ArrayExpression = ArrayExpression;
exports.RestElement = RestElement;
exports.ClassDeclaration = exports.ClassExpression = exports.FunctionDeclaration = exports.ArrowFunctionExpression = exports.FunctionExpression = Func;
exports.CallExpression = CallExpression;
exports.TaggedTemplateExpression = TaggedTemplateExpression;
exports.Identifier = void 0;
var t = _interopRequireWildcard(require("@babel/types"));
var _infererReference = _interopRequireDefault(require("./inferer-reference"));
exports.Identifier = _infererReference.default;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function VariableDeclarator() {
var id = this.get("id");
if (!id.isIdentifier()) return;
var init = this.get("init");
var type = init.getTypeAnnotation();
if (type && type.type === "AnyTypeAnnotation") {
if (init.isCallExpression() && init.get("callee").isIdentifier({
name: "Array"
}) && !init.scope.hasBinding("Array", true)) {
type = ArrayExpression();
}
}
return type;
}
function TypeCastExpression(node) {
return node.typeAnnotation;
}
TypeCastExpression.validParent = true;
function NewExpression(node) {
if (this.get("callee").isIdentifier()) {
return t.genericTypeAnnotation(node.callee);
}
}
function TemplateLiteral() {
return t.stringTypeAnnotation();
}
function UnaryExpression(node) {
var operator = node.operator;
if (operator === "void") {
return t.voidTypeAnnotation();
} else if (t.NUMBER_UNARY_OPERATORS.indexOf(operator) >= 0) {
return t.numberTypeAnnotation();
} else if (t.STRING_UNARY_OPERATORS.indexOf(operator) >= 0) {
return t.stringTypeAnnotation();
} else if (t.BOOLEAN_UNARY_OPERATORS.indexOf(operator) >= 0) {
return t.booleanTypeAnnotation();
}
}
function BinaryExpression(node) {
var operator = node.operator;
if (t.NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) {
return t.numberTypeAnnotation();
} else if (t.BOOLEAN_BINARY_OPERATORS.indexOf(operator) >= 0) {
return t.booleanTypeAnnotation();
} else if (operator === "+") {
var right = this.get("right");
var left = this.get("left");
if (left.isBaseType("number") && right.isBaseType("number")) {
return t.numberTypeAnnotation();
} else if (left.isBaseType("string") || right.isBaseType("string")) {
return t.stringTypeAnnotation();
}
return t.unionTypeAnnotation([t.stringTypeAnnotation(), t.numberTypeAnnotation()]);
}
}
function LogicalExpression() {
return t.createUnionTypeAnnotation([this.get("left").getTypeAnnotation(), this.get("right").getTypeAnnotation()]);
}
function ConditionalExpression() {
return t.createUnionTypeAnnotation([this.get("consequent").getTypeAnnotation(), this.get("alternate").getTypeAnnotation()]);
}
function SequenceExpression() {
return this.get("expressions").pop().getTypeAnnotation();
}
function AssignmentExpression() {
return this.get("right").getTypeAnnotation();
}
function UpdateExpression(node) {
var operator = node.operator;
if (operator === "++" || operator === "--") {
return t.numberTypeAnnotation();
}
}
function StringLiteral() {
return t.stringTypeAnnotation();
}
function NumericLiteral() {
return t.numberTypeAnnotation();
}
function BooleanLiteral() {
return t.booleanTypeAnnotation();
}
function NullLiteral() {
return t.nullLiteralTypeAnnotation();
}
function RegExpLiteral() {
return t.genericTypeAnnotation(t.identifier("RegExp"));
}
function ObjectExpression() {
return t.genericTypeAnnotation(t.identifier("Object"));
}
function ArrayExpression() {
return t.genericTypeAnnotation(t.identifier("Array"));
}
function RestElement() {
return ArrayExpression();
}
RestElement.validParent = true;
function Func() {
return t.genericTypeAnnotation(t.identifier("Function"));
}
var isArrayFrom = t.buildMatchMemberExpression("Array.from");
var isObjectKeys = t.buildMatchMemberExpression("Object.keys");
var isObjectValues = t.buildMatchMemberExpression("Object.values");
var isObjectEntries = t.buildMatchMemberExpression("Object.entries");
function CallExpression() {
var callee = this.node.callee;
if (isObjectKeys(callee)) {
return t.arrayTypeAnnotation(t.stringTypeAnnotation());
} else if (isArrayFrom(callee) || isObjectValues(callee)) {
return t.arrayTypeAnnotation(t.anyTypeAnnotation());
} else if (isObjectEntries(callee)) {
return t.arrayTypeAnnotation(t.tupleTypeAnnotation([t.stringTypeAnnotation(), t.anyTypeAnnotation()]));
}
return resolveCall(this.get("callee"));
}
function TaggedTemplateExpression() {
return resolveCall(this.get("tag"));
}
function resolveCall(callee) {
callee = callee.resolve();
if (callee.isFunction()) {
if (callee.is("async")) {
if (callee.is("generator")) {
return t.genericTypeAnnotation(t.identifier("AsyncIterator"));
} else {
return t.genericTypeAnnotation(t.identifier("Promise"));
}
} else {
if (callee.node.returnType) {
return callee.node.returnType;
} else {}
}
}
}
@@ -0,0 +1,361 @@
"use strict";
exports.__esModule = true;
exports.matchesPattern = matchesPattern;
exports.has = has;
exports.isStatic = isStatic;
exports.isnt = isnt;
exports.equals = equals;
exports.isNodeType = isNodeType;
exports.canHaveVariableDeclarationOrExpression = canHaveVariableDeclarationOrExpression;
exports.canSwapBetweenExpressionAndStatement = canSwapBetweenExpressionAndStatement;
exports.isCompletionRecord = isCompletionRecord;
exports.isStatementOrBlock = isStatementOrBlock;
exports.referencesImport = referencesImport;
exports.getSource = getSource;
exports.willIMaybeExecuteBefore = willIMaybeExecuteBefore;
exports._guessExecutionStatusRelativeTo = _guessExecutionStatusRelativeTo;
exports._guessExecutionStatusRelativeToDifferentFunctions = _guessExecutionStatusRelativeToDifferentFunctions;
exports.resolve = resolve;
exports._resolve = _resolve;
exports.isConstantExpression = isConstantExpression;
exports.is = void 0;
var _includes = _interopRequireDefault(require("lodash/includes"));
var t = _interopRequireWildcard(require("@babel/types"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function matchesPattern(pattern, allowPartial) {
return t.matchesPattern(this.node, pattern, allowPartial);
}
function has(key) {
var val = this.node && this.node[key];
if (val && Array.isArray(val)) {
return !!val.length;
} else {
return !!val;
}
}
function isStatic() {
return this.scope.isStatic(this.node);
}
var is = has;
exports.is = is;
function isnt(key) {
return !this.has(key);
}
function equals(key, value) {
return this.node[key] === value;
}
function isNodeType(type) {
return t.isType(this.type, type);
}
function canHaveVariableDeclarationOrExpression() {
return (this.key === "init" || this.key === "left") && this.parentPath.isFor();
}
function canSwapBetweenExpressionAndStatement(replacement) {
if (this.key !== "body" || !this.parentPath.isArrowFunctionExpression()) {
return false;
}
if (this.isExpression()) {
return t.isBlockStatement(replacement);
} else if (this.isBlockStatement()) {
return t.isExpression(replacement);
}
return false;
}
function isCompletionRecord(allowInsideFunction) {
var path = this;
var first = true;
do {
var container = path.container;
if (path.isFunction() && !first) {
return !!allowInsideFunction;
}
first = false;
if (Array.isArray(container) && path.key !== container.length - 1) {
return false;
}
} while ((path = path.parentPath) && !path.isProgram());
return true;
}
function isStatementOrBlock() {
if (this.parentPath.isLabeledStatement() || t.isBlockStatement(this.container)) {
return false;
} else {
return (0, _includes.default)(t.STATEMENT_OR_BLOCK_KEYS, this.key);
}
}
function referencesImport(moduleSource, importName) {
if (!this.isReferencedIdentifier()) return false;
var binding = this.scope.getBinding(this.node.name);
if (!binding || binding.kind !== "module") return false;
var path = binding.path;
var parent = path.parentPath;
if (!parent.isImportDeclaration()) return false;
if (parent.node.source.value === moduleSource) {
if (!importName) return true;
} else {
return false;
}
if (path.isImportDefaultSpecifier() && importName === "default") {
return true;
}
if (path.isImportNamespaceSpecifier() && importName === "*") {
return true;
}
if (path.isImportSpecifier() && path.node.imported.name === importName) {
return true;
}
return false;
}
function getSource() {
var node = this.node;
if (node.end) {
return this.hub.file.code.slice(node.start, node.end);
} else {
return "";
}
}
function willIMaybeExecuteBefore(target) {
return this._guessExecutionStatusRelativeTo(target) !== "after";
}
function _guessExecutionStatusRelativeTo(target) {
var targetFuncParent = target.scope.getFunctionParent() || target.scope.getProgramParent();
var selfFuncParent = this.scope.getFunctionParent() || target.scope.getProgramParent();
if (targetFuncParent.node !== selfFuncParent.node) {
var status = this._guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent);
if (status) {
return status;
} else {
target = targetFuncParent.path;
}
}
var targetPaths = target.getAncestry();
if (targetPaths.indexOf(this) >= 0) return "after";
var selfPaths = this.getAncestry();
var commonPath;
var targetIndex;
var selfIndex;
for (selfIndex = 0; selfIndex < selfPaths.length; selfIndex++) {
var selfPath = selfPaths[selfIndex];
targetIndex = targetPaths.indexOf(selfPath);
if (targetIndex >= 0) {
commonPath = selfPath;
break;
}
}
if (!commonPath) {
return "before";
}
var targetRelationship = targetPaths[targetIndex - 1];
var selfRelationship = selfPaths[selfIndex - 1];
if (!targetRelationship || !selfRelationship) {
return "before";
}
if (targetRelationship.listKey && targetRelationship.container === selfRelationship.container) {
return targetRelationship.key > selfRelationship.key ? "before" : "after";
}
var keys = t.VISITOR_KEYS[commonPath.type];
var targetKeyPosition = keys.indexOf(targetRelationship.key);
var selfKeyPosition = keys.indexOf(selfRelationship.key);
return targetKeyPosition > selfKeyPosition ? "before" : "after";
}
function _guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent) {
var targetFuncPath = targetFuncParent.path;
if (!targetFuncPath.isFunctionDeclaration()) return;
var binding = targetFuncPath.scope.getBinding(targetFuncPath.node.id.name);
if (!binding.references) return "before";
var referencePaths = binding.referencePaths;
for (var _iterator = referencePaths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var _path2 = _ref;
if (_path2.key !== "callee" || !_path2.parentPath.isCallExpression()) {
return;
}
}
var allStatus;
for (var _iterator2 = referencePaths, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var _path3 = _ref2;
var childOfFunction = !!_path3.find(function (path) {
return path.node === targetFuncPath.node;
});
if (childOfFunction) continue;
var status = this._guessExecutionStatusRelativeTo(_path3);
if (allStatus) {
if (allStatus !== status) return;
} else {
allStatus = status;
}
}
return allStatus;
}
function resolve(dangerous, resolved) {
return this._resolve(dangerous, resolved) || this;
}
function _resolve(dangerous, resolved) {
if (resolved && resolved.indexOf(this) >= 0) return;
resolved = resolved || [];
resolved.push(this);
if (this.isVariableDeclarator()) {
if (this.get("id").isIdentifier()) {
return this.get("init").resolve(dangerous, resolved);
} else {}
} else if (this.isReferencedIdentifier()) {
var binding = this.scope.getBinding(this.node.name);
if (!binding) return;
if (!binding.constant) return;
if (binding.kind === "module") return;
if (binding.path !== this) {
var ret = binding.path.resolve(dangerous, resolved);
if (this.find(function (parent) {
return parent.node === ret.node;
})) return;
return ret;
}
} else if (this.isTypeCastExpression()) {
return this.get("expression").resolve(dangerous, resolved);
} else if (dangerous && this.isMemberExpression()) {
var targetKey = this.toComputedKey();
if (!t.isLiteral(targetKey)) return;
var targetName = targetKey.value;
var target = this.get("object").resolve(dangerous, resolved);
if (target.isObjectExpression()) {
var props = target.get("properties");
var _arr = props;
for (var _i3 = 0; _i3 < _arr.length; _i3++) {
var prop = _arr[_i3];
if (!prop.isProperty()) continue;
var key = prop.get("key");
var match = prop.isnt("computed") && key.isIdentifier({
name: targetName
});
match = match || key.isLiteral({
value: targetName
});
if (match) return prop.get("value").resolve(dangerous, resolved);
}
} else if (target.isArrayExpression() && !isNaN(+targetName)) {
var elems = target.get("elements");
var elem = elems[targetName];
if (elem) return elem.resolve(dangerous, resolved);
}
}
}
function isConstantExpression() {
if (this.isIdentifier()) {
var binding = this.scope.getBinding(this.node.name);
if (!binding) {
return false;
}
return binding.constant && binding.path.get("init").isConstantExpression();
}
if (this.isLiteral()) {
if (this.isRegExpLiteral()) {
return false;
}
if (this.isTemplateLiteral()) {
return this.get("expressions").every(function (expression) {
return expression.isConstantExpression();
});
}
return true;
}
if (this.isUnaryExpression()) {
if (this.get("operator").node !== "void") {
return false;
}
return this.get("argument").isConstantExpression();
}
if (this.isBinaryExpression()) {
return this.get("left").isConstantExpression() && this.get("right").isConstantExpression();
}
return false;
}
@@ -0,0 +1,182 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var t = _interopRequireWildcard(require("@babel/types"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
var referenceVisitor = {
ReferencedIdentifier: function ReferencedIdentifier(path, state) {
if (path.isJSXIdentifier() && t.react.isCompatTag(path.node.name) && !path.parentPath.isJSXMemberExpression()) {
return;
}
if (path.node.name === "this") {
var scope = path.scope;
do {
if (scope.path.isFunction() && !scope.path.isArrowFunctionExpression()) {
break;
}
} while (scope = scope.parent);
if (scope) state.breakOnScopePaths.push(scope.path);
}
var binding = path.scope.getBinding(path.node.name);
if (!binding) return;
if (binding !== state.scope.getBinding(path.node.name)) return;
state.bindings[path.node.name] = binding;
}
};
var PathHoister = function () {
function PathHoister(path, scope) {
this.breakOnScopePaths = [];
this.bindings = {};
this.scopes = [];
this.scope = scope;
this.path = path;
this.attachAfter = false;
}
var _proto = PathHoister.prototype;
_proto.isCompatibleScope = function isCompatibleScope(scope) {
for (var key in this.bindings) {
var binding = this.bindings[key];
if (!scope.bindingIdentifierEquals(key, binding.identifier)) {
return false;
}
}
return true;
};
_proto.getCompatibleScopes = function getCompatibleScopes() {
var scope = this.path.scope;
do {
if (this.isCompatibleScope(scope)) {
this.scopes.push(scope);
} else {
break;
}
if (this.breakOnScopePaths.indexOf(scope.path) >= 0) {
break;
}
} while (scope = scope.parent);
};
_proto.getAttachmentPath = function getAttachmentPath() {
var path = this._getAttachmentPath();
if (!path) return;
var targetScope = path.scope;
if (targetScope.path === path) {
targetScope = path.scope.parent;
}
if (targetScope.path.isProgram() || targetScope.path.isFunction()) {
for (var name in this.bindings) {
if (!targetScope.hasOwnBinding(name)) continue;
var binding = this.bindings[name];
if (binding.kind === "param" || binding.path.parentKey === "params") {
continue;
}
var bindingParentPath = this.getAttachmentParentForPath(binding.path);
if (bindingParentPath.key >= path.key) {
this.attachAfter = true;
path = binding.path;
var _arr = binding.constantViolations;
for (var _i = 0; _i < _arr.length; _i++) {
var violationPath = _arr[_i];
if (this.getAttachmentParentForPath(violationPath).key > path.key) {
path = violationPath;
}
}
}
}
}
return path;
};
_proto._getAttachmentPath = function _getAttachmentPath() {
var scopes = this.scopes;
var scope = scopes.pop();
if (!scope) return;
if (scope.path.isFunction()) {
if (this.hasOwnParamBindings(scope)) {
if (this.scope === scope) return;
var bodies = scope.path.get("body").get("body");
for (var i = 0; i < bodies.length; i++) {
if (bodies[i].node._blockHoist) continue;
return bodies[i];
}
} else {
return this.getNextScopeAttachmentParent();
}
} else if (scope.path.isProgram()) {
return this.getNextScopeAttachmentParent();
}
};
_proto.getNextScopeAttachmentParent = function getNextScopeAttachmentParent() {
var scope = this.scopes.pop();
if (scope) return this.getAttachmentParentForPath(scope.path);
};
_proto.getAttachmentParentForPath = function getAttachmentParentForPath(path) {
do {
if (!path.parentPath || Array.isArray(path.container) && path.isStatement()) {
return path;
}
} while (path = path.parentPath);
};
_proto.hasOwnParamBindings = function hasOwnParamBindings(scope) {
for (var name in this.bindings) {
if (!scope.hasOwnBinding(name)) continue;
var binding = this.bindings[name];
if (binding.kind === "param" && binding.constant) return true;
}
return false;
};
_proto.run = function run() {
this.path.traverse(referenceVisitor, this);
this.getCompatibleScopes();
var attachTo = this.getAttachmentPath();
if (!attachTo) return;
if (attachTo.getFunctionParent() === this.path.getFunctionParent()) return;
var uid = attachTo.scope.generateUidIdentifier("ref");
var declarator = t.variableDeclarator(uid, this.path.node);
var insertFn = this.attachAfter ? "insertAfter" : "insertBefore";
attachTo[insertFn]([attachTo.isVariableDeclarator() ? declarator : t.variableDeclaration("var", [declarator])]);
var parent = this.path.parentPath;
if (parent.isJSXElement() && this.path.container === parent.node.children) {
uid = t.JSXExpressionContainer(uid);
}
this.path.replaceWith(uid);
};
return PathHoister;
}();
exports.default = PathHoister;
@@ -0,0 +1,36 @@
"use strict";
exports.__esModule = true;
exports.hooks = void 0;
var hooks = [function (self, parent) {
var removeParent = self.key === "test" && (parent.isWhile() || parent.isSwitchCase()) || self.key === "declaration" && parent.isExportDeclaration() || self.key === "body" && parent.isLabeledStatement() || self.listKey === "declarations" && parent.isVariableDeclaration() && parent.node.declarations.length === 1 || self.key === "expression" && parent.isExpressionStatement();
if (removeParent) {
parent.remove();
return true;
}
}, function (self, parent) {
if (parent.isSequenceExpression() && parent.node.expressions.length === 1) {
parent.replaceWith(parent.node.expressions[0]);
return true;
}
}, function (self, parent) {
if (parent.isBinary()) {
if (self.key === "left") {
parent.replaceWith(parent.node.right);
} else {
parent.replaceWith(parent.node.left);
}
return true;
}
}, function (self, parent) {
if (parent.isIfStatement() && (self.key === "consequent" || self.key === "alternate") || self.key === "body" && (parent.isLoop() || parent.isArrowFunctionExpression())) {
self.replaceWith({
type: "BlockStatement",
body: []
});
return true;
}
}];
exports.hooks = hooks;
@@ -0,0 +1,172 @@
"use strict";
exports.__esModule = true;
exports.ForAwaitStatement = exports.NumericLiteralTypeAnnotation = exports.ExistentialTypeParam = exports.SpreadProperty = exports.RestProperty = exports.Flow = exports.Pure = exports.Generated = exports.User = exports.Var = exports.BlockScoped = exports.Referenced = exports.Scope = exports.Expression = exports.Statement = exports.BindingIdentifier = exports.ReferencedMemberExpression = exports.ReferencedIdentifier = void 0;
var t = _interopRequireWildcard(require("@babel/types"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
var ReferencedIdentifier = {
types: ["Identifier", "JSXIdentifier"],
checkPath: function checkPath(_ref, opts) {
var node = _ref.node,
parent = _ref.parent;
if (!t.isIdentifier(node, opts) && !t.isJSXMemberExpression(parent, opts)) {
if (t.isJSXIdentifier(node, opts)) {
if (t.react.isCompatTag(node.name)) return false;
} else {
return false;
}
}
return t.isReferenced(node, parent);
}
};
exports.ReferencedIdentifier = ReferencedIdentifier;
var ReferencedMemberExpression = {
types: ["MemberExpression"],
checkPath: function checkPath(_ref2) {
var node = _ref2.node,
parent = _ref2.parent;
return t.isMemberExpression(node) && t.isReferenced(node, parent);
}
};
exports.ReferencedMemberExpression = ReferencedMemberExpression;
var BindingIdentifier = {
types: ["Identifier"],
checkPath: function checkPath(_ref3) {
var node = _ref3.node,
parent = _ref3.parent;
return t.isIdentifier(node) && t.isBinding(node, parent);
}
};
exports.BindingIdentifier = BindingIdentifier;
var Statement = {
types: ["Statement"],
checkPath: function checkPath(_ref4) {
var node = _ref4.node,
parent = _ref4.parent;
if (t.isStatement(node)) {
if (t.isVariableDeclaration(node)) {
if (t.isForXStatement(parent, {
left: node
})) return false;
if (t.isForStatement(parent, {
init: node
})) return false;
}
return true;
} else {
return false;
}
}
};
exports.Statement = Statement;
var Expression = {
types: ["Expression"],
checkPath: function checkPath(path) {
if (path.isIdentifier()) {
return path.isReferencedIdentifier();
} else {
return t.isExpression(path.node);
}
}
};
exports.Expression = Expression;
var Scope = {
types: ["Scopable"],
checkPath: function checkPath(path) {
return t.isScope(path.node, path.parent);
}
};
exports.Scope = Scope;
var Referenced = {
checkPath: function checkPath(path) {
return t.isReferenced(path.node, path.parent);
}
};
exports.Referenced = Referenced;
var BlockScoped = {
checkPath: function checkPath(path) {
return t.isBlockScoped(path.node);
}
};
exports.BlockScoped = BlockScoped;
var Var = {
types: ["VariableDeclaration"],
checkPath: function checkPath(path) {
return t.isVar(path.node);
}
};
exports.Var = Var;
var User = {
checkPath: function checkPath(path) {
return path.node && !!path.node.loc;
}
};
exports.User = User;
var Generated = {
checkPath: function checkPath(path) {
return !path.isUser();
}
};
exports.Generated = Generated;
var Pure = {
checkPath: function checkPath(path, opts) {
return path.scope.isPure(path.node, opts);
}
};
exports.Pure = Pure;
var Flow = {
types: ["Flow", "ImportDeclaration", "ExportDeclaration", "ImportSpecifier"],
checkPath: function checkPath(_ref5) {
var node = _ref5.node;
if (t.isFlow(node)) {
return true;
} else if (t.isImportDeclaration(node)) {
return node.importKind === "type" || node.importKind === "typeof";
} else if (t.isExportDeclaration(node)) {
return node.exportKind === "type";
} else if (t.isImportSpecifier(node)) {
return node.importKind === "type" || node.importKind === "typeof";
} else {
return false;
}
}
};
exports.Flow = Flow;
var RestProperty = {
types: ["RestElement"],
checkPath: function checkPath(path) {
return path.parentPath && path.parentPath.isObjectPattern();
}
};
exports.RestProperty = RestProperty;
var SpreadProperty = {
types: ["RestElement"],
checkPath: function checkPath(path) {
return path.parentPath && path.parentPath.isObjectExpression();
}
};
exports.SpreadProperty = SpreadProperty;
var ExistentialTypeParam = {
types: ["ExistsTypeAnnotation"]
};
exports.ExistentialTypeParam = ExistentialTypeParam;
var NumericLiteralTypeAnnotation = {
types: ["NumberLiteralTypeAnnotation"]
};
exports.NumericLiteralTypeAnnotation = NumericLiteralTypeAnnotation;
var ForAwaitStatement = {
types: ["ForOfStatement"],
checkPath: function checkPath(_ref6) {
var node = _ref6.node;
return node.await === true;
}
};
exports.ForAwaitStatement = ForAwaitStatement;
@@ -0,0 +1,216 @@
"use strict";
exports.__esModule = true;
exports.insertBefore = insertBefore;
exports._containerInsert = _containerInsert;
exports._containerInsertBefore = _containerInsertBefore;
exports._containerInsertAfter = _containerInsertAfter;
exports.insertAfter = insertAfter;
exports.updateSiblingKeys = updateSiblingKeys;
exports._verifyNodeList = _verifyNodeList;
exports.unshiftContainer = unshiftContainer;
exports.pushContainer = pushContainer;
exports.hoist = hoist;
var _cache = require("../cache");
var _hoister = _interopRequireDefault(require("./lib/hoister"));
var _index = _interopRequireDefault(require("./index"));
var t = _interopRequireWildcard(require("@babel/types"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function insertBefore(nodes) {
this._assertUnremoved();
nodes = this._verifyNodeList(nodes);
if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement() || this.parentPath.isExportDeclaration()) {
return this.parentPath.insertBefore(nodes);
} else if (this.isNodeType("Expression") && this.listKey !== "params" && this.listKey !== "arguments" || this.parentPath.isForStatement() && this.key === "init") {
if (this.node) nodes.push(this.node);
return this.replaceExpressionWithStatements(nodes);
} else if (Array.isArray(this.container)) {
return this._containerInsertBefore(nodes);
} else if (this.isStatementOrBlock()) {
var shouldInsertCurrentNode = this.node && (!this.isExpressionStatement() || this.node.expression != null);
this.replaceWith(t.blockStatement(shouldInsertCurrentNode ? [this.node] : []));
return this.unshiftContainer("body", nodes);
} else {
throw new Error("We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?");
}
}
function _containerInsert(from, nodes) {
var _container;
this.updateSiblingKeys(from, nodes.length);
var paths = [];
(_container = this.container).splice.apply(_container, [from, 0].concat(nodes));
for (var i = 0; i < nodes.length; i++) {
var to = from + i;
var path = this.getSibling("" + to);
paths.push(path);
if (this.context && this.context.queue) {
path.pushContext(this.context);
}
}
var contexts = this._getQueueContexts();
for (var _i = 0; _i < paths.length; _i++) {
var _path = paths[_i];
_path.setScope();
_path.debug("Inserted.");
for (var _iterator = contexts, _isArray = Array.isArray(_iterator), _i2 = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i2 >= _iterator.length) break;
_ref = _iterator[_i2++];
} else {
_i2 = _iterator.next();
if (_i2.done) break;
_ref = _i2.value;
}
var _context = _ref;
_context.maybeQueue(_path, true);
}
}
return paths;
}
function _containerInsertBefore(nodes) {
return this._containerInsert(this.key, nodes);
}
function _containerInsertAfter(nodes) {
return this._containerInsert(this.key + 1, nodes);
}
function insertAfter(nodes) {
this._assertUnremoved();
nodes = this._verifyNodeList(nodes);
if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement() || this.parentPath.isExportDeclaration()) {
return this.parentPath.insertAfter(nodes);
} else if (this.isNodeType("Expression") || this.parentPath.isForStatement() && this.key === "init") {
if (this.node) {
var temp = this.scope.generateDeclaredUidIdentifier();
nodes.unshift(t.expressionStatement(t.assignmentExpression("=", temp, this.node)));
nodes.push(t.expressionStatement(temp));
}
return this.replaceExpressionWithStatements(nodes);
} else if (Array.isArray(this.container)) {
return this._containerInsertAfter(nodes);
} else if (this.isStatementOrBlock()) {
var shouldInsertCurrentNode = this.node && (!this.isExpressionStatement() || this.node.expression != null);
this.replaceWith(t.blockStatement(shouldInsertCurrentNode ? [this.node] : []));
return this.pushContainer("body", nodes);
} else {
throw new Error("We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?");
}
}
function updateSiblingKeys(fromIndex, incrementBy) {
if (!this.parent) return;
var paths = _cache.path.get(this.parent);
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
if (path.key >= fromIndex) {
path.key += incrementBy;
}
}
}
function _verifyNodeList(nodes) {
if (!nodes) {
return [];
}
if (nodes.constructor !== Array) {
nodes = [nodes];
}
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
var msg = void 0;
if (!node) {
msg = "has falsy node";
} else if (typeof node !== "object") {
msg = "contains a non-object node";
} else if (!node.type) {
msg = "without a type";
} else if (node instanceof _index.default) {
msg = "has a NodePath when it expected a raw object";
}
if (msg) {
var type = Array.isArray(node) ? "array" : typeof node;
throw new Error("Node list " + msg + " with the index of " + i + " and type of " + type);
}
}
return nodes;
}
function unshiftContainer(listKey, nodes) {
this._assertUnremoved();
nodes = this._verifyNodeList(nodes);
var path = _index.default.get({
parentPath: this,
parent: this.node,
container: this.node[listKey],
listKey: listKey,
key: 0
});
return path.insertBefore(nodes);
}
function pushContainer(listKey, nodes) {
this._assertUnremoved();
nodes = this._verifyNodeList(nodes);
var container = this.node[listKey];
var path = _index.default.get({
parentPath: this,
parent: this.node,
container: container,
listKey: listKey,
key: container.length
});
return path.replaceWithMultiple(nodes);
}
function hoist(scope) {
if (scope === void 0) {
scope = this.scope;
}
var hoister = new _hoister.default(this, scope);
return hoister.run();
}
@@ -0,0 +1,58 @@
"use strict";
exports.__esModule = true;
exports.remove = remove;
exports._callRemovalHooks = _callRemovalHooks;
exports._remove = _remove;
exports._markRemoved = _markRemoved;
exports._assertUnremoved = _assertUnremoved;
var _removalHooks = require("./lib/removal-hooks");
function remove() {
this._assertUnremoved();
this.resync();
if (this._callRemovalHooks()) {
this._markRemoved();
return;
}
this.shareCommentsWithSiblings();
this._remove();
this._markRemoved();
}
function _callRemovalHooks() {
var _arr = _removalHooks.hooks;
for (var _i = 0; _i < _arr.length; _i++) {
var fn = _arr[_i];
if (fn(this, this.parentPath)) return true;
}
}
function _remove() {
if (Array.isArray(this.container)) {
this.container.splice(this.key, 1);
this.updateSiblingKeys(this.key, -1);
} else {
this._replaceWith(null);
}
}
function _markRemoved() {
this.shouldSkip = true;
this.removed = true;
this.node = null;
}
function _assertUnremoved() {
if (this.removed) {
throw this.buildCodeFrameError("NodePath has been removed so is read-only.");
}
}
@@ -0,0 +1,251 @@
"use strict";
exports.__esModule = true;
exports.replaceWithMultiple = replaceWithMultiple;
exports.replaceWithSourceString = replaceWithSourceString;
exports.replaceWith = replaceWith;
exports._replaceWith = _replaceWith;
exports.replaceExpressionWithStatements = replaceExpressionWithStatements;
exports.replaceInline = replaceInline;
var _codeFrame = require("@babel/code-frame");
var _index = _interopRequireDefault(require("../index"));
var _index2 = _interopRequireDefault(require("./index"));
var _babylon = require("babylon");
var t = _interopRequireWildcard(require("@babel/types"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var hoistVariablesVisitor = {
Function: function Function(path) {
path.skip();
},
VariableDeclaration: function VariableDeclaration(path) {
if (path.node.kind !== "var") return;
var bindings = path.getBindingIdentifiers();
for (var key in bindings) {
path.scope.push({
id: bindings[key]
});
}
var exprs = [];
var _arr = path.node.declarations;
for (var _i = 0; _i < _arr.length; _i++) {
var declar = _arr[_i];
if (declar.init) {
exprs.push(t.expressionStatement(t.assignmentExpression("=", declar.id, declar.init)));
}
}
path.replaceWithMultiple(exprs);
}
};
function replaceWithMultiple(nodes) {
this.resync();
nodes = this._verifyNodeList(nodes);
t.inheritLeadingComments(nodes[0], this.node);
t.inheritTrailingComments(nodes[nodes.length - 1], this.node);
this.node = this.container[this.key] = null;
var paths = this.insertAfter(nodes);
if (this.node) {
this.requeue();
} else {
this.remove();
}
return paths;
}
function replaceWithSourceString(replacement) {
this.resync();
try {
replacement = "(" + replacement + ")";
replacement = (0, _babylon.parse)(replacement);
} catch (err) {
var loc = err.loc;
if (loc) {
err.loc = null;
err.message += " - make sure this is an expression.\n" + (0, _codeFrame.codeFrameColumns)(replacement, {
start: {
line: loc.line,
column: loc.column + 1
}
});
}
throw err;
}
replacement = replacement.program.body[0].expression;
_index.default.removeProperties(replacement);
return this.replaceWith(replacement);
}
function replaceWith(replacement) {
this.resync();
if (this.removed) {
throw new Error("You can't replace this node, we've already removed it");
}
if (replacement instanceof _index2.default) {
replacement = replacement.node;
}
if (!replacement) {
throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead");
}
if (this.node === replacement) {
return [this];
}
if (this.isProgram() && !t.isProgram(replacement)) {
throw new Error("You can only replace a Program root node with another Program node");
}
if (Array.isArray(replacement)) {
throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`");
}
if (typeof replacement === "string") {
throw new Error("Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`");
}
var nodePath = "";
if (this.isNodeType("Statement") && t.isExpression(replacement)) {
if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement) && !this.parentPath.isExportDefaultDeclaration()) {
replacement = t.expressionStatement(replacement);
nodePath = "expression";
}
}
if (this.isNodeType("Expression") && t.isStatement(replacement)) {
if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement)) {
return this.replaceExpressionWithStatements([replacement]);
}
}
var oldNode = this.node;
if (oldNode) {
t.inheritsComments(replacement, oldNode);
t.removeComments(oldNode);
}
this._replaceWith(replacement);
this.type = replacement.type;
this.setScope();
this.requeue();
return [nodePath ? this.get(nodePath) : this];
}
function _replaceWith(node) {
if (!this.container) {
throw new ReferenceError("Container is falsy");
}
if (this.inList) {
t.validate(this.parent, this.key, [node]);
} else {
t.validate(this.parent, this.key, node);
}
this.debug("Replace with " + (node && node.type));
this.node = this.container[this.key] = node;
}
function replaceExpressionWithStatements(nodes) {
this.resync();
var toSequenceExpression = t.toSequenceExpression(nodes, this.scope);
if (toSequenceExpression) {
return this.replaceWith(toSequenceExpression)[0].get("expressions");
}
var container = t.arrowFunctionExpression([], t.blockStatement(nodes));
this.replaceWith(t.callExpression(container, []));
this.traverse(hoistVariablesVisitor);
var completionRecords = this.get("callee").getCompletionRecords();
for (var _iterator = completionRecords, _isArray = Array.isArray(_iterator), _i2 = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i2 >= _iterator.length) break;
_ref = _iterator[_i2++];
} else {
_i2 = _iterator.next();
if (_i2.done) break;
_ref = _i2.value;
}
var _path = _ref;
if (!_path.isExpressionStatement()) continue;
var loop = _path.findParent(function (path) {
return path.isLoop();
});
if (loop) {
var uid = loop.getData("expressionReplacementReturnUid");
if (!uid) {
var _callee = this.get("callee");
uid = _callee.scope.generateDeclaredUidIdentifier("ret");
_callee.get("body").pushContainer("body", t.returnStatement(uid));
loop.setData("expressionReplacementReturnUid", uid);
} else {
uid = t.identifier(uid.name);
}
_path.get("expression").replaceWith(t.assignmentExpression("=", uid, _path.node.expression));
} else {
_path.replaceWith(t.returnStatement(_path.node.expression));
}
}
var callee = this.get("callee");
callee.arrowFunctionToExpression();
return callee.get("body.body");
}
function replaceInline(nodes) {
this.resync();
if (Array.isArray(nodes)) {
if (Array.isArray(this.container)) {
nodes = this._verifyNodeList(nodes);
var paths = this._containerInsertAfter(nodes);
this.remove();
return paths;
} else {
return this.replaceWithMultiple(nodes);
}
} else {
return this.replaceWith(nodes);
}
}
@@ -0,0 +1,79 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var Binding = function () {
function Binding(_ref) {
var identifier = _ref.identifier,
scope = _ref.scope,
path = _ref.path,
kind = _ref.kind;
this.constantViolations = void 0;
this.constant = void 0;
this.referencePaths = void 0;
this.referenced = void 0;
this.references = void 0;
this.hasDeoptedValue = void 0;
this.hasValue = void 0;
this.value = void 0;
this.identifier = identifier;
this.scope = scope;
this.path = path;
this.kind = kind;
this.constantViolations = [];
this.constant = true;
this.referencePaths = [];
this.referenced = false;
this.references = 0;
this.clearValue();
}
var _proto = Binding.prototype;
_proto.deoptValue = function deoptValue() {
this.clearValue();
this.hasDeoptedValue = true;
};
_proto.setValue = function setValue(value) {
if (this.hasDeoptedValue) return;
this.hasValue = true;
this.value = value;
};
_proto.clearValue = function clearValue() {
this.hasDeoptedValue = false;
this.hasValue = false;
this.value = null;
};
_proto.reassign = function reassign(path) {
this.constant = false;
if (this.constantViolations.indexOf(path) !== -1) {
return;
}
this.constantViolations.push(path);
};
_proto.reference = function reference(path) {
if (this.referencePaths.indexOf(path) !== -1) {
return;
}
this.referenced = true;
this.references++;
this.referencePaths.push(path);
};
_proto.dereference = function dereference() {
this.references--;
this.referenced = !!this.references;
};
return Binding;
}();
exports.default = Binding;
@@ -0,0 +1,970 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _includes = _interopRequireDefault(require("lodash/includes"));
var _repeat = _interopRequireDefault(require("lodash/repeat"));
var _renamer = _interopRequireDefault(require("./lib/renamer"));
var _index = _interopRequireDefault(require("../index"));
var _defaults = _interopRequireDefault(require("lodash/defaults"));
var _binding2 = _interopRequireDefault(require("./binding"));
var _globals = _interopRequireDefault(require("globals"));
var t = _interopRequireWildcard(require("@babel/types"));
var _cache = require("../cache");
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function gatherNodeParts(node, parts) {
if (t.isModuleDeclaration(node)) {
if (node.source) {
gatherNodeParts(node.source, parts);
} else if (node.specifiers && node.specifiers.length) {
var _arr = node.specifiers;
for (var _i = 0; _i < _arr.length; _i++) {
var specifier = _arr[_i];
gatherNodeParts(specifier, parts);
}
} else if (node.declaration) {
gatherNodeParts(node.declaration, parts);
}
} else if (t.isModuleSpecifier(node)) {
gatherNodeParts(node.local, parts);
} else if (t.isMemberExpression(node)) {
gatherNodeParts(node.object, parts);
gatherNodeParts(node.property, parts);
} else if (t.isIdentifier(node)) {
parts.push(node.name);
} else if (t.isLiteral(node)) {
parts.push(node.value);
} else if (t.isCallExpression(node)) {
gatherNodeParts(node.callee, parts);
} else if (t.isObjectExpression(node) || t.isObjectPattern(node)) {
var _arr2 = node.properties;
for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
var prop = _arr2[_i2];
gatherNodeParts(prop.key || prop.argument, parts);
}
}
}
var collectorVisitor = {
For: function For(path) {
var _arr3 = t.FOR_INIT_KEYS;
for (var _i3 = 0; _i3 < _arr3.length; _i3++) {
var key = _arr3[_i3];
var declar = path.get(key);
if (declar.isVar()) {
var parentScope = path.scope.getFunctionParent() || path.scope.getProgramParent();
parentScope.registerBinding("var", declar);
}
}
},
Declaration: function Declaration(path) {
if (path.isBlockScoped()) return;
if (path.isExportDeclaration() && path.get("declaration").isDeclaration()) {
return;
}
var parent = path.scope.getFunctionParent() || path.scope.getProgramParent();
parent.registerDeclaration(path);
},
ReferencedIdentifier: function ReferencedIdentifier(path, state) {
state.references.push(path);
},
ForXStatement: function ForXStatement(path, state) {
var left = path.get("left");
if (left.isPattern() || left.isIdentifier()) {
state.constantViolations.push(path);
}
},
ExportDeclaration: {
exit: function exit(path) {
var node = path.node,
scope = path.scope;
var declar = node.declaration;
if (t.isClassDeclaration(declar) || t.isFunctionDeclaration(declar)) {
var _id = declar.id;
if (!_id) return;
var binding = scope.getBinding(_id.name);
if (binding) binding.reference(path);
} else if (t.isVariableDeclaration(declar)) {
var _arr4 = declar.declarations;
for (var _i4 = 0; _i4 < _arr4.length; _i4++) {
var decl = _arr4[_i4];
var ids = t.getBindingIdentifiers(decl);
for (var name in ids) {
var _binding = scope.getBinding(name);
if (_binding) _binding.reference(path);
}
}
}
}
},
LabeledStatement: function LabeledStatement(path) {
path.scope.getProgramParent().addGlobal(path.node);
path.scope.getBlockParent().registerDeclaration(path);
},
AssignmentExpression: function AssignmentExpression(path, state) {
state.assignments.push(path);
},
UpdateExpression: function UpdateExpression(path, state) {
state.constantViolations.push(path);
},
UnaryExpression: function UnaryExpression(path, state) {
if (path.node.operator === "delete") {
state.constantViolations.push(path);
}
},
BlockScoped: function BlockScoped(path) {
var scope = path.scope;
if (scope.path === path) scope = scope.parent;
scope.getBlockParent().registerDeclaration(path);
},
ClassDeclaration: function ClassDeclaration(path) {
var id = path.node.id;
if (!id) return;
var name = id.name;
path.scope.bindings[name] = path.scope.getBinding(name);
},
Block: function Block(path) {
var paths = path.get("body");
var _arr5 = paths;
for (var _i5 = 0; _i5 < _arr5.length; _i5++) {
var bodyPath = _arr5[_i5];
if (bodyPath.isFunctionDeclaration()) {
path.scope.getBlockParent().registerDeclaration(bodyPath);
}
}
}
};
var uid = 0;
var Scope = function () {
function Scope(path) {
var node = path.node;
var cached = _cache.scope.get(node);
if (cached && cached.path === path) {
return cached;
}
_cache.scope.set(node, this);
this.uid = uid++;
this.block = node;
this.path = path;
this.labels = new Map();
}
var _proto = Scope.prototype;
_proto.traverse = function traverse(node, opts, state) {
(0, _index.default)(node, opts, this, state, this.path);
};
_proto.generateDeclaredUidIdentifier = function generateDeclaredUidIdentifier(name) {
if (name === void 0) {
name = "temp";
}
var id = this.generateUidIdentifier(name);
this.push({
id: id
});
return id;
};
_proto.generateUidIdentifier = function generateUidIdentifier(name) {
if (name === void 0) {
name = "temp";
}
return t.identifier(this.generateUid(name));
};
_proto.generateUid = function generateUid(name) {
if (name === void 0) {
name = "temp";
}
name = t.toIdentifier(name).replace(/^_+/, "").replace(/[0-9]+$/g, "");
var uid;
var i = 0;
do {
uid = this._generateUid(name, i);
i++;
} while (this.hasLabel(uid) || this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid));
var program = this.getProgramParent();
program.references[uid] = true;
program.uids[uid] = true;
return uid;
};
_proto._generateUid = function _generateUid(name, i) {
var id = name;
if (i > 1) id += i;
return "_" + id;
};
_proto.generateUidIdentifierBasedOnNode = function generateUidIdentifierBasedOnNode(parent, defaultName) {
var node = parent;
if (t.isAssignmentExpression(parent)) {
node = parent.left;
} else if (t.isVariableDeclarator(parent)) {
node = parent.id;
} else if (t.isObjectProperty(node) || t.isObjectMethod(node)) {
node = node.key;
}
var parts = [];
gatherNodeParts(node, parts);
var id = parts.join("$");
id = id.replace(/^_/, "") || defaultName || "ref";
return this.generateUidIdentifier(id.slice(0, 20));
};
_proto.isStatic = function isStatic(node) {
if (t.isThisExpression(node) || t.isSuper(node)) {
return true;
}
if (t.isIdentifier(node)) {
var binding = this.getBinding(node.name);
if (binding) {
return binding.constant;
} else {
return this.hasBinding(node.name);
}
}
return false;
};
_proto.maybeGenerateMemoised = function maybeGenerateMemoised(node, dontPush) {
if (this.isStatic(node)) {
return null;
} else {
var _id2 = this.generateUidIdentifierBasedOnNode(node);
if (!dontPush) this.push({
id: _id2
});
return _id2;
}
};
_proto.checkBlockScopedCollisions = function checkBlockScopedCollisions(local, kind, name, id) {
if (kind === "param") return;
if (local.kind === "local") return;
if (kind === "hoisted" && local.kind === "let") return;
var duplicate = kind === "let" || local.kind === "let" || local.kind === "const" || local.kind === "module" || local.kind === "param" && (kind === "let" || kind === "const");
if (duplicate) {
throw this.hub.file.buildCodeFrameError(id, "Duplicate declaration \"" + name + "\"", TypeError);
}
};
_proto.rename = function rename(oldName, newName, block) {
var binding = this.getBinding(oldName);
if (binding) {
newName = newName || this.generateUidIdentifier(oldName).name;
return new _renamer.default(binding, oldName, newName).rename(block);
}
};
_proto._renameFromMap = function _renameFromMap(map, oldName, newName, value) {
if (map[oldName]) {
map[newName] = value;
map[oldName] = null;
}
};
_proto.dump = function dump() {
var sep = (0, _repeat.default)("-", 60);
console.log(sep);
var scope = this;
do {
console.log("#", scope.block.type);
for (var name in scope.bindings) {
var binding = scope.bindings[name];
console.log(" -", name, {
constant: binding.constant,
references: binding.references,
violations: binding.constantViolations.length,
kind: binding.kind
});
}
} while (scope = scope.parent);
console.log(sep);
};
_proto.toArray = function toArray(node, i) {
var file = this.hub.file;
if (t.isIdentifier(node)) {
var binding = this.getBinding(node.name);
if (binding && binding.constant && binding.path.isGenericType("Array")) {
return node;
}
}
if (t.isArrayExpression(node)) {
return node;
}
if (t.isIdentifier(node, {
name: "arguments"
})) {
return t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier("Array"), t.identifier("prototype")), t.identifier("slice")), t.identifier("call")), [node]);
}
var helperName = "toArray";
var args = [node];
if (i === true) {
helperName = "toConsumableArray";
} else if (i) {
args.push(t.numericLiteral(i));
helperName = "slicedToArray";
}
return t.callExpression(file.addHelper(helperName), args);
};
_proto.hasLabel = function hasLabel(name) {
return !!this.getLabel(name);
};
_proto.getLabel = function getLabel(name) {
return this.labels.get(name);
};
_proto.registerLabel = function registerLabel(path) {
this.labels.set(path.node.label.name, path);
};
_proto.registerDeclaration = function registerDeclaration(path) {
if (path.isFlow()) return;
if (path.isLabeledStatement()) {
this.registerLabel(path);
} else if (path.isFunctionDeclaration()) {
this.registerBinding("hoisted", path.get("id"), path);
} else if (path.isVariableDeclaration()) {
var declarations = path.get("declarations");
var _arr6 = declarations;
for (var _i6 = 0; _i6 < _arr6.length; _i6++) {
var declar = _arr6[_i6];
this.registerBinding(path.node.kind, declar);
}
} else if (path.isClassDeclaration()) {
this.registerBinding("let", path);
} else if (path.isImportDeclaration()) {
var specifiers = path.get("specifiers");
var _arr7 = specifiers;
for (var _i7 = 0; _i7 < _arr7.length; _i7++) {
var specifier = _arr7[_i7];
this.registerBinding("module", specifier);
}
} else if (path.isExportDeclaration()) {
var _declar = path.get("declaration");
if (_declar.isClassDeclaration() || _declar.isFunctionDeclaration() || _declar.isVariableDeclaration()) {
this.registerDeclaration(_declar);
}
} else {
this.registerBinding("unknown", path);
}
};
_proto.buildUndefinedNode = function buildUndefinedNode() {
if (this.hasBinding("undefined")) {
return t.unaryExpression("void", t.numericLiteral(0), true);
} else {
return t.identifier("undefined");
}
};
_proto.registerConstantViolation = function registerConstantViolation(path) {
var ids = path.getBindingIdentifiers();
for (var name in ids) {
var binding = this.getBinding(name);
if (binding) binding.reassign(path);
}
};
_proto.registerBinding = function registerBinding(kind, path, bindingPath) {
if (bindingPath === void 0) {
bindingPath = path;
}
if (!kind) throw new ReferenceError("no `kind`");
if (path.isVariableDeclaration()) {
var declarators = path.get("declarations");
for (var _iterator = declarators, _isArray = Array.isArray(_iterator), _i8 = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i8 >= _iterator.length) break;
_ref = _iterator[_i8++];
} else {
_i8 = _iterator.next();
if (_i8.done) break;
_ref = _i8.value;
}
var _declar2 = _ref;
this.registerBinding(kind, _declar2);
}
return;
}
var parent = this.getProgramParent();
var ids = path.getBindingIdentifiers(true);
for (var name in ids) {
var _arr8 = ids[name];
for (var _i9 = 0; _i9 < _arr8.length; _i9++) {
var _id3 = _arr8[_i9];
var local = this.getOwnBinding(name);
if (local) {
if (local.identifier === _id3) continue;
this.checkBlockScopedCollisions(local, kind, name, _id3);
}
parent.references[name] = true;
if (local) {
this.registerConstantViolation(bindingPath);
} else {
this.bindings[name] = new _binding2.default({
identifier: _id3,
scope: this,
path: bindingPath,
kind: kind
});
}
}
}
};
_proto.addGlobal = function addGlobal(node) {
this.globals[node.name] = node;
};
_proto.hasUid = function hasUid(name) {
var scope = this;
do {
if (scope.uids[name]) return true;
} while (scope = scope.parent);
return false;
};
_proto.hasGlobal = function hasGlobal(name) {
var scope = this;
do {
if (scope.globals[name]) return true;
} while (scope = scope.parent);
return false;
};
_proto.hasReference = function hasReference(name) {
var scope = this;
do {
if (scope.references[name]) return true;
} while (scope = scope.parent);
return false;
};
_proto.isPure = function isPure(node, constantsOnly) {
if (t.isIdentifier(node)) {
var binding = this.getBinding(node.name);
if (!binding) return false;
if (constantsOnly) return binding.constant;
return true;
} else if (t.isClass(node)) {
if (node.superClass && !this.isPure(node.superClass, constantsOnly)) {
return false;
}
return this.isPure(node.body, constantsOnly);
} else if (t.isClassBody(node)) {
for (var _iterator2 = node.body, _isArray2 = Array.isArray(_iterator2), _i10 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i10 >= _iterator2.length) break;
_ref2 = _iterator2[_i10++];
} else {
_i10 = _iterator2.next();
if (_i10.done) break;
_ref2 = _i10.value;
}
var _method = _ref2;
if (!this.isPure(_method, constantsOnly)) return false;
}
return true;
} else if (t.isBinary(node)) {
return this.isPure(node.left, constantsOnly) && this.isPure(node.right, constantsOnly);
} else if (t.isArrayExpression(node)) {
var _arr9 = node.elements;
for (var _i11 = 0; _i11 < _arr9.length; _i11++) {
var elem = _arr9[_i11];
if (!this.isPure(elem, constantsOnly)) return false;
}
return true;
} else if (t.isObjectExpression(node)) {
var _arr10 = node.properties;
for (var _i12 = 0; _i12 < _arr10.length; _i12++) {
var prop = _arr10[_i12];
if (!this.isPure(prop, constantsOnly)) return false;
}
return true;
} else if (t.isClassMethod(node)) {
if (node.computed && !this.isPure(node.key, constantsOnly)) return false;
if (node.kind === "get" || node.kind === "set") return false;
return true;
} else if (t.isClassProperty(node) || t.isObjectProperty(node)) {
if (node.computed && !this.isPure(node.key, constantsOnly)) return false;
return this.isPure(node.value, constantsOnly);
} else if (t.isUnaryExpression(node)) {
return this.isPure(node.argument, constantsOnly);
} else if (t.isTaggedTemplateExpression(node)) {
return t.matchesPattern(node.tag, "String.raw") && !this.hasBinding("String", true) && this.isPure(node.quasi, constantsOnly);
} else if (t.isTemplateLiteral(node)) {
var _arr11 = node.expressions;
for (var _i13 = 0; _i13 < _arr11.length; _i13++) {
var expression = _arr11[_i13];
if (!this.isPure(expression, constantsOnly)) return false;
}
return true;
} else {
return t.isPureish(node);
}
};
_proto.setData = function setData(key, val) {
return this.data[key] = val;
};
_proto.getData = function getData(key) {
var scope = this;
do {
var data = scope.data[key];
if (data != null) return data;
} while (scope = scope.parent);
};
_proto.removeData = function removeData(key) {
var scope = this;
do {
var data = scope.data[key];
if (data != null) scope.data[key] = null;
} while (scope = scope.parent);
};
_proto.init = function init() {
if (!this.references) this.crawl();
};
_proto.crawl = function crawl() {
var path = this.path;
this.references = Object.create(null);
this.bindings = Object.create(null);
this.globals = Object.create(null);
this.uids = Object.create(null);
this.data = Object.create(null);
if (path.isLoop()) {
var _arr12 = t.FOR_INIT_KEYS;
for (var _i14 = 0; _i14 < _arr12.length; _i14++) {
var key = _arr12[_i14];
var node = path.get(key);
if (node.isBlockScoped()) this.registerBinding(node.node.kind, node);
}
}
if (path.isFunctionExpression() && path.has("id")) {
if (!path.get("id").node[t.NOT_LOCAL_BINDING]) {
this.registerBinding("local", path.get("id"), path);
}
}
if (path.isClassExpression() && path.has("id")) {
if (!path.get("id").node[t.NOT_LOCAL_BINDING]) {
this.registerBinding("local", path);
}
}
if (path.isFunction()) {
var params = path.get("params");
for (var _iterator3 = params, _isArray3 = Array.isArray(_iterator3), _i15 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i15 >= _iterator3.length) break;
_ref3 = _iterator3[_i15++];
} else {
_i15 = _iterator3.next();
if (_i15.done) break;
_ref3 = _i15.value;
}
var _param = _ref3;
this.registerBinding("param", _param);
}
}
if (path.isCatchClause()) {
this.registerBinding("let", path);
}
var parent = this.getProgramParent();
if (parent.crawling) return;
var state = {
references: [],
constantViolations: [],
assignments: []
};
this.crawling = true;
path.traverse(collectorVisitor, state);
this.crawling = false;
for (var _iterator4 = state.assignments, _isArray4 = Array.isArray(_iterator4), _i16 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
var _ref4;
if (_isArray4) {
if (_i16 >= _iterator4.length) break;
_ref4 = _iterator4[_i16++];
} else {
_i16 = _iterator4.next();
if (_i16.done) break;
_ref4 = _i16.value;
}
var _path3 = _ref4;
var ids = _path3.getBindingIdentifiers();
var programParent = void 0;
for (var name in ids) {
if (_path3.scope.getBinding(name)) continue;
programParent = programParent || _path3.scope.getProgramParent();
programParent.addGlobal(ids[name]);
}
_path3.scope.registerConstantViolation(_path3);
}
for (var _iterator5 = state.references, _isArray5 = Array.isArray(_iterator5), _i17 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) {
var _ref5;
if (_isArray5) {
if (_i17 >= _iterator5.length) break;
_ref5 = _iterator5[_i17++];
} else {
_i17 = _iterator5.next();
if (_i17.done) break;
_ref5 = _i17.value;
}
var _ref7 = _ref5;
var binding = _ref7.scope.getBinding(_ref7.node.name);
if (binding) {
binding.reference(_ref7);
} else {
_ref7.scope.getProgramParent().addGlobal(_ref7.node);
}
}
for (var _iterator6 = state.constantViolations, _isArray6 = Array.isArray(_iterator6), _i18 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) {
var _ref6;
if (_isArray6) {
if (_i18 >= _iterator6.length) break;
_ref6 = _iterator6[_i18++];
} else {
_i18 = _iterator6.next();
if (_i18.done) break;
_ref6 = _i18.value;
}
var _path4 = _ref6;
_path4.scope.registerConstantViolation(_path4);
}
};
_proto.push = function push(opts) {
var path = this.path;
if (!path.isBlockStatement() && !path.isProgram()) {
path = this.getBlockParent().path;
}
if (path.isSwitchStatement()) {
path = (this.getFunctionParent() || this.getProgramParent()).path;
}
if (path.isLoop() || path.isCatchClause() || path.isFunction()) {
path.ensureBlock();
path = path.get("body");
}
var unique = opts.unique;
var kind = opts.kind || "var";
var blockHoist = opts._blockHoist == null ? 2 : opts._blockHoist;
var dataKey = "declaration:" + kind + ":" + blockHoist;
var declarPath = !unique && path.getData(dataKey);
if (!declarPath) {
var declar = t.variableDeclaration(kind, []);
declar._blockHoist = blockHoist;
var _path$unshiftContaine = path.unshiftContainer("body", [declar]);
declarPath = _path$unshiftContaine[0];
if (!unique) path.setData(dataKey, declarPath);
}
var declarator = t.variableDeclarator(opts.id, opts.init);
declarPath.node.declarations.push(declarator);
this.registerBinding(kind, declarPath.get("declarations").pop());
};
_proto.getProgramParent = function getProgramParent() {
var scope = this;
do {
if (scope.path.isProgram()) {
return scope;
}
} while (scope = scope.parent);
throw new Error("Couldn't find a Program");
};
_proto.getFunctionParent = function getFunctionParent() {
var scope = this;
do {
if (scope.path.isFunctionParent()) {
return scope;
}
} while (scope = scope.parent);
return null;
};
_proto.getBlockParent = function getBlockParent() {
var scope = this;
do {
if (scope.path.isBlockParent()) {
return scope;
}
} while (scope = scope.parent);
throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program...");
};
_proto.getAllBindings = function getAllBindings() {
var ids = Object.create(null);
var scope = this;
do {
(0, _defaults.default)(ids, scope.bindings);
scope = scope.parent;
} while (scope);
return ids;
};
_proto.getAllBindingsOfKind = function getAllBindingsOfKind() {
var ids = Object.create(null);
var _arr13 = arguments;
for (var _i19 = 0; _i19 < _arr13.length; _i19++) {
var kind = _arr13[_i19];
var scope = this;
do {
for (var name in scope.bindings) {
var binding = scope.bindings[name];
if (binding.kind === kind) ids[name] = binding;
}
scope = scope.parent;
} while (scope);
}
return ids;
};
_proto.bindingIdentifierEquals = function bindingIdentifierEquals(name, node) {
return this.getBindingIdentifier(name) === node;
};
_proto.getBinding = function getBinding(name) {
var scope = this;
do {
var binding = scope.getOwnBinding(name);
if (binding) return binding;
} while (scope = scope.parent);
};
_proto.getOwnBinding = function getOwnBinding(name) {
return this.bindings[name];
};
_proto.getBindingIdentifier = function getBindingIdentifier(name) {
var info = this.getBinding(name);
return info && info.identifier;
};
_proto.getOwnBindingIdentifier = function getOwnBindingIdentifier(name) {
var binding = this.bindings[name];
return binding && binding.identifier;
};
_proto.hasOwnBinding = function hasOwnBinding(name) {
return !!this.getOwnBinding(name);
};
_proto.hasBinding = function hasBinding(name, noGlobals) {
if (!name) return false;
if (this.hasOwnBinding(name)) return true;
if (this.parentHasBinding(name, noGlobals)) return true;
if (this.hasUid(name)) return true;
if (!noGlobals && (0, _includes.default)(Scope.globals, name)) return true;
if (!noGlobals && (0, _includes.default)(Scope.contextVariables, name)) return true;
return false;
};
_proto.parentHasBinding = function parentHasBinding(name, noGlobals) {
return this.parent && this.parent.hasBinding(name, noGlobals);
};
_proto.moveBindingTo = function moveBindingTo(name, scope) {
var info = this.getBinding(name);
if (info) {
info.scope.removeOwnBinding(name);
info.scope = scope;
scope.bindings[name] = info;
}
};
_proto.removeOwnBinding = function removeOwnBinding(name) {
delete this.bindings[name];
};
_proto.removeBinding = function removeBinding(name) {
var info = this.getBinding(name);
if (info) {
info.scope.removeOwnBinding(name);
}
var scope = this;
do {
if (scope.uids[name]) {
scope.uids[name] = false;
}
} while (scope = scope.parent);
};
_createClass(Scope, [{
key: "parent",
get: function get() {
var parent = this.path.findParent(function (p) {
return p.isScope();
});
return parent && parent.scope;
}
}, {
key: "parentBlock",
get: function get() {
return this.path.parent;
}
}, {
key: "hub",
get: function get() {
return this.path.hub;
}
}]);
return Scope;
}();
exports.default = Scope;
Scope.globals = Object.keys(_globals.default.builtin);
Scope.contextVariables = ["arguments", "undefined", "Infinity", "NaN"];
@@ -0,0 +1,131 @@
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _binding = _interopRequireDefault(require("../binding"));
var t = _interopRequireWildcard(require("@babel/types"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var renameVisitor = {
ReferencedIdentifier: function ReferencedIdentifier(_ref, state) {
var node = _ref.node;
if (node.name === state.oldName) {
node.name = state.newName;
}
},
Scope: function Scope(path, state) {
if (!path.scope.bindingIdentifierEquals(state.oldName, state.binding.identifier)) {
path.skip();
}
},
"AssignmentExpression|Declaration": function AssignmentExpressionDeclaration(path, state) {
var ids = path.getOuterBindingIdentifiers();
for (var name in ids) {
if (name === state.oldName) ids[name].name = state.newName;
}
}
};
var Renamer = function () {
function Renamer(binding, oldName, newName) {
this.oldName = void 0;
this.newName = void 0;
this.binding = void 0;
this.newName = newName;
this.oldName = oldName;
this.binding = binding;
}
var _proto = Renamer.prototype;
_proto.maybeConvertFromExportDeclaration = function maybeConvertFromExportDeclaration(parentDeclar) {
var exportDeclar = parentDeclar.parentPath.isExportDeclaration() && parentDeclar.parentPath;
if (!exportDeclar) return;
var isDefault = exportDeclar.isExportDefaultDeclaration();
if (isDefault && (parentDeclar.isFunctionDeclaration() || parentDeclar.isClassDeclaration()) && !parentDeclar.node.id) {
parentDeclar.node.id = parentDeclar.scope.generateUidIdentifier("default");
}
var bindingIdentifiers = parentDeclar.getOuterBindingIdentifiers();
var specifiers = [];
for (var name in bindingIdentifiers) {
var localName = name === this.oldName ? this.newName : name;
var exportedName = isDefault ? "default" : name;
specifiers.push(t.exportSpecifier(t.identifier(localName), t.identifier(exportedName)));
}
if (specifiers.length) {
var aliasDeclar = t.exportNamedDeclaration(null, specifiers);
if (parentDeclar.isFunctionDeclaration()) {
aliasDeclar._blockHoist = 3;
}
exportDeclar.insertAfter(aliasDeclar);
exportDeclar.replaceWith(parentDeclar.node);
}
};
_proto.maybeConvertFromClassFunctionDeclaration = function maybeConvertFromClassFunctionDeclaration(path) {
return;
if (!path.isFunctionDeclaration() && !path.isClassDeclaration()) return;
if (this.binding.kind !== "hoisted") return;
path.node.id = t.identifier(this.oldName);
path.node._blockHoist = 3;
path.replaceWith(t.variableDeclaration("let", [t.variableDeclarator(t.identifier(this.newName), t.toExpression(path.node))]));
};
_proto.maybeConvertFromClassFunctionExpression = function maybeConvertFromClassFunctionExpression(path) {
return;
if (!path.isFunctionExpression() && !path.isClassExpression()) return;
if (this.binding.kind !== "local") return;
path.node.id = t.identifier(this.oldName);
this.binding.scope.parent.push({
id: t.identifier(this.newName)
});
path.replaceWith(t.assignmentExpression("=", t.identifier(this.newName), path.node));
};
_proto.rename = function rename(block) {
var binding = this.binding,
oldName = this.oldName,
newName = this.newName;
var scope = binding.scope,
path = binding.path;
var parentDeclar = path.find(function (path) {
return path.isDeclaration() || path.isFunctionExpression();
});
if (parentDeclar) {
this.maybeConvertFromExportDeclaration(parentDeclar);
}
scope.traverse(block || scope.block, renameVisitor, this);
if (!block) {
scope.removeOwnBinding(oldName);
scope.bindings[newName] = binding;
this.binding.identifier.name = newName;
}
if (binding.type === "hoisted") {}
if (parentDeclar) {
this.maybeConvertFromClassFunctionDeclaration(parentDeclar);
this.maybeConvertFromClassFunctionExpression(parentDeclar);
}
};
return Renamer;
}();
exports.default = Renamer;
@@ -0,0 +1,292 @@
"use strict";
exports.__esModule = true;
exports.explode = explode;
exports.verify = verify;
exports.merge = merge;
var virtualTypes = _interopRequireWildcard(require("./path/lib/virtual-types"));
var t = _interopRequireWildcard(require("@babel/types"));
var _clone = _interopRequireDefault(require("lodash/clone"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function explode(visitor) {
if (visitor._exploded) return visitor;
visitor._exploded = true;
for (var nodeType in visitor) {
if (shouldIgnoreKey(nodeType)) continue;
var parts = nodeType.split("|");
if (parts.length === 1) continue;
var fns = visitor[nodeType];
delete visitor[nodeType];
for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var _part = _ref;
visitor[_part] = fns;
}
}
verify(visitor);
delete visitor.__esModule;
ensureEntranceObjects(visitor);
ensureCallbackArrays(visitor);
var _arr = Object.keys(visitor);
for (var _i2 = 0; _i2 < _arr.length; _i2++) {
var _nodeType = _arr[_i2];
if (shouldIgnoreKey(_nodeType)) continue;
var wrapper = virtualTypes[_nodeType];
if (!wrapper) continue;
var _fns = visitor[_nodeType];
for (var type in _fns) {
_fns[type] = wrapCheck(wrapper, _fns[type]);
}
delete visitor[_nodeType];
if (wrapper.types) {
var _arr2 = wrapper.types;
for (var _i4 = 0; _i4 < _arr2.length; _i4++) {
var _type = _arr2[_i4];
if (visitor[_type]) {
mergePair(visitor[_type], _fns);
} else {
visitor[_type] = _fns;
}
}
} else {
mergePair(visitor, _fns);
}
}
for (var _nodeType2 in visitor) {
if (shouldIgnoreKey(_nodeType2)) continue;
var _fns2 = visitor[_nodeType2];
var aliases = t.FLIPPED_ALIAS_KEYS[_nodeType2];
var deprecratedKey = t.DEPRECATED_KEYS[_nodeType2];
if (deprecratedKey) {
console.trace("Visitor defined for " + _nodeType2 + " but it has been renamed to " + deprecratedKey);
aliases = [deprecratedKey];
}
if (!aliases) continue;
delete visitor[_nodeType2];
for (var _iterator2 = aliases, _isArray2 = Array.isArray(_iterator2), _i3 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i3 >= _iterator2.length) break;
_ref2 = _iterator2[_i3++];
} else {
_i3 = _iterator2.next();
if (_i3.done) break;
_ref2 = _i3.value;
}
var _alias = _ref2;
var existing = visitor[_alias];
if (existing) {
mergePair(existing, _fns2);
} else {
visitor[_alias] = (0, _clone.default)(_fns2);
}
}
}
for (var _nodeType3 in visitor) {
if (shouldIgnoreKey(_nodeType3)) continue;
ensureCallbackArrays(visitor[_nodeType3]);
}
return visitor;
}
function verify(visitor) {
if (visitor._verified) return;
if (typeof visitor === "function") {
throw new Error("You passed `traverse()` a function when it expected a visitor object, " + "are you sure you didn't mean `{ enter: Function }`?");
}
for (var nodeType in visitor) {
if (nodeType === "enter" || nodeType === "exit") {
validateVisitorMethods(nodeType, visitor[nodeType]);
}
if (shouldIgnoreKey(nodeType)) continue;
if (t.TYPES.indexOf(nodeType) < 0) {
throw new Error("You gave us a visitor for the node type " + nodeType + " but it's not a valid type");
}
var visitors = visitor[nodeType];
if (typeof visitors === "object") {
for (var visitorKey in visitors) {
if (visitorKey === "enter" || visitorKey === "exit") {
validateVisitorMethods(nodeType + "." + visitorKey, visitors[visitorKey]);
} else {
throw new Error("You passed `traverse()` a visitor object with the property " + (nodeType + " that has the invalid property " + visitorKey));
}
}
}
}
visitor._verified = true;
}
function validateVisitorMethods(path, val) {
var fns = [].concat(val);
for (var _iterator3 = fns, _isArray3 = Array.isArray(_iterator3), _i5 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i5 >= _iterator3.length) break;
_ref3 = _iterator3[_i5++];
} else {
_i5 = _iterator3.next();
if (_i5.done) break;
_ref3 = _i5.value;
}
var _fn = _ref3;
if (typeof _fn !== "function") {
throw new TypeError("Non-function found defined in " + path + " with type " + typeof _fn);
}
}
}
function merge(visitors, states, wrapper) {
if (states === void 0) {
states = [];
}
var rootVisitor = {};
for (var i = 0; i < visitors.length; i++) {
var visitor = visitors[i];
var state = states[i];
explode(visitor);
for (var type in visitor) {
var visitorType = visitor[type];
if (state || wrapper) {
visitorType = wrapWithStateOrWrapper(visitorType, state, wrapper);
}
var nodeVisitor = rootVisitor[type] = rootVisitor[type] || {};
mergePair(nodeVisitor, visitorType);
}
}
return rootVisitor;
}
function wrapWithStateOrWrapper(oldVisitor, state, wrapper) {
var newVisitor = {};
var _loop = function _loop(key) {
var fns = oldVisitor[key];
if (!Array.isArray(fns)) return "continue";
fns = fns.map(function (fn) {
var newFn = fn;
if (state) {
newFn = function newFn(path) {
return fn.call(state, path, state);
};
}
if (wrapper) {
newFn = wrapper(state.key, key, newFn);
}
return newFn;
});
newVisitor[key] = fns;
};
for (var key in oldVisitor) {
var _ret = _loop(key);
if (_ret === "continue") continue;
}
return newVisitor;
}
function ensureEntranceObjects(obj) {
for (var key in obj) {
if (shouldIgnoreKey(key)) continue;
var fns = obj[key];
if (typeof fns === "function") {
obj[key] = {
enter: fns
};
}
}
}
function ensureCallbackArrays(obj) {
if (obj.enter && !Array.isArray(obj.enter)) obj.enter = [obj.enter];
if (obj.exit && !Array.isArray(obj.exit)) obj.exit = [obj.exit];
}
function wrapCheck(wrapper, fn) {
var newFn = function newFn(path) {
if (wrapper.checkPath(path)) {
return fn.apply(this, arguments);
}
};
newFn.toString = function () {
return fn.toString();
};
return newFn;
}
function shouldIgnoreKey(key) {
if (key[0] === "_") return true;
if (key === "enter" || key === "exit" || key === "shouldSkip") return true;
if (key === "blacklist" || key === "noScope" || key === "skipKeys") {
return true;
}
return false;
}
function mergePair(dest, src) {
for (var key in src) {
dest[key] = [].concat(dest[key] || [], src[key]);
}
}
@@ -0,0 +1,56 @@
{
"_from": "@babel/traverse@7.0.0-beta.36",
"_id": "@babel/traverse@7.0.0-beta.36",
"_inBundle": false,
"_integrity": "sha512-OTUb6iSKVR/98dGThRJ1BiyfwbuX10BVnkz89IpaerjTPRhDfMBfLsqmzxz5MiywUOW4M0Clta0o7rSxkfcuzw==",
"_location": "/babel-eslint/@babel/traverse",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@babel/traverse@7.0.0-beta.36",
"name": "@babel/traverse",
"escapedName": "@babel%2ftraverse",
"scope": "@babel",
"rawSpec": "7.0.0-beta.36",
"saveSpec": null,
"fetchSpec": "7.0.0-beta.36"
},
"_requiredBy": [
"/babel-eslint"
],
"_resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.0.0-beta.36.tgz",
"_shasum": "1dc6f8750e89b6b979de5fe44aa993b1a2192261",
"_spec": "@babel/traverse@7.0.0-beta.36",
"_where": "/home/mzasso/git/nodejs/node/tools/babel-eslint-tmp/node_modules/babel-eslint",
"author": {
"name": "Sebastian McKenzie",
"email": "sebmck@gmail.com"
},
"bundleDependencies": false,
"dependencies": {
"@babel/code-frame": "7.0.0-beta.36",
"@babel/helper-function-name": "7.0.0-beta.36",
"@babel/types": "7.0.0-beta.36",
"babylon": "7.0.0-beta.36",
"debug": "^3.0.1",
"globals": "^11.1.0",
"invariant": "^2.2.0",
"lodash": "^4.2.0"
},
"deprecated": false,
"description": "The Babel Traverse module maintains the overall tree state, and is responsible for replacing, removing, and adding nodes",
"devDependencies": {
"@babel/generator": "7.0.0-beta.36",
"@babel/helper-plugin-test-runner": "7.0.0-beta.36"
},
"homepage": "https://babeljs.io/",
"license": "MIT",
"main": "lib/index.js",
"name": "@babel/traverse",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-traverse"
},
"version": "7.0.0-beta.36"
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,15 @@
"use strict";
exports.__esModule = true;
exports.default = assertNode;
var _isNode = _interopRequireDefault(require("../validators/isNode"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function assertNode(node) {
if (!(0, _isNode.default)(node)) {
var type = node && node.type || JSON.stringify(node);
throw new TypeError("Not a valid node of type \"" + type + "\"");
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,44 @@
"use strict";
exports.__esModule = true;
exports.default = builder;
var _clone = _interopRequireDefault(require("lodash/clone"));
var _definitions = require("../definitions");
var _validate = _interopRequireDefault(require("../validators/validate"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function builder(type) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var keys = _definitions.BUILDER_KEYS[type];
var countArgs = args.length;
if (countArgs > keys.length) {
throw new Error(type + ": Too many arguments passed. Received " + countArgs + " but can receive no more than " + keys.length);
}
var node = {
type: type
};
var i = 0;
keys.forEach(function (key) {
var field = _definitions.NODE_FIELDS[type][key];
var arg;
if (i < countArgs) arg = args[i];
if (arg === undefined) arg = (0, _clone.default)(field.default);
node[key] = arg;
i++;
});
for (var key in node) {
(0, _validate.default)(node, key, node[key]);
}
return node;
}
@@ -0,0 +1,26 @@
"use strict";
exports.__esModule = true;
exports.default = createTypeAnnotationBasedOnTypeof;
var _generated = require("../generated");
function createTypeAnnotationBasedOnTypeof(type) {
if (type === "string") {
return (0, _generated.stringTypeAnnotation)();
} else if (type === "number") {
return (0, _generated.numberTypeAnnotation)();
} else if (type === "undefined") {
return (0, _generated.voidTypeAnnotation)();
} else if (type === "boolean") {
return (0, _generated.booleanTypeAnnotation)();
} else if (type === "function") {
return (0, _generated.genericTypeAnnotation)((0, _generated.identifier)("Function"));
} else if (type === "object") {
return (0, _generated.genericTypeAnnotation)((0, _generated.identifier)("Object"));
} else if (type === "symbol") {
return (0, _generated.genericTypeAnnotation)((0, _generated.identifier)("Symbol"));
} else {
throw new Error("Invalid typeof value");
}
}
@@ -0,0 +1,20 @@
"use strict";
exports.__esModule = true;
exports.default = createUnionTypeAnnotation;
var _generated = require("../generated");
var _removeTypeDuplicates = _interopRequireDefault(require("../../modifications/flow/removeTypeDuplicates"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function createUnionTypeAnnotation(types) {
var flattened = (0, _removeTypeDuplicates.default)(types);
if (flattened.length === 1) {
return flattened[0];
} else {
return (0, _generated.unionTypeAnnotation)(flattened);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,29 @@
"use strict";
exports.__esModule = true;
exports.default = buildChildren;
var _generated = require("../../validators/generated");
var _cleanJSXElementLiteralChild = _interopRequireDefault(require("../../utils/react/cleanJSXElementLiteralChild"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function buildChildren(node) {
var elements = [];
for (var i = 0; i < node.children.length; i++) {
var child = node.children[i];
if ((0, _generated.isJSXText)(child)) {
(0, _cleanJSXElementLiteralChild.default)(child, elements);
continue;
}
if ((0, _generated.isJSXExpressionContainer)(child)) child = child.expression;
if ((0, _generated.isJSXEmptyExpression)(child)) continue;
elements.push(child);
}
return elements;
}
@@ -0,0 +1,14 @@
"use strict";
exports.__esModule = true;
exports.default = clone;
function clone(node) {
if (!node) return node;
var newNode = {};
Object.keys(node).forEach(function (key) {
if (key[0] === "_") return;
newNode[key] = node[key];
});
return newNode;
}
@@ -0,0 +1,24 @@
"use strict";
exports.__esModule = true;
exports.default = cloneDeep;
function cloneDeep(node) {
if (!node) return node;
var newNode = {};
Object.keys(node).forEach(function (key) {
if (key[0] === "_") return;
var val = node[key];
if (val) {
if (val.type) {
val = cloneDeep(val);
} else if (Array.isArray(val)) {
val = val.map(cloneDeep);
}
}
newNode[key] = val;
});
return newNode;
}
@@ -0,0 +1,14 @@
"use strict";
exports.__esModule = true;
exports.default = cloneWithoutLoc;
var _clone = _interopRequireDefault(require("./clone"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function cloneWithoutLoc(node) {
var newNode = (0, _clone.default)(node);
newNode.loc = null;
return newNode;
}
@@ -0,0 +1,15 @@
"use strict";
exports.__esModule = true;
exports.default = addComment;
var _addComments = _interopRequireDefault(require("./addComments"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function addComment(node, type, content, line) {
return (0, _addComments.default)(node, type, [{
type: line ? "CommentLine" : "CommentBlock",
value: content
}]);
}
@@ -0,0 +1,21 @@
"use strict";
exports.__esModule = true;
exports.default = addComments;
function addComments(node, type, comments) {
if (!comments || !node) return node;
var key = type + "Comments";
if (node[key]) {
if (type === "leading") {
node[key] = comments.concat(node[key]);
} else {
node[key] = node[key].concat(comments);
}
} else {
node[key] = comments;
}
return node;
}
@@ -0,0 +1,12 @@
"use strict";
exports.__esModule = true;
exports.default = inheritInnerComments;
var _inherit = _interopRequireDefault(require("../utils/inherit"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function inheritInnerComments(child, parent) {
(0, _inherit.default)("innerComments", child, parent);
}
@@ -0,0 +1,12 @@
"use strict";
exports.__esModule = true;
exports.default = inheritLeadingComments;
var _inherit = _interopRequireDefault(require("../utils/inherit"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function inheritLeadingComments(child, parent) {
(0, _inherit.default)("leadingComments", child, parent);
}
@@ -0,0 +1,12 @@
"use strict";
exports.__esModule = true;
exports.default = inheritTrailingComments;
var _inherit = _interopRequireDefault(require("../utils/inherit"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function inheritTrailingComments(child, parent) {
(0, _inherit.default)("trailingComments", child, parent);
}
@@ -0,0 +1,19 @@
"use strict";
exports.__esModule = true;
exports.default = inheritsComments;
var _inheritTrailingComments = _interopRequireDefault(require("./inheritTrailingComments"));
var _inheritLeadingComments = _interopRequireDefault(require("./inheritLeadingComments"));
var _inheritInnerComments = _interopRequireDefault(require("./inheritInnerComments"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function inheritsComments(child, parent) {
(0, _inheritTrailingComments.default)(child, parent);
(0, _inheritLeadingComments.default)(child, parent);
(0, _inheritInnerComments.default)(child, parent);
return child;
}
@@ -0,0 +1,14 @@
"use strict";
exports.__esModule = true;
exports.default = removeComments;
var _constants = require("../constants");
function removeComments(node) {
_constants.COMMENT_KEYS.forEach(function (key) {
node[key] = null;
});
return node;
}
@@ -0,0 +1,87 @@
"use strict";
exports.__esModule = true;
exports.TSTYPE_TYPES = exports.TSTYPEELEMENT_TYPES = exports.JSX_TYPES = exports.FLOWPREDICATE_TYPES = exports.FLOWDECLARATION_TYPES = exports.FLOWBASEANNOTATION_TYPES = exports.FLOW_TYPES = exports.MODULESPECIFIER_TYPES = exports.EXPORTDECLARATION_TYPES = exports.MODULEDECLARATION_TYPES = exports.CLASS_TYPES = exports.PATTERN_TYPES = exports.UNARYLIKE_TYPES = exports.PROPERTY_TYPES = exports.OBJECTMEMBER_TYPES = exports.METHOD_TYPES = exports.USERWHITESPACABLE_TYPES = exports.IMMUTABLE_TYPES = exports.LITERAL_TYPES = exports.TSENTITYNAME_TYPES = exports.LVAL_TYPES = exports.PATTERNLIKE_TYPES = exports.DECLARATION_TYPES = exports.PUREISH_TYPES = exports.FUNCTIONPARENT_TYPES = exports.FUNCTION_TYPES = exports.FORXSTATEMENT_TYPES = exports.FOR_TYPES = exports.EXPRESSIONWRAPPER_TYPES = exports.WHILE_TYPES = exports.LOOP_TYPES = exports.CONDITIONAL_TYPES = exports.COMPLETIONSTATEMENT_TYPES = exports.TERMINATORLESS_TYPES = exports.STATEMENT_TYPES = exports.BLOCK_TYPES = exports.BLOCKPARENT_TYPES = exports.SCOPABLE_TYPES = exports.BINARY_TYPES = exports.EXPRESSION_TYPES = void 0;
var _definitions = require("../../definitions");
var EXPRESSION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Expression"];
exports.EXPRESSION_TYPES = EXPRESSION_TYPES;
var BINARY_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Binary"];
exports.BINARY_TYPES = BINARY_TYPES;
var SCOPABLE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Scopable"];
exports.SCOPABLE_TYPES = SCOPABLE_TYPES;
var BLOCKPARENT_TYPES = _definitions.FLIPPED_ALIAS_KEYS["BlockParent"];
exports.BLOCKPARENT_TYPES = BLOCKPARENT_TYPES;
var BLOCK_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Block"];
exports.BLOCK_TYPES = BLOCK_TYPES;
var STATEMENT_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Statement"];
exports.STATEMENT_TYPES = STATEMENT_TYPES;
var TERMINATORLESS_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Terminatorless"];
exports.TERMINATORLESS_TYPES = TERMINATORLESS_TYPES;
var COMPLETIONSTATEMENT_TYPES = _definitions.FLIPPED_ALIAS_KEYS["CompletionStatement"];
exports.COMPLETIONSTATEMENT_TYPES = COMPLETIONSTATEMENT_TYPES;
var CONDITIONAL_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Conditional"];
exports.CONDITIONAL_TYPES = CONDITIONAL_TYPES;
var LOOP_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Loop"];
exports.LOOP_TYPES = LOOP_TYPES;
var WHILE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["While"];
exports.WHILE_TYPES = WHILE_TYPES;
var EXPRESSIONWRAPPER_TYPES = _definitions.FLIPPED_ALIAS_KEYS["ExpressionWrapper"];
exports.EXPRESSIONWRAPPER_TYPES = EXPRESSIONWRAPPER_TYPES;
var FOR_TYPES = _definitions.FLIPPED_ALIAS_KEYS["For"];
exports.FOR_TYPES = FOR_TYPES;
var FORXSTATEMENT_TYPES = _definitions.FLIPPED_ALIAS_KEYS["ForXStatement"];
exports.FORXSTATEMENT_TYPES = FORXSTATEMENT_TYPES;
var FUNCTION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Function"];
exports.FUNCTION_TYPES = FUNCTION_TYPES;
var FUNCTIONPARENT_TYPES = _definitions.FLIPPED_ALIAS_KEYS["FunctionParent"];
exports.FUNCTIONPARENT_TYPES = FUNCTIONPARENT_TYPES;
var PUREISH_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Pureish"];
exports.PUREISH_TYPES = PUREISH_TYPES;
var DECLARATION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Declaration"];
exports.DECLARATION_TYPES = DECLARATION_TYPES;
var PATTERNLIKE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["PatternLike"];
exports.PATTERNLIKE_TYPES = PATTERNLIKE_TYPES;
var LVAL_TYPES = _definitions.FLIPPED_ALIAS_KEYS["LVal"];
exports.LVAL_TYPES = LVAL_TYPES;
var TSENTITYNAME_TYPES = _definitions.FLIPPED_ALIAS_KEYS["TSEntityName"];
exports.TSENTITYNAME_TYPES = TSENTITYNAME_TYPES;
var LITERAL_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Literal"];
exports.LITERAL_TYPES = LITERAL_TYPES;
var IMMUTABLE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Immutable"];
exports.IMMUTABLE_TYPES = IMMUTABLE_TYPES;
var USERWHITESPACABLE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["UserWhitespacable"];
exports.USERWHITESPACABLE_TYPES = USERWHITESPACABLE_TYPES;
var METHOD_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Method"];
exports.METHOD_TYPES = METHOD_TYPES;
var OBJECTMEMBER_TYPES = _definitions.FLIPPED_ALIAS_KEYS["ObjectMember"];
exports.OBJECTMEMBER_TYPES = OBJECTMEMBER_TYPES;
var PROPERTY_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Property"];
exports.PROPERTY_TYPES = PROPERTY_TYPES;
var UNARYLIKE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["UnaryLike"];
exports.UNARYLIKE_TYPES = UNARYLIKE_TYPES;
var PATTERN_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Pattern"];
exports.PATTERN_TYPES = PATTERN_TYPES;
var CLASS_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Class"];
exports.CLASS_TYPES = CLASS_TYPES;
var MODULEDECLARATION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["ModuleDeclaration"];
exports.MODULEDECLARATION_TYPES = MODULEDECLARATION_TYPES;
var EXPORTDECLARATION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["ExportDeclaration"];
exports.EXPORTDECLARATION_TYPES = EXPORTDECLARATION_TYPES;
var MODULESPECIFIER_TYPES = _definitions.FLIPPED_ALIAS_KEYS["ModuleSpecifier"];
exports.MODULESPECIFIER_TYPES = MODULESPECIFIER_TYPES;
var FLOW_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Flow"];
exports.FLOW_TYPES = FLOW_TYPES;
var FLOWBASEANNOTATION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["FlowBaseAnnotation"];
exports.FLOWBASEANNOTATION_TYPES = FLOWBASEANNOTATION_TYPES;
var FLOWDECLARATION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["FlowDeclaration"];
exports.FLOWDECLARATION_TYPES = FLOWDECLARATION_TYPES;
var FLOWPREDICATE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["FlowPredicate"];
exports.FLOWPREDICATE_TYPES = FLOWPREDICATE_TYPES;
var JSX_TYPES = _definitions.FLIPPED_ALIAS_KEYS["JSX"];
exports.JSX_TYPES = JSX_TYPES;
var TSTYPEELEMENT_TYPES = _definitions.FLIPPED_ALIAS_KEYS["TSTypeElement"];
exports.TSTYPEELEMENT_TYPES = TSTYPEELEMENT_TYPES;
var TSTYPE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["TSType"];
exports.TSTYPE_TYPES = TSTYPE_TYPES;
@@ -0,0 +1,45 @@
"use strict";
exports.__esModule = true;
exports.NOT_LOCAL_BINDING = exports.BLOCK_SCOPED_SYMBOL = exports.INHERIT_KEYS = exports.UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = exports.BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = exports.UPDATE_OPERATORS = exports.LOGICAL_OPERATORS = exports.COMMENT_KEYS = exports.FOR_INIT_KEYS = exports.FLATTENABLE_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = void 0;
var STATEMENT_OR_BLOCK_KEYS = ["consequent", "body", "alternate"];
exports.STATEMENT_OR_BLOCK_KEYS = STATEMENT_OR_BLOCK_KEYS;
var FLATTENABLE_KEYS = ["body", "expressions"];
exports.FLATTENABLE_KEYS = FLATTENABLE_KEYS;
var FOR_INIT_KEYS = ["left", "init"];
exports.FOR_INIT_KEYS = FOR_INIT_KEYS;
var COMMENT_KEYS = ["leadingComments", "trailingComments", "innerComments"];
exports.COMMENT_KEYS = COMMENT_KEYS;
var LOGICAL_OPERATORS = ["||", "&&", "??"];
exports.LOGICAL_OPERATORS = LOGICAL_OPERATORS;
var UPDATE_OPERATORS = ["++", "--"];
exports.UPDATE_OPERATORS = UPDATE_OPERATORS;
var BOOLEAN_NUMBER_BINARY_OPERATORS = [">", "<", ">=", "<="];
exports.BOOLEAN_NUMBER_BINARY_OPERATORS = BOOLEAN_NUMBER_BINARY_OPERATORS;
var EQUALITY_BINARY_OPERATORS = ["==", "===", "!=", "!=="];
exports.EQUALITY_BINARY_OPERATORS = EQUALITY_BINARY_OPERATORS;
var COMPARISON_BINARY_OPERATORS = EQUALITY_BINARY_OPERATORS.concat(["in", "instanceof"]);
exports.COMPARISON_BINARY_OPERATORS = COMPARISON_BINARY_OPERATORS;
var BOOLEAN_BINARY_OPERATORS = COMPARISON_BINARY_OPERATORS.concat(BOOLEAN_NUMBER_BINARY_OPERATORS);
exports.BOOLEAN_BINARY_OPERATORS = BOOLEAN_BINARY_OPERATORS;
var NUMBER_BINARY_OPERATORS = ["-", "/", "%", "*", "**", "&", "|", ">>", ">>>", "<<", "^"];
exports.NUMBER_BINARY_OPERATORS = NUMBER_BINARY_OPERATORS;
var BINARY_OPERATORS = ["+"].concat(NUMBER_BINARY_OPERATORS, BOOLEAN_BINARY_OPERATORS);
exports.BINARY_OPERATORS = BINARY_OPERATORS;
var BOOLEAN_UNARY_OPERATORS = ["delete", "!"];
exports.BOOLEAN_UNARY_OPERATORS = BOOLEAN_UNARY_OPERATORS;
var NUMBER_UNARY_OPERATORS = ["+", "-", "~"];
exports.NUMBER_UNARY_OPERATORS = NUMBER_UNARY_OPERATORS;
var STRING_UNARY_OPERATORS = ["typeof"];
exports.STRING_UNARY_OPERATORS = STRING_UNARY_OPERATORS;
var UNARY_OPERATORS = ["void", "throw"].concat(BOOLEAN_UNARY_OPERATORS, NUMBER_UNARY_OPERATORS, STRING_UNARY_OPERATORS);
exports.UNARY_OPERATORS = UNARY_OPERATORS;
var INHERIT_KEYS = {
optional: ["typeAnnotation", "typeParameters", "returnType"],
force: ["start", "loc", "end"]
};
exports.INHERIT_KEYS = INHERIT_KEYS;
var BLOCK_SCOPED_SYMBOL = Symbol.for("var used to be block scoped");
exports.BLOCK_SCOPED_SYMBOL = BLOCK_SCOPED_SYMBOL;
var NOT_LOCAL_BINDING = Symbol.for("should not be considered a local binding");
exports.NOT_LOCAL_BINDING = NOT_LOCAL_BINDING;
@@ -0,0 +1,16 @@
"use strict";
exports.__esModule = true;
exports.default = ensureBlock;
var _toBlock = _interopRequireDefault(require("./toBlock"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function ensureBlock(node, key) {
if (key === void 0) {
key = "body";
}
return node[key] = (0, _toBlock.default)(node[key], node);
}
@@ -0,0 +1,83 @@
"use strict";
exports.__esModule = true;
exports.default = gatherSequenceExpressions;
var _getBindingIdentifiers = _interopRequireDefault(require("../retrievers/getBindingIdentifiers"));
var _generated = require("../validators/generated");
var _generated2 = require("../builders/generated");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function gatherSequenceExpressions(nodes, scope, declars) {
var exprs = [];
var ensureLastUndefined = true;
for (var _iterator = nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var _node = _ref;
ensureLastUndefined = false;
if ((0, _generated.isExpression)(_node)) {
exprs.push(_node);
} else if ((0, _generated.isExpressionStatement)(_node)) {
exprs.push(_node.expression);
} else if ((0, _generated.isVariableDeclaration)(_node)) {
if (_node.kind !== "var") return;
var _arr = _node.declarations;
for (var _i2 = 0; _i2 < _arr.length; _i2++) {
var declar = _arr[_i2];
var bindings = (0, _getBindingIdentifiers.default)(declar);
for (var key in bindings) {
declars.push({
kind: _node.kind,
id: bindings[key]
});
}
if (declar.init) {
exprs.push((0, _generated2.assignmentExpression)("=", declar.id, declar.init));
}
}
ensureLastUndefined = true;
} else if ((0, _generated.isIfStatement)(_node)) {
var consequent = _node.consequent ? gatherSequenceExpressions([_node.consequent], scope, declars) : scope.buildUndefinedNode();
var alternate = _node.alternate ? gatherSequenceExpressions([_node.alternate], scope, declars) : scope.buildUndefinedNode();
if (!consequent || !alternate) return;
exprs.push((0, _generated2.conditionalExpression)(_node.test, consequent, alternate));
} else if ((0, _generated.isBlockStatement)(_node)) {
var body = gatherSequenceExpressions(_node.body, scope, declars);
if (!body) return;
exprs.push(body);
} else if ((0, _generated.isEmptyStatement)(_node)) {
ensureLastUndefined = true;
} else {
return;
}
}
if (ensureLastUndefined) {
exprs.push(scope.buildUndefinedNode());
}
if (exprs.length === 1) {
return exprs[0];
} else {
return (0, _generated2.sequenceExpression)(exprs);
}
}
@@ -0,0 +1,14 @@
"use strict";
exports.__esModule = true;
exports.default = toBindingIdentifierName;
var _toIdentifier = _interopRequireDefault(require("./toIdentifier"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function toBindingIdentifierName(name) {
name = (0, _toIdentifier.default)(name);
if (name === "eval" || name === "arguments") name = "_" + name;
return name;
}
@@ -0,0 +1,32 @@
"use strict";
exports.__esModule = true;
exports.default = toBlock;
var _generated = require("../validators/generated");
var _generated2 = require("../builders/generated");
function toBlock(node, parent) {
if ((0, _generated.isBlockStatement)(node)) {
return node;
}
var blockNodes = [];
if ((0, _generated.isEmptyStatement)(node)) {
blockNodes = [];
} else {
if (!(0, _generated.isStatement)(node)) {
if ((0, _generated.isFunction)(parent)) {
node = (0, _generated2.returnStatement)(node);
} else {
node = (0, _generated2.expressionStatement)(node);
}
}
blockNodes = [node];
}
return (0, _generated2.blockStatement)(blockNodes);
}
@@ -0,0 +1,17 @@
"use strict";
exports.__esModule = true;
exports.default = toComputedKey;
var _generated = require("../validators/generated");
var _generated2 = require("../builders/generated");
function toComputedKey(node, key) {
if (key === void 0) {
key = node.key || node.property;
}
if (!node.computed && (0, _generated.isIdentifier)(key)) key = (0, _generated2.stringLiteral)(key.name);
return key;
}
@@ -0,0 +1,28 @@
"use strict";
exports.__esModule = true;
exports.default = toExpression;
var _generated = require("../validators/generated");
function toExpression(node) {
if ((0, _generated.isExpressionStatement)(node)) {
node = node.expression;
}
if ((0, _generated.isExpression)(node)) {
return node;
}
if ((0, _generated.isClass)(node)) {
node.type = "ClassExpression";
} else if ((0, _generated.isFunction)(node)) {
node.type = "FunctionExpression";
}
if (!(0, _generated.isExpression)(node)) {
throw new Error("cannot turn " + node.type + " to an expression");
}
return node;
}
@@ -0,0 +1,23 @@
"use strict";
exports.__esModule = true;
exports.default = toIdentifier;
var _isValidIdentifier = _interopRequireDefault(require("../validators/isValidIdentifier"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function toIdentifier(name) {
name = name + "";
name = name.replace(/[^a-zA-Z0-9$_]/g, "-");
name = name.replace(/^[-0-9]+/, "");
name = name.replace(/[-\s]+(.)?/g, function (match, c) {
return c ? c.toUpperCase() : "";
});
if (!(0, _isValidIdentifier.default)(name)) {
name = "_" + name;
}
return name || "_";
}
@@ -0,0 +1,50 @@
"use strict";
exports.__esModule = true;
exports.default = toKeyAlias;
var _generated = require("../validators/generated");
var _cloneDeep = _interopRequireDefault(require("../clone/cloneDeep"));
var _removePropertiesDeep = _interopRequireDefault(require("../modifications/removePropertiesDeep"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function toKeyAlias(node, key) {
if (key === void 0) {
key = node.key;
}
var alias;
if (node.kind === "method") {
return toKeyAlias.increment() + "";
} else if ((0, _generated.isIdentifier)(key)) {
alias = key.name;
} else if ((0, _generated.isStringLiteral)(key)) {
alias = JSON.stringify(key.value);
} else {
alias = JSON.stringify((0, _removePropertiesDeep.default)((0, _cloneDeep.default)(key)));
}
if (node.computed) {
alias = "[" + alias + "]";
}
if (node.static) {
alias = "static:" + alias;
}
return alias;
}
toKeyAlias.uid = 0;
toKeyAlias.increment = function () {
if (toKeyAlias.uid >= Number.MAX_SAFE_INTEGER) {
return toKeyAlias.uid = 0;
} else {
return toKeyAlias.uid++;
}
};
@@ -0,0 +1,22 @@
"use strict";
exports.__esModule = true;
exports.default = toSequenceExpression;
var _gatherSequenceExpressions = _interopRequireDefault(require("./gatherSequenceExpressions"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function toSequenceExpression(nodes, scope) {
if (!nodes || !nodes.length) return;
var declars = [];
var result = (0, _gatherSequenceExpressions.default)(nodes, scope, declars);
if (!result) return;
for (var _i = 0; _i < declars.length; _i++) {
var declar = declars[_i];
scope.push(declar);
}
return result;
}
@@ -0,0 +1,42 @@
"use strict";
exports.__esModule = true;
exports.default = toStatement;
var _generated = require("../validators/generated");
var _generated2 = require("../builders/generated");
function toStatement(node, ignore) {
if ((0, _generated.isStatement)(node)) {
return node;
}
var mustHaveId = false;
var newType;
if ((0, _generated.isClass)(node)) {
mustHaveId = true;
newType = "ClassDeclaration";
} else if ((0, _generated.isFunction)(node)) {
mustHaveId = true;
newType = "FunctionDeclaration";
} else if ((0, _generated.isAssignmentExpression)(node)) {
return (0, _generated2.expressionStatement)(node);
}
if (mustHaveId && !node.id) {
newType = false;
}
if (!newType) {
if (ignore) {
return false;
} else {
throw new Error("cannot turn " + node.type + " to a statement");
}
}
node.type = newType;
return node;
}
@@ -0,0 +1,66 @@
"use strict";
exports.__esModule = true;
exports.default = valueToNode;
var _isPlainObject = _interopRequireDefault(require("lodash/isPlainObject"));
var _isRegExp = _interopRequireDefault(require("lodash/isRegExp"));
var _isValidIdentifier = _interopRequireDefault(require("../validators/isValidIdentifier"));
var _generated = require("../builders/generated");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function valueToNode(value) {
if (value === undefined) {
return (0, _generated.identifier)("undefined");
}
if (value === true || value === false) {
return (0, _generated.booleanLiteral)(value);
}
if (value === null) {
return (0, _generated.nullLiteral)();
}
if (typeof value === "string") {
return (0, _generated.stringLiteral)(value);
}
if (typeof value === "number") {
return (0, _generated.numericLiteral)(value);
}
if ((0, _isRegExp.default)(value)) {
var pattern = value.source;
var flags = value.toString().match(/\/([a-z]+|)$/)[1];
return (0, _generated.regExpLiteral)(pattern, flags);
}
if (Array.isArray(value)) {
return (0, _generated.arrayExpression)(value.map(valueToNode));
}
if ((0, _isPlainObject.default)(value)) {
var props = [];
for (var key in value) {
var nodeKey = void 0;
if ((0, _isValidIdentifier.default)(key)) {
nodeKey = (0, _generated.identifier)(key);
} else {
nodeKey = (0, _generated.stringLiteral)(key);
}
props.push((0, _generated.objectProperty)(nodeKey, valueToNode(value[key])));
}
return (0, _generated.objectExpression)(props);
}
throw new Error("don't know how to turn this value into a node");
}
@@ -0,0 +1,693 @@
"use strict";
exports.__esModule = true;
exports.patternLikeCommon = exports.functionDeclarationCommon = exports.functionTypeAnnotationCommon = exports.functionCommon = void 0;
var _isValidIdentifier = _interopRequireDefault(require("../validators/isValidIdentifier"));
var _constants = require("../constants");
var _utils = _interopRequireWildcard(require("./utils"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
(0, _utils.default)("ArrayExpression", {
fields: {
elements: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeOrValueType)("null", "Expression", "SpreadElement"))),
default: []
}
},
visitor: ["elements"],
aliases: ["Expression"]
});
(0, _utils.default)("AssignmentExpression", {
fields: {
operator: {
validate: (0, _utils.assertValueType)("string")
},
left: {
validate: (0, _utils.assertNodeType)("LVal")
},
right: {
validate: (0, _utils.assertNodeType)("Expression")
}
},
builder: ["operator", "left", "right"],
visitor: ["left", "right"],
aliases: ["Expression"]
});
(0, _utils.default)("BinaryExpression", {
builder: ["operator", "left", "right"],
fields: {
operator: {
validate: _utils.assertOneOf.apply(void 0, _constants.BINARY_OPERATORS)
},
left: {
validate: (0, _utils.assertNodeType)("Expression")
},
right: {
validate: (0, _utils.assertNodeType)("Expression")
}
},
visitor: ["left", "right"],
aliases: ["Binary", "Expression"]
});
(0, _utils.default)("Directive", {
visitor: ["value"],
fields: {
value: {
validate: (0, _utils.assertNodeType)("DirectiveLiteral")
}
}
});
(0, _utils.default)("DirectiveLiteral", {
builder: ["value"],
fields: {
value: {
validate: (0, _utils.assertValueType)("string")
}
}
});
(0, _utils.default)("BlockStatement", {
builder: ["body", "directives"],
visitor: ["directives", "body"],
fields: {
directives: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Directive"))),
default: []
},
body: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Statement")))
}
},
aliases: ["Scopable", "BlockParent", "Block", "Statement"]
});
(0, _utils.default)("BreakStatement", {
visitor: ["label"],
fields: {
label: {
validate: (0, _utils.assertNodeType)("Identifier"),
optional: true
}
},
aliases: ["Statement", "Terminatorless", "CompletionStatement"]
});
(0, _utils.default)("CallExpression", {
visitor: ["callee", "arguments", "typeParameters"],
builder: ["callee", "arguments"],
aliases: ["Expression"],
fields: {
callee: {
validate: (0, _utils.assertNodeType)("Expression")
},
arguments: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression", "SpreadElement", "JSXNamespacedName")))
},
optional: {
validate: (0, _utils.assertOneOf)(true, false),
optional: true
},
typeParameters: {
validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"),
optional: true
}
}
});
(0, _utils.default)("CatchClause", {
visitor: ["param", "body"],
fields: {
param: {
validate: (0, _utils.assertNodeType)("Identifier"),
optional: true
},
body: {
validate: (0, _utils.assertNodeType)("BlockStatement")
}
},
aliases: ["Scopable", "BlockParent"]
});
(0, _utils.default)("ConditionalExpression", {
visitor: ["test", "consequent", "alternate"],
fields: {
test: {
validate: (0, _utils.assertNodeType)("Expression")
},
consequent: {
validate: (0, _utils.assertNodeType)("Expression")
},
alternate: {
validate: (0, _utils.assertNodeType)("Expression")
}
},
aliases: ["Expression", "Conditional"]
});
(0, _utils.default)("ContinueStatement", {
visitor: ["label"],
fields: {
label: {
validate: (0, _utils.assertNodeType)("Identifier"),
optional: true
}
},
aliases: ["Statement", "Terminatorless", "CompletionStatement"]
});
(0, _utils.default)("DebuggerStatement", {
aliases: ["Statement"]
});
(0, _utils.default)("DoWhileStatement", {
visitor: ["test", "body"],
fields: {
test: {
validate: (0, _utils.assertNodeType)("Expression")
},
body: {
validate: (0, _utils.assertNodeType)("Statement")
}
},
aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"]
});
(0, _utils.default)("EmptyStatement", {
aliases: ["Statement"]
});
(0, _utils.default)("ExpressionStatement", {
visitor: ["expression"],
fields: {
expression: {
validate: (0, _utils.assertNodeType)("Expression")
}
},
aliases: ["Statement", "ExpressionWrapper"]
});
(0, _utils.default)("File", {
builder: ["program", "comments", "tokens"],
visitor: ["program"],
fields: {
program: {
validate: (0, _utils.assertNodeType)("Program")
}
}
});
(0, _utils.default)("ForInStatement", {
visitor: ["left", "right", "body"],
aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"],
fields: {
left: {
validate: (0, _utils.assertNodeType)("VariableDeclaration", "LVal")
},
right: {
validate: (0, _utils.assertNodeType)("Expression")
},
body: {
validate: (0, _utils.assertNodeType)("Statement")
}
}
});
(0, _utils.default)("ForStatement", {
visitor: ["init", "test", "update", "body"],
aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop"],
fields: {
init: {
validate: (0, _utils.assertNodeType)("VariableDeclaration", "Expression"),
optional: true
},
test: {
validate: (0, _utils.assertNodeType)("Expression"),
optional: true
},
update: {
validate: (0, _utils.assertNodeType)("Expression"),
optional: true
},
body: {
validate: (0, _utils.assertNodeType)("Statement")
}
}
});
var functionCommon = {
params: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("LVal")))
},
generator: {
default: false,
validate: (0, _utils.assertValueType)("boolean")
},
async: {
validate: (0, _utils.assertValueType)("boolean"),
default: false
}
};
exports.functionCommon = functionCommon;
var functionTypeAnnotationCommon = {
returnType: {
validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"),
optional: true
},
typeParameters: {
validate: (0, _utils.assertNodeType)("TypeParameterDeclaration", "TSTypeParameterDeclaration", "Noop"),
optional: true
}
};
exports.functionTypeAnnotationCommon = functionTypeAnnotationCommon;
var functionDeclarationCommon = Object.assign({}, functionCommon, {
declare: {
validate: (0, _utils.assertValueType)("boolean"),
optional: true
},
id: {
validate: (0, _utils.assertNodeType)("Identifier"),
optional: true
}
});
exports.functionDeclarationCommon = functionDeclarationCommon;
(0, _utils.default)("FunctionDeclaration", {
builder: ["id", "params", "body", "generator", "async"],
visitor: ["id", "params", "body", "returnType", "typeParameters"],
fields: Object.assign({}, functionDeclarationCommon, functionTypeAnnotationCommon, {
body: {
validate: (0, _utils.assertNodeType)("BlockStatement")
}
}),
aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Statement", "Pureish", "Declaration"]
});
(0, _utils.default)("FunctionExpression", {
inherits: "FunctionDeclaration",
aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"],
fields: Object.assign({}, functionCommon, functionTypeAnnotationCommon, {
id: {
validate: (0, _utils.assertNodeType)("Identifier"),
optional: true
},
body: {
validate: (0, _utils.assertNodeType)("BlockStatement")
}
})
});
var patternLikeCommon = {
typeAnnotation: {
validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"),
optional: true
},
decorators: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator")))
}
};
exports.patternLikeCommon = patternLikeCommon;
(0, _utils.default)("Identifier", {
builder: ["name"],
visitor: ["typeAnnotation"],
aliases: ["Expression", "PatternLike", "LVal", "TSEntityName"],
fields: Object.assign({}, patternLikeCommon, {
name: {
validate: function validate(node, key, val) {
if (!(0, _isValidIdentifier.default)(val)) {}
}
},
optional: {
validate: (0, _utils.assertValueType)("boolean"),
optional: true
}
})
});
(0, _utils.default)("IfStatement", {
visitor: ["test", "consequent", "alternate"],
aliases: ["Statement", "Conditional"],
fields: {
test: {
validate: (0, _utils.assertNodeType)("Expression")
},
consequent: {
validate: (0, _utils.assertNodeType)("Statement")
},
alternate: {
optional: true,
validate: (0, _utils.assertNodeType)("Statement")
}
}
});
(0, _utils.default)("LabeledStatement", {
visitor: ["label", "body"],
aliases: ["Statement"],
fields: {
label: {
validate: (0, _utils.assertNodeType)("Identifier")
},
body: {
validate: (0, _utils.assertNodeType)("Statement")
}
}
});
(0, _utils.default)("StringLiteral", {
builder: ["value"],
fields: {
value: {
validate: (0, _utils.assertValueType)("string")
}
},
aliases: ["Expression", "Pureish", "Literal", "Immutable"]
});
(0, _utils.default)("NumericLiteral", {
builder: ["value"],
deprecatedAlias: "NumberLiteral",
fields: {
value: {
validate: (0, _utils.assertValueType)("number")
}
},
aliases: ["Expression", "Pureish", "Literal", "Immutable"]
});
(0, _utils.default)("NullLiteral", {
aliases: ["Expression", "Pureish", "Literal", "Immutable"]
});
(0, _utils.default)("BooleanLiteral", {
builder: ["value"],
fields: {
value: {
validate: (0, _utils.assertValueType)("boolean")
}
},
aliases: ["Expression", "Pureish", "Literal", "Immutable"]
});
(0, _utils.default)("RegExpLiteral", {
builder: ["pattern", "flags"],
deprecatedAlias: "RegexLiteral",
aliases: ["Expression", "Literal"],
fields: {
pattern: {
validate: (0, _utils.assertValueType)("string")
},
flags: {
validate: (0, _utils.assertValueType)("string"),
default: ""
}
}
});
(0, _utils.default)("LogicalExpression", {
builder: ["operator", "left", "right"],
visitor: ["left", "right"],
aliases: ["Binary", "Expression"],
fields: {
operator: {
validate: _utils.assertOneOf.apply(void 0, _constants.LOGICAL_OPERATORS)
},
left: {
validate: (0, _utils.assertNodeType)("Expression")
},
right: {
validate: (0, _utils.assertNodeType)("Expression")
}
}
});
(0, _utils.default)("MemberExpression", {
builder: ["object", "property", "computed", "optional"],
visitor: ["object", "property"],
aliases: ["Expression", "LVal"],
fields: {
object: {
validate: (0, _utils.assertNodeType)("Expression")
},
property: {
validate: function () {
var normal = (0, _utils.assertNodeType)("Identifier");
var computed = (0, _utils.assertNodeType)("Expression");
return function (node, key, val) {
var validator = node.computed ? computed : normal;
validator(node, key, val);
};
}()
},
computed: {
default: false
},
optional: {
validate: (0, _utils.assertOneOf)(true, false),
optional: true
}
}
});
(0, _utils.default)("NewExpression", {
inherits: "CallExpression"
});
(0, _utils.default)("Program", {
visitor: ["directives", "body"],
builder: ["body", "directives", "sourceType"],
fields: {
sourceFile: {
validate: (0, _utils.assertValueType)("string")
},
sourceType: {
validate: (0, _utils.assertOneOf)("script", "module"),
default: "script"
},
directives: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Directive"))),
default: []
},
body: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Statement")))
}
},
aliases: ["Scopable", "BlockParent", "Block"]
});
(0, _utils.default)("ObjectExpression", {
visitor: ["properties"],
aliases: ["Expression"],
fields: {
properties: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("ObjectMethod", "ObjectProperty", "SpreadElement")))
}
}
});
(0, _utils.default)("ObjectMethod", {
builder: ["kind", "key", "params", "body", "computed"],
fields: Object.assign({}, functionCommon, functionTypeAnnotationCommon, {
kind: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), (0, _utils.assertOneOf)("method", "get", "set")),
default: "method"
},
computed: {
validate: (0, _utils.assertValueType)("boolean"),
default: false
},
key: {
validate: function () {
var normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral");
var computed = (0, _utils.assertNodeType)("Expression");
return function (node, key, val) {
var validator = node.computed ? computed : normal;
validator(node, key, val);
};
}()
},
decorators: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator")))
},
body: {
validate: (0, _utils.assertNodeType)("BlockStatement")
}
}),
visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"],
aliases: ["UserWhitespacable", "Function", "Scopable", "BlockParent", "FunctionParent", "Method", "ObjectMember"]
});
(0, _utils.default)("ObjectProperty", {
builder: ["key", "value", "computed", "shorthand", "decorators"],
fields: {
computed: {
validate: (0, _utils.assertValueType)("boolean"),
default: false
},
key: {
validate: function () {
var normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral");
var computed = (0, _utils.assertNodeType)("Expression");
return function (node, key, val) {
var validator = node.computed ? computed : normal;
validator(node, key, val);
};
}()
},
value: {
validate: (0, _utils.assertNodeType)("Expression", "PatternLike")
},
shorthand: {
validate: (0, _utils.assertValueType)("boolean"),
default: false
},
decorators: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))),
optional: true
}
},
visitor: ["key", "value", "decorators"],
aliases: ["UserWhitespacable", "Property", "ObjectMember"]
});
(0, _utils.default)("RestElement", {
visitor: ["argument", "typeAnnotation"],
builder: ["argument"],
aliases: ["LVal", "PatternLike"],
deprecatedAlias: "RestProperty",
fields: Object.assign({}, patternLikeCommon, {
argument: {
validate: (0, _utils.assertNodeType)("LVal")
}
})
});
(0, _utils.default)("ReturnStatement", {
visitor: ["argument"],
aliases: ["Statement", "Terminatorless", "CompletionStatement"],
fields: {
argument: {
validate: (0, _utils.assertNodeType)("Expression"),
optional: true
}
}
});
(0, _utils.default)("SequenceExpression", {
visitor: ["expressions"],
fields: {
expressions: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression")))
}
},
aliases: ["Expression"]
});
(0, _utils.default)("SwitchCase", {
visitor: ["test", "consequent"],
fields: {
test: {
validate: (0, _utils.assertNodeType)("Expression"),
optional: true
},
consequent: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Statement")))
}
}
});
(0, _utils.default)("SwitchStatement", {
visitor: ["discriminant", "cases"],
aliases: ["Statement", "BlockParent", "Scopable"],
fields: {
discriminant: {
validate: (0, _utils.assertNodeType)("Expression")
},
cases: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("SwitchCase")))
}
}
});
(0, _utils.default)("ThisExpression", {
aliases: ["Expression"]
});
(0, _utils.default)("ThrowStatement", {
visitor: ["argument"],
aliases: ["Statement", "Terminatorless", "CompletionStatement"],
fields: {
argument: {
validate: (0, _utils.assertNodeType)("Expression")
}
}
});
(0, _utils.default)("TryStatement", {
visitor: ["block", "handler", "finalizer"],
aliases: ["Statement"],
fields: {
block: {
validate: (0, _utils.assertNodeType)("BlockStatement")
},
handler: {
optional: true,
validate: (0, _utils.assertNodeType)("CatchClause")
},
finalizer: {
optional: true,
validate: (0, _utils.assertNodeType)("BlockStatement")
}
}
});
(0, _utils.default)("UnaryExpression", {
builder: ["operator", "argument", "prefix"],
fields: {
prefix: {
default: true
},
argument: {
validate: (0, _utils.assertNodeType)("Expression")
},
operator: {
validate: _utils.assertOneOf.apply(void 0, _constants.UNARY_OPERATORS)
}
},
visitor: ["argument"],
aliases: ["UnaryLike", "Expression"]
});
(0, _utils.default)("UpdateExpression", {
builder: ["operator", "argument", "prefix"],
fields: {
prefix: {
default: false
},
argument: {
validate: (0, _utils.assertNodeType)("Expression")
},
operator: {
validate: _utils.assertOneOf.apply(void 0, _constants.UPDATE_OPERATORS)
}
},
visitor: ["argument"],
aliases: ["Expression"]
});
(0, _utils.default)("VariableDeclaration", {
builder: ["kind", "declarations"],
visitor: ["declarations"],
aliases: ["Statement", "Declaration"],
fields: {
declare: {
validate: (0, _utils.assertValueType)("boolean"),
optional: true
},
kind: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), (0, _utils.assertOneOf)("var", "let", "const"))
},
declarations: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("VariableDeclarator")))
}
}
});
(0, _utils.default)("VariableDeclarator", {
visitor: ["id", "init"],
fields: {
id: {
validate: (0, _utils.assertNodeType)("LVal")
},
init: {
optional: true,
validate: (0, _utils.assertNodeType)("Expression")
}
}
});
(0, _utils.default)("WhileStatement", {
visitor: ["test", "body"],
aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"],
fields: {
test: {
validate: (0, _utils.assertNodeType)("Expression")
},
body: {
validate: (0, _utils.assertNodeType)("BlockStatement", "Statement")
}
}
});
(0, _utils.default)("WithStatement", {
visitor: ["object", "body"],
aliases: ["Statement"],
fields: {
object: {
validate: (0, _utils.assertNodeType)("Expression")
},
body: {
validate: (0, _utils.assertNodeType)("BlockStatement", "Statement")
}
}
});
@@ -0,0 +1,379 @@
"use strict";
exports.__esModule = true;
exports.classMethodOrDeclareMethodCommon = exports.classMethodOrPropertyCommon = void 0;
var _utils = _interopRequireWildcard(require("./utils"));
var _core = require("./core");
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
(0, _utils.default)("AssignmentPattern", {
visitor: ["left", "right"],
builder: ["left", "right"],
aliases: ["Pattern", "PatternLike", "LVal"],
fields: Object.assign({}, _core.patternLikeCommon, {
left: {
validate: (0, _utils.assertNodeType)("Identifier", "ObjectPattern", "ArrayPattern")
},
right: {
validate: (0, _utils.assertNodeType)("Expression")
},
decorators: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator")))
}
})
});
(0, _utils.default)("ArrayPattern", {
visitor: ["elements", "typeAnnotation"],
builder: ["elements"],
aliases: ["Pattern", "PatternLike", "LVal"],
fields: Object.assign({}, _core.patternLikeCommon, {
elements: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("PatternLike")))
},
decorators: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator")))
}
})
});
(0, _utils.default)("ArrowFunctionExpression", {
builder: ["params", "body", "async"],
visitor: ["params", "body", "returnType", "typeParameters"],
aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"],
fields: Object.assign({}, _core.functionCommon, _core.functionTypeAnnotationCommon, {
expression: {
validate: (0, _utils.assertValueType)("boolean")
},
body: {
validate: (0, _utils.assertNodeType)("BlockStatement", "Expression")
}
})
});
(0, _utils.default)("ClassBody", {
visitor: ["body"],
fields: {
body: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("ClassMethod", "ClassProperty", "TSDeclareMethod", "TSIndexSignature")))
}
}
});
var classCommon = {
typeParameters: {
validate: (0, _utils.assertNodeType)("TypeParameterDeclaration", "TSTypeParameterDeclaration", "Noop"),
optional: true
},
body: {
validate: (0, _utils.assertNodeType)("ClassBody")
},
superClass: {
optional: true,
validate: (0, _utils.assertNodeType)("Expression")
},
superTypeParameters: {
validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"),
optional: true
},
implements: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("TSExpressionWithTypeArguments", "FlowClassImplements"))),
optional: true
}
};
(0, _utils.default)("ClassDeclaration", {
builder: ["id", "superClass", "body", "decorators"],
visitor: ["id", "body", "superClass", "mixins", "typeParameters", "superTypeParameters", "implements", "decorators"],
aliases: ["Scopable", "Class", "Statement", "Declaration", "Pureish"],
fields: Object.assign({}, classCommon, {
declare: {
validate: (0, _utils.assertValueType)("boolean"),
optional: true
},
abstract: {
validate: (0, _utils.assertValueType)("boolean"),
optional: true
},
id: {
validate: (0, _utils.assertNodeType)("Identifier"),
optional: true
},
decorators: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))),
optional: true
}
})
});
(0, _utils.default)("ClassExpression", {
inherits: "ClassDeclaration",
aliases: ["Scopable", "Class", "Expression", "Pureish"],
fields: Object.assign({}, classCommon, {
id: {
optional: true,
validate: (0, _utils.assertNodeType)("Identifier")
},
body: {
validate: (0, _utils.assertNodeType)("ClassBody")
},
superClass: {
optional: true,
validate: (0, _utils.assertNodeType)("Expression")
},
decorators: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))),
optional: true
}
})
});
(0, _utils.default)("ExportAllDeclaration", {
visitor: ["source"],
aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"],
fields: {
source: {
validate: (0, _utils.assertNodeType)("StringLiteral")
}
}
});
(0, _utils.default)("ExportDefaultDeclaration", {
visitor: ["declaration"],
aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"],
fields: {
declaration: {
validate: (0, _utils.assertNodeType)("FunctionDeclaration", "TSDeclareFunction", "ClassDeclaration", "Expression")
}
}
});
(0, _utils.default)("ExportNamedDeclaration", {
visitor: ["declaration", "specifiers", "source"],
aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"],
fields: {
declaration: {
validate: (0, _utils.assertNodeType)("Declaration"),
optional: true
},
specifiers: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("ExportSpecifier", "ExportDefaultSpecifier", "ExportNamespaceSpecifier")))
},
source: {
validate: (0, _utils.assertNodeType)("StringLiteral"),
optional: true
}
}
});
(0, _utils.default)("ExportSpecifier", {
visitor: ["local", "exported"],
aliases: ["ModuleSpecifier"],
fields: {
local: {
validate: (0, _utils.assertNodeType)("Identifier")
},
exported: {
validate: (0, _utils.assertNodeType)("Identifier")
}
}
});
(0, _utils.default)("ForOfStatement", {
visitor: ["left", "right", "body"],
aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"],
fields: {
left: {
validate: (0, _utils.assertNodeType)("VariableDeclaration", "LVal")
},
right: {
validate: (0, _utils.assertNodeType)("Expression")
},
body: {
validate: (0, _utils.assertNodeType)("Statement")
},
await: {
default: false,
validate: (0, _utils.assertValueType)("boolean")
}
}
});
(0, _utils.default)("ImportDeclaration", {
visitor: ["specifiers", "source"],
aliases: ["Statement", "Declaration", "ModuleDeclaration"],
fields: {
specifiers: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("ImportSpecifier", "ImportDefaultSpecifier", "ImportNamespaceSpecifier")))
},
source: {
validate: (0, _utils.assertNodeType)("StringLiteral")
}
}
});
(0, _utils.default)("ImportDefaultSpecifier", {
visitor: ["local"],
aliases: ["ModuleSpecifier"],
fields: {
local: {
validate: (0, _utils.assertNodeType)("Identifier")
}
}
});
(0, _utils.default)("ImportNamespaceSpecifier", {
visitor: ["local"],
aliases: ["ModuleSpecifier"],
fields: {
local: {
validate: (0, _utils.assertNodeType)("Identifier")
}
}
});
(0, _utils.default)("ImportSpecifier", {
visitor: ["local", "imported"],
aliases: ["ModuleSpecifier"],
fields: {
local: {
validate: (0, _utils.assertNodeType)("Identifier")
},
imported: {
validate: (0, _utils.assertNodeType)("Identifier")
},
importKind: {
validate: (0, _utils.assertOneOf)(null, "type", "typeof")
}
}
});
(0, _utils.default)("MetaProperty", {
visitor: ["meta", "property"],
aliases: ["Expression"],
fields: {
meta: {
validate: (0, _utils.assertNodeType)("Identifier")
},
property: {
validate: (0, _utils.assertNodeType)("Identifier")
}
}
});
var classMethodOrPropertyCommon = {
abstract: {
validate: (0, _utils.assertValueType)("boolean"),
optional: true
},
accessibility: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), (0, _utils.assertOneOf)("public", "private", "protected")),
optional: true
},
static: {
validate: (0, _utils.assertValueType)("boolean"),
optional: true
},
computed: {
default: false,
validate: (0, _utils.assertValueType)("boolean")
},
optional: {
validate: (0, _utils.assertValueType)("boolean"),
optional: true
},
key: {
validate: function () {
var normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral");
var computed = (0, _utils.assertNodeType)("Expression");
return function (node, key, val) {
var validator = node.computed ? computed : normal;
validator(node, key, val);
};
}()
}
};
exports.classMethodOrPropertyCommon = classMethodOrPropertyCommon;
var classMethodOrDeclareMethodCommon = Object.assign({}, _core.functionCommon, classMethodOrPropertyCommon, {
kind: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), (0, _utils.assertOneOf)("get", "set", "method", "constructor")),
default: "method"
},
access: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), (0, _utils.assertOneOf)("public", "private", "protected")),
optional: true
},
decorators: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))),
optional: true
}
});
exports.classMethodOrDeclareMethodCommon = classMethodOrDeclareMethodCommon;
(0, _utils.default)("ClassMethod", {
aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method"],
builder: ["kind", "key", "params", "body", "computed", "static"],
visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"],
fields: Object.assign({}, classMethodOrDeclareMethodCommon, _core.functionTypeAnnotationCommon, {
body: {
validate: (0, _utils.assertNodeType)("BlockStatement")
}
})
});
(0, _utils.default)("ObjectPattern", {
visitor: ["properties", "typeAnnotation"],
builder: ["properties"],
aliases: ["Pattern", "PatternLike", "LVal"],
fields: Object.assign({}, _core.patternLikeCommon, {
properties: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("RestElement", "ObjectProperty")))
}
})
});
(0, _utils.default)("SpreadElement", {
visitor: ["argument"],
aliases: ["UnaryLike"],
deprecatedAlias: "SpreadProperty",
fields: {
argument: {
validate: (0, _utils.assertNodeType)("Expression")
}
}
});
(0, _utils.default)("Super", {
aliases: ["Expression"]
});
(0, _utils.default)("TaggedTemplateExpression", {
visitor: ["tag", "quasi"],
aliases: ["Expression"],
fields: {
tag: {
validate: (0, _utils.assertNodeType)("Expression")
},
quasi: {
validate: (0, _utils.assertNodeType)("TemplateLiteral")
}
}
});
(0, _utils.default)("TemplateElement", {
builder: ["value", "tail"],
fields: {
value: {},
tail: {
validate: (0, _utils.assertValueType)("boolean"),
default: false
}
}
});
(0, _utils.default)("TemplateLiteral", {
visitor: ["quasis", "expressions"],
aliases: ["Expression", "Literal"],
fields: {
quasis: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("TemplateElement")))
},
expressions: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression")))
}
}
});
(0, _utils.default)("YieldExpression", {
builder: ["argument", "delegate"],
visitor: ["argument"],
aliases: ["Expression", "Terminatorless"],
fields: {
delegate: {
validate: (0, _utils.assertValueType)("boolean"),
default: false
},
argument: {
optional: true,
validate: (0, _utils.assertNodeType)("Expression")
}
}
});
@@ -0,0 +1,84 @@
"use strict";
var _utils = _interopRequireWildcard(require("./utils"));
var _es = require("./es2015");
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
(0, _utils.default)("AwaitExpression", {
builder: ["argument"],
visitor: ["argument"],
aliases: ["Expression", "Terminatorless"],
fields: {
argument: {
validate: (0, _utils.assertNodeType)("Expression")
}
}
});
(0, _utils.default)("BindExpression", {
visitor: ["object", "callee"],
aliases: ["Expression"],
fields: {}
});
(0, _utils.default)("ClassProperty", {
visitor: ["key", "value", "typeAnnotation", "decorators"],
builder: ["key", "value", "typeAnnotation", "decorators", "computed"],
aliases: ["Property"],
fields: Object.assign({}, _es.classMethodOrPropertyCommon, {
value: {
validate: (0, _utils.assertNodeType)("Expression"),
optional: true
},
typeAnnotation: {
validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"),
optional: true
},
decorators: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))),
optional: true
},
readonly: {
validate: (0, _utils.assertValueType)("boolean"),
optional: true
}
})
});
(0, _utils.default)("Import", {
aliases: ["Expression"]
});
(0, _utils.default)("Decorator", {
visitor: ["expression"],
fields: {
expression: {
validate: (0, _utils.assertNodeType)("Expression")
}
}
});
(0, _utils.default)("DoExpression", {
visitor: ["body"],
aliases: ["Expression"],
fields: {
body: {
validate: (0, _utils.assertNodeType)("BlockStatement")
}
}
});
(0, _utils.default)("ExportDefaultSpecifier", {
visitor: ["exported"],
aliases: ["ModuleSpecifier"],
fields: {
exported: {
validate: (0, _utils.assertNodeType)("Identifier")
}
}
});
(0, _utils.default)("ExportNamespaceSpecifier", {
visitor: ["exported"],
aliases: ["ModuleSpecifier"],
fields: {
exported: {
validate: (0, _utils.assertNodeType)("Identifier")
}
}
});
@@ -0,0 +1,263 @@
"use strict";
var _utils = _interopRequireWildcard(require("./utils"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
(0, _utils.default)("AnyTypeAnnotation", {
aliases: ["Flow", "FlowBaseAnnotation"],
fields: {}
});
(0, _utils.default)("ArrayTypeAnnotation", {
visitor: ["elementType"],
aliases: ["Flow"],
fields: {}
});
(0, _utils.default)("BooleanTypeAnnotation", {
aliases: ["Flow", "FlowBaseAnnotation"],
fields: {}
});
(0, _utils.default)("BooleanLiteralTypeAnnotation", {
aliases: ["Flow"],
fields: {}
});
(0, _utils.default)("NullLiteralTypeAnnotation", {
aliases: ["Flow", "FlowBaseAnnotation"],
fields: {}
});
(0, _utils.default)("ClassImplements", {
visitor: ["id", "typeParameters"],
aliases: ["Flow"],
fields: {}
});
(0, _utils.default)("DeclareClass", {
visitor: ["id", "typeParameters", "extends", "body"],
aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
fields: {}
});
(0, _utils.default)("DeclareFunction", {
visitor: ["id"],
aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
fields: {}
});
(0, _utils.default)("DeclareInterface", {
visitor: ["id", "typeParameters", "extends", "body"],
aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
fields: {}
});
(0, _utils.default)("DeclareModule", {
visitor: ["id", "body"],
aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
fields: {}
});
(0, _utils.default)("DeclareModuleExports", {
visitor: ["typeAnnotation"],
aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
fields: {}
});
(0, _utils.default)("DeclareTypeAlias", {
visitor: ["id", "typeParameters", "right"],
aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
fields: {}
});
(0, _utils.default)("DeclareOpaqueType", {
visitor: ["id", "typeParameters", "supertype"],
aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
fields: {}
});
(0, _utils.default)("DeclareVariable", {
visitor: ["id"],
aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
fields: {}
});
(0, _utils.default)("DeclareExportDeclaration", {
visitor: ["declaration", "specifiers", "source"],
aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
fields: {}
});
(0, _utils.default)("DeclareExportAllDeclaration", {
visitor: ["source"],
aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
fields: {}
});
(0, _utils.default)("DeclaredPredicate", {
visitor: ["value"],
aliases: ["Flow", "FlowPredicate"],
fields: {}
});
(0, _utils.default)("ExistsTypeAnnotation", {
aliases: ["Flow"]
});
(0, _utils.default)("FunctionTypeAnnotation", {
visitor: ["typeParameters", "params", "rest", "returnType"],
aliases: ["Flow"],
fields: {}
});
(0, _utils.default)("FunctionTypeParam", {
visitor: ["name", "typeAnnotation"],
aliases: ["Flow"],
fields: {}
});
(0, _utils.default)("GenericTypeAnnotation", {
visitor: ["id", "typeParameters"],
aliases: ["Flow"],
fields: {}
});
(0, _utils.default)("InferredPredicate", {
aliases: ["Flow", "FlowPredicate"],
fields: {}
});
(0, _utils.default)("InterfaceExtends", {
visitor: ["id", "typeParameters"],
aliases: ["Flow"],
fields: {}
});
(0, _utils.default)("InterfaceDeclaration", {
visitor: ["id", "typeParameters", "extends", "body"],
aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
fields: {}
});
(0, _utils.default)("IntersectionTypeAnnotation", {
visitor: ["types"],
aliases: ["Flow"],
fields: {}
});
(0, _utils.default)("MixedTypeAnnotation", {
aliases: ["Flow", "FlowBaseAnnotation"]
});
(0, _utils.default)("EmptyTypeAnnotation", {
aliases: ["Flow", "FlowBaseAnnotation"]
});
(0, _utils.default)("NullableTypeAnnotation", {
visitor: ["typeAnnotation"],
aliases: ["Flow"],
fields: {}
});
(0, _utils.default)("NumberLiteralTypeAnnotation", {
aliases: ["Flow"],
fields: {}
});
(0, _utils.default)("NumberTypeAnnotation", {
aliases: ["Flow", "FlowBaseAnnotation"],
fields: {}
});
(0, _utils.default)("ObjectTypeAnnotation", {
visitor: ["properties", "indexers", "callProperties"],
aliases: ["Flow"],
fields: {}
});
(0, _utils.default)("ObjectTypeCallProperty", {
visitor: ["value"],
aliases: ["Flow", "UserWhitespacable"],
fields: {}
});
(0, _utils.default)("ObjectTypeIndexer", {
visitor: ["id", "key", "value"],
aliases: ["Flow", "UserWhitespacable"],
fields: {}
});
(0, _utils.default)("ObjectTypeProperty", {
visitor: ["key", "value"],
aliases: ["Flow", "UserWhitespacable"],
fields: {}
});
(0, _utils.default)("ObjectTypeSpreadProperty", {
visitor: ["argument"],
aliases: ["Flow", "UserWhitespacable"],
fields: {}
});
(0, _utils.default)("OpaqueType", {
visitor: ["id", "typeParameters", "supertype", "impltype"],
aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
fields: {}
});
(0, _utils.default)("QualifiedTypeIdentifier", {
visitor: ["id", "qualification"],
aliases: ["Flow"],
fields: {}
});
(0, _utils.default)("StringLiteralTypeAnnotation", {
aliases: ["Flow"],
fields: {}
});
(0, _utils.default)("StringTypeAnnotation", {
aliases: ["Flow", "FlowBaseAnnotation"],
fields: {}
});
(0, _utils.default)("ThisTypeAnnotation", {
aliases: ["Flow", "FlowBaseAnnotation"],
fields: {}
});
(0, _utils.default)("TupleTypeAnnotation", {
visitor: ["types"],
aliases: ["Flow"],
fields: {}
});
(0, _utils.default)("TypeofTypeAnnotation", {
visitor: ["argument"],
aliases: ["Flow"],
fields: {}
});
(0, _utils.default)("TypeAlias", {
visitor: ["id", "typeParameters", "right"],
aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
fields: {}
});
(0, _utils.default)("TypeAnnotation", {
aliases: ["Flow"],
visitor: ["typeAnnotation"],
fields: {
typeAnnotation: {
validate: (0, _utils.assertNodeType)("Flow")
}
}
});
(0, _utils.default)("TypeCastExpression", {
visitor: ["expression", "typeAnnotation"],
aliases: ["Flow", "ExpressionWrapper", "Expression"],
fields: {}
});
(0, _utils.default)("TypeParameter", {
aliases: ["Flow"],
visitor: ["bound", "default"],
fields: {
name: {
validate: (0, _utils.assertValueType)("string")
},
bound: {
validate: (0, _utils.assertNodeType)("TypeAnnotation"),
optional: true
},
default: {
validate: (0, _utils.assertNodeType)("Flow"),
optional: true
}
}
});
(0, _utils.default)("TypeParameterDeclaration", {
aliases: ["Flow"],
visitor: ["params"],
fields: {
params: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("TypeParameter")))
}
}
});
(0, _utils.default)("TypeParameterInstantiation", {
aliases: ["Flow"],
visitor: ["params"],
fields: {
params: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Flow")))
}
}
});
(0, _utils.default)("UnionTypeAnnotation", {
visitor: ["types"],
aliases: ["Flow"],
fields: {}
});
(0, _utils.default)("VoidTypeAnnotation", {
aliases: ["Flow", "FlowBaseAnnotation"],
fields: {}
});
@@ -0,0 +1,40 @@
"use strict";
exports.__esModule = true;
exports.TYPES = void 0;
var _toFastProperties = _interopRequireDefault(require("to-fast-properties"));
require("./core");
require("./es2015");
require("./flow");
require("./jsx");
require("./misc");
require("./experimental");
require("./typescript");
var _utils = require("./utils");
exports.VISITOR_KEYS = _utils.VISITOR_KEYS;
exports.ALIAS_KEYS = _utils.ALIAS_KEYS;
exports.FLIPPED_ALIAS_KEYS = _utils.FLIPPED_ALIAS_KEYS;
exports.NODE_FIELDS = _utils.NODE_FIELDS;
exports.BUILDER_KEYS = _utils.BUILDER_KEYS;
exports.DEPRECATED_KEYS = _utils.DEPRECATED_KEYS;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
(0, _toFastProperties.default)(_utils.VISITOR_KEYS);
(0, _toFastProperties.default)(_utils.ALIAS_KEYS);
(0, _toFastProperties.default)(_utils.FLIPPED_ALIAS_KEYS);
(0, _toFastProperties.default)(_utils.NODE_FIELDS);
(0, _toFastProperties.default)(_utils.BUILDER_KEYS);
(0, _toFastProperties.default)(_utils.DEPRECATED_KEYS);
var TYPES = Object.keys(_utils.VISITOR_KEYS).concat(Object.keys(_utils.FLIPPED_ALIAS_KEYS)).concat(Object.keys(_utils.DEPRECATED_KEYS));
exports.TYPES = TYPES;
Loaded 100 of 1318 files, more files were not shown because too many files have changed in this diff. Show more