Commit ac419aba authored by Cholgrrr's avatar Cholgrrr
Browse files

.gitignore, settings.json und 14061 weitere dateien aktualisiert...

parent ed14b8b4
# @babel/plugin-transform-block-scoping
> Compile ES2015 block scoping (const and let) to ES5
See our website [@babel/plugin-transform-block-scoping](https://babeljs.io/docs/en/next/babel-plugin-transform-block-scoping.html) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/plugin-transform-block-scoping
```
or using yarn:
```sh
yarn add @babel/plugin-transform-block-scoping --dev
```
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _helperPluginUtils = require("@babel/helper-plugin-utils");
var _tdz = require("./tdz");
var _values = _interopRequireDefault(require("lodash/values"));
var _extend = _interopRequireDefault(require("lodash/extend"));
var _core = require("@babel/core");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const DONE = new WeakSet();
var _default = (0, _helperPluginUtils.declare)((api, opts) => {
api.assertVersion(7);
const {
throwIfClosureRequired = false,
tdz: tdzEnabled = false
} = opts;
if (typeof throwIfClosureRequired !== "boolean") {
throw new Error(`.throwIfClosureRequired must be a boolean, or undefined`);
}
if (typeof tdzEnabled !== "boolean") {
throw new Error(`.tdz must be a boolean, or undefined`);
}
return {
name: "transform-block-scoping",
visitor: {
VariableDeclaration(path) {
const {
node,
parent,
scope
} = path;
if (!isBlockScoped(node)) return;
convertBlockScopedToVar(path, null, parent, scope, true);
if (node._tdzThis) {
const nodes = [node];
for (let i = 0; i < node.declarations.length; i++) {
const decl = node.declarations[i];
const assign = _core.types.assignmentExpression("=", decl.id, decl.init || scope.buildUndefinedNode());
assign._ignoreBlockScopingTDZ = true;
nodes.push(_core.types.expressionStatement(assign));
decl.init = this.addHelper("temporalUndefined");
}
node._blockHoist = 2;
if (path.isCompletionRecord()) {
nodes.push(_core.types.expressionStatement(scope.buildUndefinedNode()));
}
path.replaceWithMultiple(nodes);
}
},
Loop(path, state) {
const {
parent,
scope
} = path;
path.ensureBlock();
const blockScoping = new BlockScoping(path, path.get("body"), parent, scope, throwIfClosureRequired, tdzEnabled, state);
const replace = blockScoping.run();
if (replace) path.replaceWith(replace);
},
CatchClause(path, state) {
const {
parent,
scope
} = path;
const blockScoping = new BlockScoping(null, path.get("body"), parent, scope, throwIfClosureRequired, tdzEnabled, state);
blockScoping.run();
},
"BlockStatement|SwitchStatement|Program"(path, state) {
if (!ignoreBlock(path)) {
const blockScoping = new BlockScoping(null, path, path.parent, path.scope, throwIfClosureRequired, tdzEnabled, state);
blockScoping.run();
}
}
}
};
});
exports.default = _default;
function ignoreBlock(path) {
return _core.types.isLoop(path.parent) || _core.types.isCatchClause(path.parent);
}
const buildRetCheck = (0, _core.template)(`
if (typeof RETURN === "object") return RETURN.v;
`);
function isBlockScoped(node) {
if (!_core.types.isVariableDeclaration(node)) return false;
if (node[_core.types.BLOCK_SCOPED_SYMBOL]) return true;
if (node.kind !== "let" && node.kind !== "const") return false;
return true;
}
function isInLoop(path) {
const loopOrFunctionParent = path.find(path => path.isLoop() || path.isFunction());
return loopOrFunctionParent && loopOrFunctionParent.isLoop();
}
function convertBlockScopedToVar(path, node, parent, scope, moveBindingsToParent = false) {
if (!node) {
node = path.node;
}
if (isInLoop(path) && !_core.types.isFor(parent)) {
for (let i = 0; i < node.declarations.length; i++) {
const declar = node.declarations[i];
declar.init = declar.init || scope.buildUndefinedNode();
}
}
node[_core.types.BLOCK_SCOPED_SYMBOL] = true;
node.kind = "var";
if (moveBindingsToParent) {
const parentScope = scope.getFunctionParent() || scope.getProgramParent();
for (const name of Object.keys(path.getBindingIdentifiers())) {
const binding = scope.getOwnBinding(name);
if (binding) binding.kind = "var";
scope.moveBindingTo(name, parentScope);
}
}
}
function isVar(node) {
return _core.types.isVariableDeclaration(node, {
kind: "var"
}) && !isBlockScoped(node);
}
const letReferenceBlockVisitor = _core.traverse.visitors.merge([{
Loop: {
enter(path, state) {
state.loopDepth++;
},
exit(path, state) {
state.loopDepth--;
}
},
Function(path, state) {
if (state.loopDepth > 0) {
path.traverse(letReferenceFunctionVisitor, state);
} else {
path.traverse(_tdz.visitor, state);
}
return path.skip();
}
}, _tdz.visitor]);
const letReferenceFunctionVisitor = _core.traverse.visitors.merge([{
ReferencedIdentifier(path, state) {
const ref = state.letReferences[path.node.name];
if (!ref) return;
const localBinding = path.scope.getBindingIdentifier(path.node.name);
if (localBinding && localBinding !== ref) return;
state.closurify = true;
}
}, _tdz.visitor]);
const hoistVarDeclarationsVisitor = {
enter(path, self) {
const {
node,
parent
} = path;
if (path.isForStatement()) {
if (isVar(node.init, node)) {
const nodes = self.pushDeclar(node.init);
if (nodes.length === 1) {
node.init = nodes[0];
} else {
node.init = _core.types.sequenceExpression(nodes);
}
}
} else if (path.isFor()) {
if (isVar(node.left, node)) {
self.pushDeclar(node.left);
node.left = node.left.declarations[0].id;
}
} else if (isVar(node, parent)) {
path.replaceWithMultiple(self.pushDeclar(node).map(expr => _core.types.expressionStatement(expr)));
} else if (path.isFunction()) {
return path.skip();
}
}
};
const loopLabelVisitor = {
LabeledStatement({
node
}, state) {
state.innerLabels.push(node.label.name);
}
};
const continuationVisitor = {
enter(path, state) {
if (path.isAssignmentExpression() || path.isUpdateExpression()) {
for (const name of Object.keys(path.getBindingIdentifiers())) {
if (state.outsideReferences[name] !== path.scope.getBindingIdentifier(name)) {
continue;
}
state.reassignments[name] = true;
}
} else if (path.isReturnStatement()) {
state.returnStatements.push(path);
}
}
};
function loopNodeTo(node) {
if (_core.types.isBreakStatement(node)) {
return "break";
} else if (_core.types.isContinueStatement(node)) {
return "continue";
}
}
const loopVisitor = {
Loop(path, state) {
const oldIgnoreLabeless = state.ignoreLabeless;
state.ignoreLabeless = true;
path.traverse(loopVisitor, state);
state.ignoreLabeless = oldIgnoreLabeless;
path.skip();
},
Function(path) {
path.skip();
},
SwitchCase(path, state) {
const oldInSwitchCase = state.inSwitchCase;
state.inSwitchCase = true;
path.traverse(loopVisitor, state);
state.inSwitchCase = oldInSwitchCase;
path.skip();
},
"BreakStatement|ContinueStatement|ReturnStatement"(path, state) {
const {
node,
scope
} = path;
if (node[this.LOOP_IGNORE]) return;
let replace;
let loopText = loopNodeTo(node);
if (loopText) {
if (node.label) {
if (state.innerLabels.indexOf(node.label.name) >= 0) {
return;
}
loopText = `${loopText}|${node.label.name}`;
} else {
if (state.ignoreLabeless) return;
if (_core.types.isBreakStatement(node) && state.inSwitchCase) return;
}
state.hasBreakContinue = true;
state.map[loopText] = node;
replace = _core.types.stringLiteral(loopText);
}
if (path.isReturnStatement()) {
state.hasReturn = true;
replace = _core.types.objectExpression([_core.types.objectProperty(_core.types.identifier("v"), node.argument || scope.buildUndefinedNode())]);
}
if (replace) {
replace = _core.types.returnStatement(replace);
replace[this.LOOP_IGNORE] = true;
path.skip();
path.replaceWith(_core.types.inherits(replace, node));
}
}
};
class BlockScoping {
constructor(loopPath, blockPath, parent, scope, throwIfClosureRequired, tdzEnabled, state) {
this.parent = parent;
this.scope = scope;
this.state = state;
this.throwIfClosureRequired = throwIfClosureRequired;
this.tdzEnabled = tdzEnabled;
this.blockPath = blockPath;
this.block = blockPath.node;
this.outsideLetReferences = Object.create(null);
this.hasLetReferences = false;
this.letReferences = Object.create(null);
this.body = [];
if (loopPath) {
this.loopParent = loopPath.parent;
this.loopLabel = _core.types.isLabeledStatement(this.loopParent) && this.loopParent.label;
this.loopPath = loopPath;
this.loop = loopPath.node;
}
}
run() {
const block = this.block;
if (DONE.has(block)) return;
DONE.add(block);
const needsClosure = this.getLetReferences();
this.checkConstants();
if (_core.types.isFunction(this.parent) || _core.types.isProgram(this.block)) {
this.updateScopeInfo();
return;
}
if (!this.hasLetReferences) return;
if (needsClosure) {
this.wrapClosure();
} else {
this.remap();
}
this.updateScopeInfo(needsClosure);
if (this.loopLabel && !_core.types.isLabeledStatement(this.loopParent)) {
return _core.types.labeledStatement(this.loopLabel, this.loop);
}
}
checkConstants() {
const scope = this.scope;
const state = this.state;
for (const name of Object.keys(scope.bindings)) {
const binding = scope.bindings[name];
if (binding.kind !== "const") continue;
for (const violation of binding.constantViolations) {
const readOnlyError = state.addHelper("readOnlyError");
const throwNode = _core.types.callExpression(readOnlyError, [_core.types.stringLiteral(name)]);
if (violation.isAssignmentExpression()) {
violation.get("right").replaceWith(_core.types.sequenceExpression([throwNode, violation.get("right").node]));
} else if (violation.isUpdateExpression()) {
violation.replaceWith(_core.types.sequenceExpression([throwNode, violation.node]));
} else if (violation.isForXStatement()) {
violation.ensureBlock();
violation.node.body.body.unshift(_core.types.expressionStatement(throwNode));
}
}
}
}
updateScopeInfo(wrappedInClosure) {
const blockScope = this.blockPath.scope;
const parentScope = blockScope.getFunctionParent() || blockScope.getProgramParent();
const letRefs = this.letReferences;
for (const key of Object.keys(letRefs)) {
const ref = letRefs[key];
const binding = blockScope.getBinding(ref.name);
if (!binding) continue;
if (binding.kind === "let" || binding.kind === "const") {
binding.kind = "var";
if (wrappedInClosure) {
if (blockScope.hasOwnBinding(ref.name)) {
blockScope.removeBinding(ref.name);
}
} else {
blockScope.moveBindingTo(ref.name, parentScope);
}
}
}
}
remap() {
const letRefs = this.letReferences;
const outsideLetRefs = this.outsideLetReferences;
const scope = this.scope;
const blockPathScope = this.blockPath.scope;
for (const key of Object.keys(letRefs)) {
const ref = letRefs[key];
if (scope.parentHasBinding(key) || scope.hasGlobal(key)) {
if (scope.hasOwnBinding(key)) {
scope.rename(ref.name);
}
if (blockPathScope.hasOwnBinding(key)) {
blockPathScope.rename(ref.name);
}
}
}
for (const key of Object.keys(outsideLetRefs)) {
const ref = letRefs[key];
if (isInLoop(this.blockPath) && blockPathScope.hasOwnBinding(key)) {
blockPathScope.rename(ref.name);
}
}
}
wrapClosure() {
if (this.throwIfClosureRequired) {
throw this.blockPath.buildCodeFrameError("Compiling let/const in this block would add a closure " + "(throwIfClosureRequired).");
}
const block = this.block;
const outsideRefs = this.outsideLetReferences;
if (this.loop) {
for (const name of Object.keys(outsideRefs)) {
const id = outsideRefs[name];
if (this.scope.hasGlobal(id.name) || this.scope.parentHasBinding(id.name)) {
delete outsideRefs[id.name];
delete this.letReferences[id.name];
this.scope.rename(id.name);
this.letReferences[id.name] = id;
outsideRefs[id.name] = id;
}
}
}
this.has = this.checkLoop();
this.hoistVarDeclarations();
const args = (0, _values.default)(outsideRefs).map(id => _core.types.cloneNode(id));
const params = args.map(id => _core.types.cloneNode(id));
const isSwitch = this.blockPath.isSwitchStatement();
const fn = _core.types.functionExpression(null, params, _core.types.blockStatement(isSwitch ? [block] : block.body));
this.addContinuations(fn);
let call = _core.types.callExpression(_core.types.nullLiteral(), args);
let basePath = ".callee";
const hasYield = _core.traverse.hasType(fn.body, "YieldExpression", _core.types.FUNCTION_TYPES);
if (hasYield) {
fn.generator = true;
call = _core.types.yieldExpression(call, true);
basePath = ".argument" + basePath;
}
const hasAsync = _core.traverse.hasType(fn.body, "AwaitExpression", _core.types.FUNCTION_TYPES);
if (hasAsync) {
fn.async = true;
call = _core.types.awaitExpression(call);
basePath = ".argument" + basePath;
}
let placeholderPath;
let index;
if (this.has.hasReturn || this.has.hasBreakContinue) {
const ret = this.scope.generateUid("ret");
this.body.push(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(_core.types.identifier(ret), call)]));
placeholderPath = "declarations.0.init" + basePath;
index = this.body.length - 1;
this.buildHas(ret);
} else {
this.body.push(_core.types.expressionStatement(call));
placeholderPath = "expression" + basePath;
index = this.body.length - 1;
}
let callPath;
if (isSwitch) {
const {
parentPath,
listKey,
key
} = this.blockPath;
this.blockPath.replaceWithMultiple(this.body);
callPath = parentPath.get(listKey)[key + index];
} else {
block.body = this.body;
callPath = this.blockPath.get("body")[index];
}
const placeholder = callPath.get(placeholderPath);
let fnPath;
if (this.loop) {
const loopId = this.scope.generateUid("loop");
const p = this.loopPath.insertBefore(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(_core.types.identifier(loopId), fn)]));
placeholder.replaceWith(_core.types.identifier(loopId));
fnPath = p[0].get("declarations.0.init");
} else {
placeholder.replaceWith(fn);
fnPath = placeholder;
}
fnPath.unwrapFunctionEnvironment();
}
addContinuations(fn) {
const state = {
reassignments: {},
returnStatements: [],
outsideReferences: this.outsideLetReferences
};
this.scope.traverse(fn, continuationVisitor, state);
for (let i = 0; i < fn.params.length; i++) {
const param = fn.params[i];
if (!state.reassignments[param.name]) continue;
const paramName = param.name;
const newParamName = this.scope.generateUid(param.name);
fn.params[i] = _core.types.identifier(newParamName);
this.scope.rename(paramName, newParamName, fn);
state.returnStatements.forEach(returnStatement => {
returnStatement.insertBefore(_core.types.expressionStatement(_core.types.assignmentExpression("=", _core.types.identifier(paramName), _core.types.identifier(newParamName))));
});
fn.body.body.push(_core.types.expressionStatement(_core.types.assignmentExpression("=", _core.types.identifier(paramName), _core.types.identifier(newParamName))));
}
}
getLetReferences() {
const block = this.block;
let declarators = [];
if (this.loop) {
const init = this.loop.left || this.loop.init;
if (isBlockScoped(init)) {
declarators.push(init);
(0, _extend.default)(this.outsideLetReferences, _core.types.getBindingIdentifiers(init));
}
}
const addDeclarationsFromChild = (path, node) => {
node = node || path.node;
if (_core.types.isClassDeclaration(node) || _core.types.isFunctionDeclaration(node) || isBlockScoped(node)) {
if (isBlockScoped(node)) {
convertBlockScopedToVar(path, node, block, this.scope);
}
declarators = declarators.concat(node.declarations || node);
}
if (_core.types.isLabeledStatement(node)) {
addDeclarationsFromChild(path.get("body"), node.body);
}
};
if (block.body) {
const declarPaths = this.blockPath.get("body");
for (let i = 0; i < block.body.length; i++) {
addDeclarationsFromChild(declarPaths[i]);
}
}
if (block.cases) {
const declarPaths = this.blockPath.get("cases");
for (let i = 0; i < block.cases.length; i++) {
const consequents = block.cases[i].consequent;
for (let j = 0; j < consequents.length; j++) {
const declar = consequents[j];
addDeclarationsFromChild(declarPaths[i], declar);
}
}
}
for (let i = 0; i < declarators.length; i++) {
const declar = declarators[i];
const keys = _core.types.getBindingIdentifiers(declar, false, true);
(0, _extend.default)(this.letReferences, keys);
this.hasLetReferences = true;
}
if (!this.hasLetReferences) return;
const state = {
letReferences: this.letReferences,
closurify: false,
loopDepth: 0,
tdzEnabled: this.tdzEnabled,
addHelper: name => this.state.addHelper(name)
};
if (isInLoop(this.blockPath)) {
state.loopDepth++;
}
this.blockPath.traverse(letReferenceBlockVisitor, state);
return state.closurify;
}
checkLoop() {
const state = {
hasBreakContinue: false,
ignoreLabeless: false,
inSwitchCase: false,
innerLabels: [],
hasReturn: false,
isLoop: !!this.loop,
map: {},
LOOP_IGNORE: Symbol()
};
this.blockPath.traverse(loopLabelVisitor, state);
this.blockPath.traverse(loopVisitor, state);
return state;
}
hoistVarDeclarations() {
this.blockPath.traverse(hoistVarDeclarationsVisitor, this);
}
pushDeclar(node) {
const declars = [];
const names = _core.types.getBindingIdentifiers(node);
for (const name of Object.keys(names)) {
declars.push(_core.types.variableDeclarator(names[name]));
}
this.body.push(_core.types.variableDeclaration(node.kind, declars));
const replace = [];
for (let i = 0; i < node.declarations.length; i++) {
const declar = node.declarations[i];
if (!declar.init) continue;
const expr = _core.types.assignmentExpression("=", _core.types.cloneNode(declar.id), _core.types.cloneNode(declar.init));
replace.push(_core.types.inherits(expr, declar));
}
return replace;
}
buildHas(ret) {
const body = this.body;
let retCheck;
const has = this.has;
const cases = [];
if (has.hasReturn) {
retCheck = buildRetCheck({
RETURN: _core.types.identifier(ret)
});
}
if (has.hasBreakContinue) {
for (const key of Object.keys(has.map)) {
cases.push(_core.types.switchCase(_core.types.stringLiteral(key), [has.map[key]]));
}
if (has.hasReturn) {
cases.push(_core.types.switchCase(null, [retCheck]));
}
if (cases.length === 1) {
const single = cases[0];
body.push(_core.types.ifStatement(_core.types.binaryExpression("===", _core.types.identifier(ret), single.test), single.consequent[0]));
} else {
if (this.loop) {
for (let i = 0; i < cases.length; i++) {
const caseConsequent = cases[i].consequent[0];
if (_core.types.isBreakStatement(caseConsequent) && !caseConsequent.label) {
if (!this.loopLabel) {
this.loopLabel = this.scope.generateUidIdentifier("loop");
}
caseConsequent.label = _core.types.cloneNode(this.loopLabel);
}
}
}
body.push(_core.types.switchStatement(_core.types.identifier(ret), cases));
}
} else {
if (has.hasReturn) {
body.push(retCheck);
}
}
}
}
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.visitor = void 0;
var _core = require("@babel/core");
function getTDZStatus(refPath, bindingPath) {
const executionStatus = bindingPath._guessExecutionStatusRelativeTo(refPath);
if (executionStatus === "before") {
return "outside";
} else if (executionStatus === "after") {
return "inside";
} else {
return "maybe";
}
}
function buildTDZAssert(node, state) {
return _core.types.callExpression(state.addHelper("temporalRef"), [node, _core.types.stringLiteral(node.name)]);
}
function isReference(node, scope, state) {
const declared = state.letReferences[node.name];
if (!declared) return false;
return scope.getBindingIdentifier(node.name) === declared;
}
const visitor = {
ReferencedIdentifier(path, state) {
if (!state.tdzEnabled) return;
const {
node,
parent,
scope
} = path;
if (path.parentPath.isFor({
left: node
})) return;
if (!isReference(node, scope, state)) return;
const bindingPath = scope.getBinding(node.name).path;
if (bindingPath.isFunctionDeclaration()) return;
const status = getTDZStatus(path, bindingPath);
if (status === "outside") return;
if (status === "maybe") {
const assert = buildTDZAssert(node, state);
bindingPath.parent._tdzThis = true;
path.skip();
if (path.parentPath.isUpdateExpression()) {
if (parent._ignoreBlockScopingTDZ) return;
path.parentPath.replaceWith(_core.types.sequenceExpression([assert, parent]));
} else {
path.replaceWith(assert);
}
} else if (status === "inside") {
path.replaceWith(_core.template.ast`${state.addHelper("tdz")}("${node.name}")`);
}
},
AssignmentExpression: {
exit(path, state) {
if (!state.tdzEnabled) return;
const {
node
} = path;
if (node._ignoreBlockScopingTDZ) return;
const nodes = [];
const ids = path.getBindingIdentifiers();
for (const name of Object.keys(ids)) {
const id = ids[name];
if (isReference(id, path.scope, state)) {
nodes.push(id);
}
}
if (nodes.length) {
node._ignoreBlockScopingTDZ = true;
nodes.push(node);
path.replaceWithMultiple(nodes.map(n => _core.types.expressionStatement(n)));
}
}
}
};
exports.visitor = visitor;
\ No newline at end of file
{
"name": "@babel/plugin-transform-block-scoping",
"version": "7.6.3",
"description": "Compile ES2015 block scoping (const and let) to ES5",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-block-scoping",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"main": "lib/index.js",
"dependencies": {
"@babel/helper-plugin-utils": "^7.0.0",
"lodash": "^4.17.13"
},
"keywords": [
"babel-plugin"
],
"peerDependencies": {
"@babel/core": "^7.0.0-0"
},
"devDependencies": {
"@babel/core": "^7.6.3",
"@babel/helper-plugin-test-runner": "^7.0.0"
},
"gitHead": "d329156ebc17da01382acb83e212cb4328534ebc"
}
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# @babel/plugin-transform-classes
> Compile ES2015 classes to ES5
See our website [@babel/plugin-transform-classes](https://babeljs.io/docs/en/next/babel-plugin-transform-classes.html) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/plugin-transform-classes
```
or using yarn:
```sh
yarn add @babel/plugin-transform-classes --dev
```
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _helperPluginUtils = require("@babel/helper-plugin-utils");
var _helperAnnotateAsPure = _interopRequireDefault(require("@babel/helper-annotate-as-pure"));
var _helperFunctionName = _interopRequireDefault(require("@babel/helper-function-name"));
var _helperSplitExportDeclaration = _interopRequireDefault(require("@babel/helper-split-export-declaration"));
var _core = require("@babel/core");
var _globals = _interopRequireDefault(require("globals"));
var _transformClass = _interopRequireDefault(require("./transformClass"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const getBuiltinClasses = category => Object.keys(_globals.default[category]).filter(name => /^[A-Z]/.test(name));
const builtinClasses = new Set([...getBuiltinClasses("builtin"), ...getBuiltinClasses("browser")]);
var _default = (0, _helperPluginUtils.declare)((api, options) => {
api.assertVersion(7);
const {
loose
} = options;
const VISITED = Symbol();
return {
name: "transform-classes",
visitor: {
ExportDefaultDeclaration(path) {
if (!path.get("declaration").isClassDeclaration()) return;
(0, _helperSplitExportDeclaration.default)(path);
},
ClassDeclaration(path) {
const {
node
} = path;
const ref = node.id || path.scope.generateUidIdentifier("class");
path.replaceWith(_core.types.variableDeclaration("let", [_core.types.variableDeclarator(ref, _core.types.toExpression(node))]));
},
ClassExpression(path, state) {
const {
node
} = path;
if (node[VISITED]) return;
const inferred = (0, _helperFunctionName.default)(path);
if (inferred && inferred !== node) {
path.replaceWith(inferred);
return;
}
node[VISITED] = true;
path.replaceWith((0, _transformClass.default)(path, state.file, builtinClasses, loose));
if (path.isCallExpression()) {
(0, _helperAnnotateAsPure.default)(path);
if (path.get("callee").isArrowFunctionExpression()) {
path.get("callee").arrowFunctionToExpression();
}
}
}
}
};
});
exports.default = _default;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = transformClass;
var _helperFunctionName = _interopRequireDefault(require("@babel/helper-function-name"));
var _helperReplaceSupers = _interopRequireWildcard(require("@babel/helper-replace-supers"));
var _helperOptimiseCallExpression = _interopRequireDefault(require("@babel/helper-optimise-call-expression"));
var defineMap = _interopRequireWildcard(require("@babel/helper-define-map"));
var _core = require("@babel/core");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function buildConstructor(classRef, constructorBody, node) {
const func = _core.types.functionDeclaration(_core.types.cloneNode(classRef), [], constructorBody);
_core.types.inherits(func, node);
return func;
}
function transformClass(path, file, builtinClasses, isLoose) {
const classState = {
parent: undefined,
scope: undefined,
node: undefined,
path: undefined,
file: undefined,
classId: undefined,
classRef: undefined,
superName: undefined,
superReturns: [],
isDerived: false,
extendsNative: false,
construct: undefined,
constructorBody: undefined,
userConstructor: undefined,
userConstructorPath: undefined,
hasConstructor: false,
instancePropBody: [],
instancePropRefs: {},
staticPropBody: [],
body: [],
superThises: [],
pushedConstructor: false,
pushedInherits: false,
protoAlias: null,
isLoose: false,
hasInstanceDescriptors: false,
hasStaticDescriptors: false,
instanceMutatorMap: {},
staticMutatorMap: {}
};
const setState = newState => {
Object.assign(classState, newState);
};
const findThisesVisitor = _core.traverse.visitors.merge([_helperReplaceSupers.environmentVisitor, {
ThisExpression(path) {
classState.superThises.push(path);
}
}]);
function pushToMap(node, enumerable, kind = "value", scope) {
let mutatorMap;
if (node.static) {
setState({
hasStaticDescriptors: true
});
mutatorMap = classState.staticMutatorMap;
} else {
setState({
hasInstanceDescriptors: true
});
mutatorMap = classState.instanceMutatorMap;
}
const map = defineMap.push(mutatorMap, node, kind, classState.file, scope);
if (enumerable) {
map.enumerable = _core.types.booleanLiteral(true);
}
return map;
}
function maybeCreateConstructor() {
let hasConstructor = false;
const paths = classState.path.get("body.body");
for (const path of paths) {
hasConstructor = path.equals("kind", "constructor");
if (hasConstructor) break;
}
if (hasConstructor) return;
let params, body;
if (classState.isDerived) {
const constructor = _core.template.expression.ast`
(function () {
super(...arguments);
})
`;
params = constructor.params;
body = constructor.body;
} else {
params = [];
body = _core.types.blockStatement([]);
}
classState.path.get("body").unshiftContainer("body", _core.types.classMethod("constructor", _core.types.identifier("constructor"), params, body));
}
function buildBody() {
maybeCreateConstructor();
pushBody();
verifyConstructor();
if (classState.userConstructor) {
const {
constructorBody,
userConstructor,
construct
} = classState;
constructorBody.body = constructorBody.body.concat(userConstructor.body.body);
_core.types.inherits(construct, userConstructor);
_core.types.inherits(constructorBody, userConstructor.body);
}
pushDescriptors();
}
function pushBody() {
const classBodyPaths = classState.path.get("body.body");
for (const path of classBodyPaths) {
const node = path.node;
if (path.isClassProperty()) {
throw path.buildCodeFrameError("Missing class properties transform.");
}
if (node.decorators) {
throw path.buildCodeFrameError("Method has decorators, put the decorator plugin before the classes one.");
}
if (_core.types.isClassMethod(node)) {
const isConstructor = node.kind === "constructor";
const replaceSupers = new _helperReplaceSupers.default({
methodPath: path,
objectRef: classState.classRef,
superRef: classState.superName,
isLoose: classState.isLoose,
file: classState.file
});
replaceSupers.replace();
const superReturns = [];
path.traverse(_core.traverse.visitors.merge([_helperReplaceSupers.environmentVisitor, {
ReturnStatement(path) {
if (!path.getFunctionParent().isArrowFunctionExpression()) {
superReturns.push(path);
}
}
}]));
if (isConstructor) {
pushConstructor(superReturns, node, path);
} else {
pushMethod(node, path);
}
}
}
}
function clearDescriptors() {
setState({
hasInstanceDescriptors: false,
hasStaticDescriptors: false,
instanceMutatorMap: {},
staticMutatorMap: {}
});
}
function pushDescriptors() {
pushInheritsToBody();
const {
body
} = classState;
let instanceProps;
let staticProps;
if (classState.hasInstanceDescriptors) {
instanceProps = defineMap.toClassObject(classState.instanceMutatorMap);
}
if (classState.hasStaticDescriptors) {
staticProps = defineMap.toClassObject(classState.staticMutatorMap);
}
if (instanceProps || staticProps) {
if (instanceProps) {
instanceProps = defineMap.toComputedObjectFromClass(instanceProps);
}
if (staticProps) {
staticProps = defineMap.toComputedObjectFromClass(staticProps);
}
let args = [_core.types.cloneNode(classState.classRef), _core.types.nullLiteral(), _core.types.nullLiteral()];
if (instanceProps) args[1] = instanceProps;
if (staticProps) args[2] = staticProps;
let lastNonNullIndex = 0;
for (let i = 0; i < args.length; i++) {
if (!_core.types.isNullLiteral(args[i])) lastNonNullIndex = i;
}
args = args.slice(0, lastNonNullIndex + 1);
body.push(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper("createClass"), args)));
}
clearDescriptors();
}
function wrapSuperCall(bareSuper, superRef, thisRef, body) {
let bareSuperNode = bareSuper.node;
let call;
if (classState.isLoose) {
bareSuperNode.arguments.unshift(_core.types.thisExpression());
if (bareSuperNode.arguments.length === 2 && _core.types.isSpreadElement(bareSuperNode.arguments[1]) && _core.types.isIdentifier(bareSuperNode.arguments[1].argument, {
name: "arguments"
})) {
bareSuperNode.arguments[1] = bareSuperNode.arguments[1].argument;
bareSuperNode.callee = _core.types.memberExpression(_core.types.cloneNode(superRef), _core.types.identifier("apply"));
} else {
bareSuperNode.callee = _core.types.memberExpression(_core.types.cloneNode(superRef), _core.types.identifier("call"));
}
call = _core.types.logicalExpression("||", bareSuperNode, _core.types.thisExpression());
} else {
bareSuperNode = (0, _helperOptimiseCallExpression.default)(_core.types.callExpression(classState.file.addHelper("getPrototypeOf"), [_core.types.cloneNode(classState.classRef)]), _core.types.thisExpression(), bareSuperNode.arguments);
call = _core.types.callExpression(classState.file.addHelper("possibleConstructorReturn"), [_core.types.thisExpression(), bareSuperNode]);
}
if (bareSuper.parentPath.isExpressionStatement() && bareSuper.parentPath.container === body.node.body && body.node.body.length - 1 === bareSuper.parentPath.key) {
if (classState.superThises.length) {
call = _core.types.assignmentExpression("=", thisRef(), call);
}
bareSuper.parentPath.replaceWith(_core.types.returnStatement(call));
} else {
bareSuper.replaceWith(_core.types.assignmentExpression("=", thisRef(), call));
}
}
function verifyConstructor() {
if (!classState.isDerived) return;
const path = classState.userConstructorPath;
const body = path.get("body");
path.traverse(findThisesVisitor);
let thisRef = function () {
const ref = path.scope.generateDeclaredUidIdentifier("this");
thisRef = () => _core.types.cloneNode(ref);
return ref;
};
for (const thisPath of classState.superThises) {
const {
node,
parentPath
} = thisPath;
if (parentPath.isMemberExpression({
object: node
})) {
thisPath.replaceWith(thisRef());
continue;
}
thisPath.replaceWith(_core.types.callExpression(classState.file.addHelper("assertThisInitialized"), [thisRef()]));
}
const bareSupers = new Set();
path.traverse(_core.traverse.visitors.merge([_helperReplaceSupers.environmentVisitor, {
Super(path) {
const {
node,
parentPath
} = path;
if (parentPath.isCallExpression({
callee: node
})) {
bareSupers.add(parentPath);
}
}
}]));
let guaranteedSuperBeforeFinish = !!bareSupers.size;
for (const bareSuper of bareSupers) {
wrapSuperCall(bareSuper, classState.superName, thisRef, body);
if (guaranteedSuperBeforeFinish) {
bareSuper.find(function (parentPath) {
if (parentPath === path) {
return true;
}
if (parentPath.isLoop() || parentPath.isConditional() || parentPath.isArrowFunctionExpression()) {
guaranteedSuperBeforeFinish = false;
return true;
}
});
}
}
let wrapReturn;
if (classState.isLoose) {
wrapReturn = returnArg => {
const thisExpr = _core.types.callExpression(classState.file.addHelper("assertThisInitialized"), [thisRef()]);
return returnArg ? _core.types.logicalExpression("||", returnArg, thisExpr) : thisExpr;
};
} else {
wrapReturn = returnArg => _core.types.callExpression(classState.file.addHelper("possibleConstructorReturn"), [thisRef()].concat(returnArg || []));
}
const bodyPaths = body.get("body");
if (!bodyPaths.length || !bodyPaths.pop().isReturnStatement()) {
body.pushContainer("body", _core.types.returnStatement(guaranteedSuperBeforeFinish ? thisRef() : wrapReturn()));
}
for (const returnPath of classState.superReturns) {
returnPath.get("argument").replaceWith(wrapReturn(returnPath.node.argument));
}
}
function pushMethod(node, path) {
const scope = path ? path.scope : classState.scope;
if (node.kind === "method") {
if (processMethod(node, scope)) return;
}
pushToMap(node, false, null, scope);
}
function processMethod(node, scope) {
if (classState.isLoose && !node.decorators) {
let {
classRef
} = classState;
if (!node.static) {
insertProtoAliasOnce();
classRef = classState.protoAlias;
}
const methodName = _core.types.memberExpression(_core.types.cloneNode(classRef), node.key, node.computed || _core.types.isLiteral(node.key));
let func = _core.types.functionExpression(null, node.params, node.body, node.generator, node.async);
_core.types.inherits(func, node);
const key = _core.types.toComputedKey(node, node.key);
if (_core.types.isStringLiteral(key)) {
func = (0, _helperFunctionName.default)({
node: func,
id: key,
scope
});
}
const expr = _core.types.expressionStatement(_core.types.assignmentExpression("=", methodName, func));
_core.types.inheritsComments(expr, node);
classState.body.push(expr);
return true;
}
return false;
}
function insertProtoAliasOnce() {
if (classState.protoAlias === null) {
setState({
protoAlias: classState.scope.generateUidIdentifier("proto")
});
const classProto = _core.types.memberExpression(classState.classRef, _core.types.identifier("prototype"));
const protoDeclaration = _core.types.variableDeclaration("var", [_core.types.variableDeclarator(classState.protoAlias, classProto)]);
classState.body.push(protoDeclaration);
}
}
function pushConstructor(superReturns, method, path) {
if (path.scope.hasOwnBinding(classState.classRef.name)) {
path.scope.rename(classState.classRef.name);
}
setState({
userConstructorPath: path,
userConstructor: method,
hasConstructor: true,
superReturns
});
const {
construct
} = classState;
_core.types.inheritsComments(construct, method);
construct.params = method.params;
_core.types.inherits(construct.body, method.body);
construct.body.directives = method.body.directives;
pushConstructorToBody();
}
function pushConstructorToBody() {
if (classState.pushedConstructor) return;
classState.pushedConstructor = true;
if (classState.hasInstanceDescriptors || classState.hasStaticDescriptors) {
pushDescriptors();
}
classState.body.push(classState.construct);
pushInheritsToBody();
}
function pushInheritsToBody() {
if (!classState.isDerived || classState.pushedInherits) return;
setState({
pushedInherits: true
});
classState.body.unshift(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper(classState.isLoose ? "inheritsLoose" : "inherits"), [_core.types.cloneNode(classState.classRef), _core.types.cloneNode(classState.superName)])));
}
function setupClosureParamsArgs() {
const {
superName
} = classState;
const closureParams = [];
const closureArgs = [];
if (classState.isDerived) {
const arg = classState.extendsNative ? _core.types.callExpression(classState.file.addHelper("wrapNativeSuper"), [_core.types.cloneNode(superName)]) : _core.types.cloneNode(superName);
const param = classState.scope.generateUidIdentifierBasedOnNode(superName);
closureParams.push(param);
closureArgs.push(arg);
setState({
superName: _core.types.cloneNode(param)
});
}
return {
closureParams,
closureArgs
};
}
function classTransformer(path, file, builtinClasses, isLoose) {
setState({
parent: path.parent,
scope: path.scope,
node: path.node,
path,
file,
isLoose
});
setState({
classId: classState.node.id,
classRef: classState.node.id ? _core.types.identifier(classState.node.id.name) : classState.scope.generateUidIdentifier("class"),
superName: classState.node.superClass,
isDerived: !!classState.node.superClass,
constructorBody: _core.types.blockStatement([])
});
setState({
extendsNative: classState.isDerived && builtinClasses.has(classState.superName.name) && !classState.scope.hasBinding(classState.superName.name, true)
});
const {
classRef,
node,
constructorBody
} = classState;
setState({
construct: buildConstructor(classRef, constructorBody, node)
});
let {
body
} = classState;
const {
closureParams,
closureArgs
} = setupClosureParamsArgs();
buildBody();
if (!classState.isLoose) {
constructorBody.body.unshift(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper("classCallCheck"), [_core.types.thisExpression(), _core.types.cloneNode(classState.classRef)])));
}
body = body.concat(classState.staticPropBody.map(fn => fn(_core.types.cloneNode(classState.classRef))));
const isStrict = path.isInStrictMode();
let constructorOnly = classState.classId && body.length === 1;
if (constructorOnly && !isStrict) {
for (const param of classState.construct.params) {
if (!_core.types.isIdentifier(param)) {
constructorOnly = false;
break;
}
}
}
const directives = constructorOnly ? body[0].body.directives : [];
if (!isStrict) {
directives.push(_core.types.directive(_core.types.directiveLiteral("use strict")));
}
if (constructorOnly) {
return _core.types.toExpression(body[0]);
}
body.push(_core.types.returnStatement(_core.types.cloneNode(classState.classRef)));
const container = _core.types.arrowFunctionExpression(closureParams, _core.types.blockStatement(body, directives));
return _core.types.callExpression(container, closureArgs);
}
return classTransformer(path, file, builtinClasses, isLoose);
}
\ No newline at end of file
{
"name": "@babel/plugin-transform-classes",
"version": "7.7.0",
"description": "Compile ES2015 classes to ES5",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-classes",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"main": "lib/index.js",
"dependencies": {
"@babel/helper-annotate-as-pure": "^7.7.0",
"@babel/helper-define-map": "^7.7.0",
"@babel/helper-function-name": "^7.7.0",
"@babel/helper-optimise-call-expression": "^7.7.0",
"@babel/helper-plugin-utils": "^7.0.0",
"@babel/helper-replace-supers": "^7.7.0",
"@babel/helper-split-export-declaration": "^7.7.0",
"globals": "^11.1.0"
},
"keywords": [
"babel-plugin"
],
"peerDependencies": {
"@babel/core": "^7.0.0-0"
},
"devDependencies": {
"@babel/core": "^7.7.0",
"@babel/helper-plugin-test-runner": "^7.0.0"
},
"gitHead": "97faa83953cb87e332554fa559a4956d202343ea"
}
MIT License
Copyright (c) 2014-2018 Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# @babel/plugin-transform-computed-properties
> Compile ES2015 computed properties to ES5
See our website [@babel/plugin-transform-computed-properties](https://babeljs.io/docs/en/next/babel-plugin-transform-computed-properties.html) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/plugin-transform-computed-properties
```
or using yarn:
```sh
yarn add @babel/plugin-transform-computed-properties --dev
```
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _helperPluginUtils() {
const data = require("@babel/helper-plugin-utils");
_helperPluginUtils = function () {
return data;
};
return data;
}
function _core() {
const data = require("@babel/core");
_core = function () {
return data;
};
return data;
}
var _default = (0, _helperPluginUtils().declare)((api, options) => {
api.assertVersion(7);
const {
loose
} = options;
const pushComputedProps = loose ? pushComputedPropsLoose : pushComputedPropsSpec;
const buildMutatorMapAssign = (0, _core().template)(`
MUTATOR_MAP_REF[KEY] = MUTATOR_MAP_REF[KEY] || {};
MUTATOR_MAP_REF[KEY].KIND = VALUE;
`);
function getValue(prop) {
if (_core().types.isObjectProperty(prop)) {
return prop.value;
} else if (_core().types.isObjectMethod(prop)) {
return _core().types.functionExpression(null, prop.params, prop.body, prop.generator, prop.async);
}
}
function pushAssign(objId, prop, body) {
if (prop.kind === "get" && prop.kind === "set") {
pushMutatorDefine(objId, prop, body);
} else {
body.push(_core().types.expressionStatement(_core().types.assignmentExpression("=", _core().types.memberExpression(_core().types.cloneNode(objId), prop.key, prop.computed || _core().types.isLiteral(prop.key)), getValue(prop))));
}
}
function pushMutatorDefine({
body,
getMutatorId,
scope
}, prop) {
let key = !prop.computed && _core().types.isIdentifier(prop.key) ? _core().types.stringLiteral(prop.key.name) : prop.key;
const maybeMemoise = scope.maybeGenerateMemoised(key);
if (maybeMemoise) {
body.push(_core().types.expressionStatement(_core().types.assignmentExpression("=", maybeMemoise, key)));
key = maybeMemoise;
}
body.push(...buildMutatorMapAssign({
MUTATOR_MAP_REF: getMutatorId(),
KEY: _core().types.cloneNode(key),
VALUE: getValue(prop),
KIND: _core().types.identifier(prop.kind)
}));
}
function pushComputedPropsLoose(info) {
for (const prop of info.computedProps) {
if (prop.kind === "get" || prop.kind === "set") {
pushMutatorDefine(info, prop);
} else {
pushAssign(_core().types.cloneNode(info.objId), prop, info.body);
}
}
}
function pushComputedPropsSpec(info) {
const {
objId,
body,
computedProps,
state
} = info;
for (const prop of computedProps) {
const key = _core().types.toComputedKey(prop);
if (prop.kind === "get" || prop.kind === "set") {
pushMutatorDefine(info, prop);
} else if (_core().types.isStringLiteral(key, {
value: "__proto__"
})) {
pushAssign(objId, prop, body);
} else {
if (computedProps.length === 1) {
return _core().types.callExpression(state.addHelper("defineProperty"), [info.initPropExpression, key, getValue(prop)]);
} else {
body.push(_core().types.expressionStatement(_core().types.callExpression(state.addHelper("defineProperty"), [_core().types.cloneNode(objId), key, getValue(prop)])));
}
}
}
}
return {
name: "transform-computed-properties",
visitor: {
ObjectExpression: {
exit(path, state) {
const {
node,
parent,
scope
} = path;
let hasComputed = false;
for (const prop of node.properties) {
hasComputed = prop.computed === true;
if (hasComputed) break;
}
if (!hasComputed) return;
const initProps = [];
const computedProps = [];
let foundComputed = false;
for (const prop of node.properties) {
if (prop.computed) {
foundComputed = true;
}
if (foundComputed) {
computedProps.push(prop);
} else {
initProps.push(prop);
}
}
const objId = scope.generateUidIdentifierBasedOnNode(parent);
const initPropExpression = _core().types.objectExpression(initProps);
const body = [];
body.push(_core().types.variableDeclaration("var", [_core().types.variableDeclarator(objId, initPropExpression)]));
let mutatorRef;
const getMutatorId = function () {
if (!mutatorRef) {
mutatorRef = scope.generateUidIdentifier("mutatorMap");
body.push(_core().types.variableDeclaration("var", [_core().types.variableDeclarator(mutatorRef, _core().types.objectExpression([]))]));
}
return _core().types.cloneNode(mutatorRef);
};
const single = pushComputedProps({
scope,
objId,
body,
computedProps,
initPropExpression,
getMutatorId,
state
});
if (mutatorRef) {
body.push(_core().types.expressionStatement(_core().types.callExpression(state.addHelper("defineEnumerableProperties"), [_core().types.cloneNode(objId), _core().types.cloneNode(mutatorRef)])));
}
if (single) {
path.replaceWith(single);
} else {
body.push(_core().types.expressionStatement(_core().types.cloneNode(objId)));
path.replaceWithMultiple(body);
}
}
}
}
};
});
exports.default = _default;
\ No newline at end of file
{
"name": "@babel/plugin-transform-computed-properties",
"version": "7.2.0",
"description": "Compile ES2015 computed properties to ES5",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-computed-properties",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"main": "lib/index.js",
"keywords": [
"babel-plugin"
],
"dependencies": {
"@babel/helper-plugin-utils": "^7.0.0"
},
"peerDependencies": {
"@babel/core": "^7.0.0-0"
},
"devDependencies": {
"@babel/core": "^7.2.0",
"@babel/helper-plugin-test-runner": "^7.0.0"
}
}
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# @babel/plugin-transform-destructuring
> Compile ES2015 destructuring to ES5
See our website [@babel/plugin-transform-destructuring](https://babeljs.io/docs/en/next/babel-plugin-transform-destructuring.html) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/plugin-transform-destructuring
```
or using yarn:
```sh
yarn add @babel/plugin-transform-destructuring --dev
```
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _helperPluginUtils() {
const data = require("@babel/helper-plugin-utils");
_helperPluginUtils = function () {
return data;
};
return data;
}
function _core() {
const data = require("@babel/core");
_core = function () {
return data;
};
return data;
}
var _default = (0, _helperPluginUtils().declare)((api, options) => {
api.assertVersion(7);
const {
loose = false,
useBuiltIns = false
} = options;
if (typeof loose !== "boolean") {
throw new Error(`.loose must be a boolean or undefined`);
}
const arrayOnlySpread = loose;
function getExtendsHelper(file) {
return useBuiltIns ? _core().types.memberExpression(_core().types.identifier("Object"), _core().types.identifier("assign")) : file.addHelper("extends");
}
function variableDeclarationHasPattern(node) {
for (const declar of node.declarations) {
if (_core().types.isPattern(declar.id)) {
return true;
}
}
return false;
}
function hasRest(pattern) {
for (const elem of pattern.elements) {
if (_core().types.isRestElement(elem)) {
return true;
}
}
return false;
}
function hasObjectRest(pattern) {
for (const elem of pattern.properties) {
if (_core().types.isRestElement(elem)) {
return true;
}
}
return false;
}
const STOP_TRAVERSAL = {};
const arrayUnpackVisitor = (node, ancestors, state) => {
if (!ancestors.length) {
return;
}
if (_core().types.isIdentifier(node) && _core().types.isReferenced(node, ancestors[ancestors.length - 1]) && state.bindings[node.name]) {
state.deopt = true;
throw STOP_TRAVERSAL;
}
};
class DestructuringTransformer {
constructor(opts) {
this.blockHoist = opts.blockHoist;
this.operator = opts.operator;
this.arrays = {};
this.nodes = opts.nodes || [];
this.scope = opts.scope;
this.kind = opts.kind;
this.arrayOnlySpread = opts.arrayOnlySpread;
this.addHelper = opts.addHelper;
}
buildVariableAssignment(id, init) {
let op = this.operator;
if (_core().types.isMemberExpression(id)) op = "=";
let node;
if (op) {
node = _core().types.expressionStatement(_core().types.assignmentExpression(op, id, _core().types.cloneNode(init) || this.scope.buildUndefinedNode()));
} else {
node = _core().types.variableDeclaration(this.kind, [_core().types.variableDeclarator(id, _core().types.cloneNode(init))]);
}
node._blockHoist = this.blockHoist;
return node;
}
buildVariableDeclaration(id, init) {
const declar = _core().types.variableDeclaration("var", [_core().types.variableDeclarator(_core().types.cloneNode(id), _core().types.cloneNode(init))]);
declar._blockHoist = this.blockHoist;
return declar;
}
push(id, _init) {
const init = _core().types.cloneNode(_init);
if (_core().types.isObjectPattern(id)) {
this.pushObjectPattern(id, init);
} else if (_core().types.isArrayPattern(id)) {
this.pushArrayPattern(id, init);
} else if (_core().types.isAssignmentPattern(id)) {
this.pushAssignmentPattern(id, init);
} else {
this.nodes.push(this.buildVariableAssignment(id, init));
}
}
toArray(node, count) {
if (this.arrayOnlySpread || _core().types.isIdentifier(node) && this.arrays[node.name]) {
return node;
} else {
return this.scope.toArray(node, count);
}
}
pushAssignmentPattern({
left,
right
}, valueRef) {
const tempId = this.scope.generateUidIdentifierBasedOnNode(valueRef);
this.nodes.push(this.buildVariableDeclaration(tempId, valueRef));
const tempConditional = _core().types.conditionalExpression(_core().types.binaryExpression("===", _core().types.cloneNode(tempId), this.scope.buildUndefinedNode()), right, _core().types.cloneNode(tempId));
if (_core().types.isPattern(left)) {
let patternId;
let node;
if (this.kind === "const") {
patternId = this.scope.generateUidIdentifier(tempId.name);
node = this.buildVariableDeclaration(patternId, tempConditional);
} else {
patternId = tempId;
node = _core().types.expressionStatement(_core().types.assignmentExpression("=", _core().types.cloneNode(tempId), tempConditional));
}
this.nodes.push(node);
this.push(left, patternId);
} else {
this.nodes.push(this.buildVariableAssignment(left, tempConditional));
}
}
pushObjectRest(pattern, objRef, spreadProp, spreadPropIndex) {
const keys = [];
let allLiteral = true;
for (let i = 0; i < pattern.properties.length; i++) {
const prop = pattern.properties[i];
if (i >= spreadPropIndex) break;
if (_core().types.isRestElement(prop)) continue;
const key = prop.key;
if (_core().types.isIdentifier(key) && !prop.computed) {
keys.push(_core().types.stringLiteral(key.name));
} else if (_core().types.isTemplateLiteral(prop.key)) {
keys.push(_core().types.cloneNode(prop.key));
} else if (_core().types.isLiteral(key)) {
keys.push(_core().types.stringLiteral(String(key.value)));
} else {
keys.push(_core().types.cloneNode(key));
allLiteral = false;
}
}
let value;
if (keys.length === 0) {
value = _core().types.callExpression(getExtendsHelper(this), [_core().types.objectExpression([]), _core().types.cloneNode(objRef)]);
} else {
let keyExpression = _core().types.arrayExpression(keys);
if (!allLiteral) {
keyExpression = _core().types.callExpression(_core().types.memberExpression(keyExpression, _core().types.identifier("map")), [this.addHelper("toPropertyKey")]);
}
value = _core().types.callExpression(this.addHelper(`objectWithoutProperties${loose ? "Loose" : ""}`), [_core().types.cloneNode(objRef), keyExpression]);
}
this.nodes.push(this.buildVariableAssignment(spreadProp.argument, value));
}
pushObjectProperty(prop, propRef) {
if (_core().types.isLiteral(prop.key)) prop.computed = true;
const pattern = prop.value;
const objRef = _core().types.memberExpression(_core().types.cloneNode(propRef), prop.key, prop.computed);
if (_core().types.isPattern(pattern)) {
this.push(pattern, objRef);
} else {
this.nodes.push(this.buildVariableAssignment(pattern, objRef));
}
}
pushObjectPattern(pattern, objRef) {
if (!pattern.properties.length) {
this.nodes.push(_core().types.expressionStatement(_core().types.callExpression(this.addHelper("objectDestructuringEmpty"), [objRef])));
}
if (pattern.properties.length > 1 && !this.scope.isStatic(objRef)) {
const temp = this.scope.generateUidIdentifierBasedOnNode(objRef);
this.nodes.push(this.buildVariableDeclaration(temp, objRef));
objRef = temp;
}
if (hasObjectRest(pattern)) {
let copiedPattern;
for (let i = 0; i < pattern.properties.length; i++) {
const prop = pattern.properties[i];
if (_core().types.isRestElement(prop)) {
break;
}
const key = prop.key;
if (prop.computed && !this.scope.isPure(key)) {
const name = this.scope.generateUidIdentifierBasedOnNode(key);
this.nodes.push(this.buildVariableDeclaration(name, key));
if (!copiedPattern) {
copiedPattern = pattern = Object.assign({}, pattern, {
properties: pattern.properties.slice()
});
}
copiedPattern.properties[i] = Object.assign({}, copiedPattern.properties[i], {
key: name
});
}
}
}
for (let i = 0; i < pattern.properties.length; i++) {
const prop = pattern.properties[i];
if (_core().types.isRestElement(prop)) {
this.pushObjectRest(pattern, objRef, prop, i);
} else {
this.pushObjectProperty(prop, objRef);
}
}
}
canUnpackArrayPattern(pattern, arr) {
if (!_core().types.isArrayExpression(arr)) return false;
if (pattern.elements.length > arr.elements.length) return;
if (pattern.elements.length < arr.elements.length && !hasRest(pattern)) {
return false;
}
for (const elem of pattern.elements) {
if (!elem) return false;
if (_core().types.isMemberExpression(elem)) return false;
}
for (const elem of arr.elements) {
if (_core().types.isSpreadElement(elem)) return false;
if (_core().types.isCallExpression(elem)) return false;
if (_core().types.isMemberExpression(elem)) return false;
}
const bindings = _core().types.getBindingIdentifiers(pattern);
const state = {
deopt: false,
bindings
};
try {
_core().types.traverse(arr, arrayUnpackVisitor, state);
} catch (e) {
if (e !== STOP_TRAVERSAL) throw e;
}
return !state.deopt;
}
pushUnpackedArrayPattern(pattern, arr) {
for (let i = 0; i < pattern.elements.length; i++) {
const elem = pattern.elements[i];
if (_core().types.isRestElement(elem)) {
this.push(elem.argument, _core().types.arrayExpression(arr.elements.slice(i)));
} else {
this.push(elem, arr.elements[i]);
}
}
}
pushArrayPattern(pattern, arrayRef) {
if (!pattern.elements) return;
if (this.canUnpackArrayPattern(pattern, arrayRef)) {
return this.pushUnpackedArrayPattern(pattern, arrayRef);
}
const count = !hasRest(pattern) && pattern.elements.length;
const toArray = this.toArray(arrayRef, count);
if (_core().types.isIdentifier(toArray)) {
arrayRef = toArray;
} else {
arrayRef = this.scope.generateUidIdentifierBasedOnNode(arrayRef);
this.arrays[arrayRef.name] = true;
this.nodes.push(this.buildVariableDeclaration(arrayRef, toArray));
}
for (let i = 0; i < pattern.elements.length; i++) {
let elem = pattern.elements[i];
if (!elem) continue;
let elemRef;
if (_core().types.isRestElement(elem)) {
elemRef = this.toArray(arrayRef);
elemRef = _core().types.callExpression(_core().types.memberExpression(elemRef, _core().types.identifier("slice")), [_core().types.numericLiteral(i)]);
elem = elem.argument;
} else {
elemRef = _core().types.memberExpression(arrayRef, _core().types.numericLiteral(i), true);
}
this.push(elem, elemRef);
}
}
init(pattern, ref) {
if (!_core().types.isArrayExpression(ref) && !_core().types.isMemberExpression(ref)) {
const memo = this.scope.maybeGenerateMemoised(ref, true);
if (memo) {
this.nodes.push(this.buildVariableDeclaration(memo, _core().types.cloneNode(ref)));
ref = memo;
}
}
this.push(pattern, ref);
return this.nodes;
}
}
return {
name: "transform-destructuring",
visitor: {
ExportNamedDeclaration(path) {
const declaration = path.get("declaration");
if (!declaration.isVariableDeclaration()) return;
if (!variableDeclarationHasPattern(declaration.node)) return;
const specifiers = [];
for (const name of Object.keys(path.getOuterBindingIdentifiers(path))) {
specifiers.push(_core().types.exportSpecifier(_core().types.identifier(name), _core().types.identifier(name)));
}
path.replaceWith(declaration.node);
path.insertAfter(_core().types.exportNamedDeclaration(null, specifiers));
},
ForXStatement(path) {
const {
node,
scope
} = path;
const left = node.left;
if (_core().types.isPattern(left)) {
const temp = scope.generateUidIdentifier("ref");
node.left = _core().types.variableDeclaration("var", [_core().types.variableDeclarator(temp)]);
path.ensureBlock();
if (node.body.body.length === 0 && path.isCompletionRecord()) {
node.body.body.unshift(_core().types.expressionStatement(scope.buildUndefinedNode()));
}
node.body.body.unshift(_core().types.expressionStatement(_core().types.assignmentExpression("=", left, temp)));
return;
}
if (!_core().types.isVariableDeclaration(left)) return;
const pattern = left.declarations[0].id;
if (!_core().types.isPattern(pattern)) return;
const key = scope.generateUidIdentifier("ref");
node.left = _core().types.variableDeclaration(left.kind, [_core().types.variableDeclarator(key, null)]);
const nodes = [];
const destructuring = new DestructuringTransformer({
kind: left.kind,
scope: scope,
nodes: nodes,
arrayOnlySpread,
addHelper: name => this.addHelper(name)
});
destructuring.init(pattern, key);
path.ensureBlock();
const block = node.body;
block.body = nodes.concat(block.body);
},
CatchClause({
node,
scope
}) {
const pattern = node.param;
if (!_core().types.isPattern(pattern)) return;
const ref = scope.generateUidIdentifier("ref");
node.param = ref;
const nodes = [];
const destructuring = new DestructuringTransformer({
kind: "let",
scope: scope,
nodes: nodes,
arrayOnlySpread,
addHelper: name => this.addHelper(name)
});
destructuring.init(pattern, ref);
node.body.body = nodes.concat(node.body.body);
},
AssignmentExpression(path) {
const {
node,
scope
} = path;
if (!_core().types.isPattern(node.left)) return;
const nodes = [];
const destructuring = new DestructuringTransformer({
operator: node.operator,
scope: scope,
nodes: nodes,
arrayOnlySpread,
addHelper: name => this.addHelper(name)
});
let ref;
if (path.isCompletionRecord() || !path.parentPath.isExpressionStatement()) {
ref = scope.generateUidIdentifierBasedOnNode(node.right, "ref");
nodes.push(_core().types.variableDeclaration("var", [_core().types.variableDeclarator(ref, node.right)]));
if (_core().types.isArrayExpression(node.right)) {
destructuring.arrays[ref.name] = true;
}
}
destructuring.init(node.left, ref || node.right);
if (ref) {
if (path.parentPath.isArrowFunctionExpression()) {
path.replaceWith(_core().types.blockStatement([]));
nodes.push(_core().types.returnStatement(_core().types.cloneNode(ref)));
} else {
nodes.push(_core().types.expressionStatement(_core().types.cloneNode(ref)));
}
}
path.replaceWithMultiple(nodes);
},
VariableDeclaration(path) {
const {
node,
scope,
parent
} = path;
if (_core().types.isForXStatement(parent)) return;
if (!parent || !path.container) return;
if (!variableDeclarationHasPattern(node)) return;
const nodeKind = node.kind;
const nodes = [];
let declar;
for (let i = 0; i < node.declarations.length; i++) {
declar = node.declarations[i];
const patternId = declar.init;
const pattern = declar.id;
const destructuring = new DestructuringTransformer({
blockHoist: node._blockHoist,
nodes: nodes,
scope: scope,
kind: node.kind,
arrayOnlySpread,
addHelper: name => this.addHelper(name)
});
if (_core().types.isPattern(pattern)) {
destructuring.init(pattern, patternId);
if (+i !== node.declarations.length - 1) {
_core().types.inherits(nodes[nodes.length - 1], declar);
}
} else {
nodes.push(_core().types.inherits(destructuring.buildVariableAssignment(declar.id, _core().types.cloneNode(declar.init)), declar));
}
}
let tail = null;
const nodesOut = [];
for (const node of nodes) {
if (tail !== null && _core().types.isVariableDeclaration(node)) {
tail.declarations.push(...node.declarations);
} else {
node.kind = nodeKind;
nodesOut.push(node);
tail = _core().types.isVariableDeclaration(node) ? node : null;
}
}
for (const nodeOut of nodesOut) {
if (!nodeOut.declarations) continue;
for (const declaration of nodeOut.declarations) {
const {
name
} = declaration.id;
if (scope.bindings[name]) {
scope.bindings[name].kind = nodeOut.kind;
}
}
}
if (nodesOut.length === 1) {
path.replaceWith(nodesOut[0]);
} else {
path.replaceWithMultiple(nodesOut);
}
}
}
};
});
exports.default = _default;
\ No newline at end of file
{
"name": "@babel/plugin-transform-destructuring",
"version": "7.6.0",
"description": "Compile ES2015 destructuring to ES5",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-destructuring",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"main": "lib/index.js",
"keywords": [
"babel-plugin"
],
"dependencies": {
"@babel/helper-plugin-utils": "^7.0.0"
},
"peerDependencies": {
"@babel/core": "^7.0.0-0"
},
"devDependencies": {
"@babel/core": "^7.6.0",
"@babel/helper-plugin-test-runner": "^7.0.0"
},
"gitHead": "cbd5a26e57758e3f748174ff84aa570e8780e85d"
}
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# @babel/plugin-transform-dotall-regex
> Compile regular expressions using the `s` (`dotAll`) flag to ES5.
See our website [@babel/plugin-transform-dotall-regex](https://babeljs.io/docs/en/next/babel-plugin-transform-dotall-regex.html) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/plugin-transform-dotall-regex
```
or using yarn:
```sh
yarn add @babel/plugin-transform-dotall-regex --dev
```
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _helperCreateRegexpFeaturesPlugin = require("@babel/helper-create-regexp-features-plugin");
var _helperPluginUtils = require("@babel/helper-plugin-utils");
var _default = (0, _helperPluginUtils.declare)(api => {
api.assertVersion(7);
return (0, _helperCreateRegexpFeaturesPlugin.createRegExpFeaturePlugin)({
name: "transform-dotall-regex",
feature: "dotAllFlag"
});
});
exports.default = _default;
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment