@babel/traverse 8.0.0-alpha.10 → 8.0.0-alpha.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,13 +1,10 @@
1
1
  import * as _t from '@babel/types';
2
2
  import buildDebug from 'debug';
3
- import splitExportDeclaration from '@babel/helper-split-export-declaration';
4
- import environmentVisitor, { requeueComputedKeyAndDecorators } from '@babel/helper-environment-visitor';
5
3
  import globals from 'globals';
6
4
  import generator from '@babel/generator';
7
5
  import { codeFrameColumns } from '@babel/code-frame';
8
6
  import { parse } from '@babel/parser';
9
- import hoistVariables from '@babel/helper-hoist-variables';
10
- import nameFunction from '@babel/helper-function-name';
7
+ import template from '@babel/template';
11
8
 
12
9
  const ReferencedIdentifier = ["Identifier", "JSXIdentifier"];
13
10
  const ReferencedMemberExpression = ["MemberExpression"];
@@ -291,7 +288,7 @@ function verify$1(visitor) {
291
288
  validateVisitorMethods(nodeType, visitor[nodeType]);
292
289
  }
293
290
  if (shouldIgnoreKey(nodeType)) continue;
294
- if (TYPES.indexOf(nodeType) < 0) {
291
+ if (!TYPES.includes(nodeType)) {
295
292
  throw new Error(`You gave us a visitor for the node type ${nodeType} but it's not a valid type`);
296
293
  }
297
294
  const visitors = visitor[nodeType];
@@ -406,9 +403,27 @@ function mergePair(dest, src) {
406
403
  dest[phase] = [].concat(dest[phase] || [], src[phase]);
407
404
  }
408
405
  }
406
+ const _environmentVisitor = {
407
+ FunctionParent(path) {
408
+ if (path.isArrowFunctionExpression()) return;
409
+ path.skip();
410
+ if (path.isMethod()) {
411
+ path.requeueComputedKeyAndDecorators();
412
+ }
413
+ },
414
+ Property(path) {
415
+ if (path.isObjectProperty()) return;
416
+ path.skip();
417
+ path.requeueComputedKeyAndDecorators();
418
+ }
419
+ };
420
+ function environmentVisitor(visitor) {
421
+ return merge([_environmentVisitor, visitor]);
422
+ }
409
423
 
410
424
  var visitors = /*#__PURE__*/Object.freeze({
411
425
  __proto__: null,
426
+ environmentVisitor: environmentVisitor,
412
427
  explode: explode$1,
413
428
  isExplodedVisitor: isExplodedVisitor,
414
429
  merge: merge,
@@ -462,7 +477,7 @@ const renameVisitor = {
462
477
  if (!path.scope.bindingIdentifierEquals(state.oldName, state.binding.identifier)) {
463
478
  path.skip();
464
479
  if (path.isMethod()) {
465
- requeueComputedKeyAndDecorators(path);
480
+ path.requeueComputedKeyAndDecorators();
466
481
  }
467
482
  }
468
483
  },
@@ -479,7 +494,7 @@ const renameVisitor = {
479
494
  },
480
495
  "AssignmentExpression|Declaration|VariableDeclarator"(path, state) {
481
496
  if (path.isVariableDeclaration()) return;
482
- const ids = path.getOuterBindingIdentifiers();
497
+ const ids = path.isAssignmentExpression() ? path.getAssignmentIdentifiers() : path.getOuterBindingIdentifiers();
483
498
  for (const name in ids) {
484
499
  if (name === state.oldName) ids[name].name = state.newName;
485
500
  }
@@ -507,7 +522,7 @@ class Renamer {
507
522
  if (maybeExportDeclar.isExportAllDeclaration()) {
508
523
  return;
509
524
  }
510
- splitExportDeclaration(maybeExportDeclar);
525
+ maybeExportDeclar.splitExportDeclaration();
511
526
  }
512
527
  maybeConvertFromClassFunctionDeclaration(path) {
513
528
  return path;
@@ -589,13 +604,13 @@ class Binding {
589
604
  }
590
605
  reassign(path) {
591
606
  this.constant = false;
592
- if (this.constantViolations.indexOf(path) !== -1) {
607
+ if (this.constantViolations.includes(path)) {
593
608
  return;
594
609
  }
595
610
  this.constantViolations.push(path);
596
611
  }
597
612
  reference(path) {
598
- if (this.referencePaths.indexOf(path) !== -1) {
613
+ if (this.referencePaths.includes(path)) {
599
614
  return;
600
615
  }
601
616
  this.referenced = true;
@@ -625,8 +640,9 @@ function isDeclaredInLoop(path) {
625
640
 
626
641
  const {
627
642
  NOT_LOCAL_BINDING,
643
+ assignmentExpression: assignmentExpression$3,
628
644
  callExpression: callExpression$3,
629
- cloneNode: cloneNode$3,
645
+ cloneNode: cloneNode$4,
630
646
  getBindingIdentifiers: getBindingIdentifiers$3,
631
647
  identifier: identifier$3,
632
648
  isArrayExpression,
@@ -656,12 +672,13 @@ const {
656
672
  isThisExpression,
657
673
  isUnaryExpression,
658
674
  isVariableDeclaration: isVariableDeclaration$1,
675
+ expressionStatement: expressionStatement$3,
659
676
  matchesPattern: matchesPattern$1,
660
677
  memberExpression: memberExpression$1,
661
678
  numericLiteral: numericLiteral$2,
662
679
  toIdentifier,
663
- variableDeclaration: variableDeclaration$1,
664
- variableDeclarator: variableDeclarator$1,
680
+ variableDeclaration: variableDeclaration$2,
681
+ variableDeclarator: variableDeclarator$2,
665
682
  isRecordExpression,
666
683
  isTupleExpression,
667
684
  isObjectProperty,
@@ -669,7 +686,8 @@ const {
669
686
  isMetaProperty,
670
687
  isPrivateName,
671
688
  isExportDeclaration,
672
- buildUndefinedNode: buildUndefinedNode$1
689
+ buildUndefinedNode: buildUndefinedNode$1,
690
+ sequenceExpression: sequenceExpression$2
673
691
  } = _t;
674
692
  function gatherNodeParts(node, parts) {
675
693
  switch (node?.type) {
@@ -946,7 +964,7 @@ class Scope {
946
964
  this.push({
947
965
  id
948
966
  });
949
- return cloneNode$3(id);
967
+ return cloneNode$4(id);
950
968
  }
951
969
  generateUidIdentifier(name) {
952
970
  return identifier$3(this.generateUid(name));
@@ -1002,7 +1020,7 @@ class Scope {
1002
1020
  this.push({
1003
1021
  id
1004
1022
  });
1005
- return cloneNode$3(id);
1023
+ return cloneNode$4(id);
1006
1024
  }
1007
1025
  return id;
1008
1026
  }
@@ -1125,7 +1143,7 @@ class Scope {
1125
1143
  return buildUndefinedNode$1();
1126
1144
  }
1127
1145
  registerConstantViolation(path) {
1128
- const ids = path.getBindingIdentifiers();
1146
+ const ids = path.getAssignmentIdentifiers();
1129
1147
  for (const name of Object.keys(ids)) {
1130
1148
  this.getBinding(name)?.reassign(path);
1131
1149
  }
@@ -1150,7 +1168,7 @@ class Scope {
1150
1168
  this.checkBlockScopedCollisions(local, kind, name, id);
1151
1169
  }
1152
1170
  if (local) {
1153
- this.registerConstantViolation(bindingPath);
1171
+ local.reassign(bindingPath);
1154
1172
  } else {
1155
1173
  this.bindings[name] = new Binding({
1156
1174
  identifier: id,
@@ -1307,7 +1325,7 @@ class Scope {
1307
1325
  path.traverse(collectorVisitor, state);
1308
1326
  this.crawling = false;
1309
1327
  for (const path of state.assignments) {
1310
- const ids = path.getBindingIdentifiers();
1328
+ const ids = path.getAssignmentIdentifiers();
1311
1329
  for (const name of Object.keys(ids)) {
1312
1330
  if (path.scope.getBinding(name)) continue;
1313
1331
  programParent.addGlobal(ids[name]);
@@ -1357,12 +1375,12 @@ class Scope {
1357
1375
  const dataKey = `declaration:${kind}:${blockHoist}`;
1358
1376
  let declarPath = !unique && path.getData(dataKey);
1359
1377
  if (!declarPath) {
1360
- const declar = variableDeclaration$1(kind, []);
1378
+ const declar = variableDeclaration$2(kind, []);
1361
1379
  declar._blockHoist = blockHoist;
1362
1380
  [declarPath] = path.unshiftContainer("body", [declar]);
1363
1381
  if (!unique) path.setData(dataKey, declarPath);
1364
1382
  }
1365
- const declarator = variableDeclarator$1(id, init);
1383
+ const declarator = variableDeclarator$2(id, init);
1366
1384
  const len = declarPath.node.declarations.push(declarator);
1367
1385
  path.scope.registerBinding(kind, declarPath.get("declarations")[len - 1]);
1368
1386
  }
@@ -1462,16 +1480,23 @@ class Scope {
1462
1480
  }
1463
1481
  hasBinding(name, opts) {
1464
1482
  if (!name) return false;
1465
- if (this.hasOwnBinding(name)) return true;
1466
- {
1467
- if (typeof opts === "boolean") opts = {
1468
- noGlobals: opts
1469
- };
1470
- }
1471
- if (this.parentHasBinding(name, opts)) return true;
1472
- if (!opts?.noUids && this.hasUid(name)) return true;
1473
- if (!opts?.noGlobals && Scope.globals.includes(name)) return true;
1474
- if (!opts?.noGlobals && Scope.contextVariables.includes(name)) return true;
1483
+ let scope = this;
1484
+ do {
1485
+ if (scope.hasOwnBinding(name)) {
1486
+ return true;
1487
+ }
1488
+ } while (scope = scope.parent);
1489
+ let noGlobals;
1490
+ let noUids;
1491
+ if (typeof opts === "object") {
1492
+ noGlobals = opts.noGlobals;
1493
+ noUids = opts.noUids;
1494
+ } else if (typeof opts === "boolean") {
1495
+ noGlobals = opts;
1496
+ }
1497
+ if (!noUids && this.hasUid(name)) return true;
1498
+ if (!noGlobals && Scope.globals.includes(name)) return true;
1499
+ if (!noGlobals && Scope.contextVariables.includes(name)) return true;
1475
1500
  return false;
1476
1501
  }
1477
1502
  parentHasBinding(name, opts) {
@@ -1497,6 +1522,54 @@ class Scope {
1497
1522
  }
1498
1523
  } while (scope = scope.parent);
1499
1524
  }
1525
+ hoistVariables(emit = id => this.push({
1526
+ id
1527
+ })) {
1528
+ this.crawl();
1529
+ const seen = new Set();
1530
+ for (const name of Object.keys(this.bindings)) {
1531
+ const binding = this.bindings[name];
1532
+ if (!binding) continue;
1533
+ const {
1534
+ path
1535
+ } = binding;
1536
+ if (!path.isVariableDeclarator()) continue;
1537
+ const {
1538
+ parent,
1539
+ parentPath
1540
+ } = path;
1541
+ if (parent.kind !== "var" || seen.has(parent)) continue;
1542
+ seen.add(path.parent);
1543
+ let firstId;
1544
+ const init = [];
1545
+ for (const decl of parent.declarations) {
1546
+ firstId ??= decl.id;
1547
+ if (decl.init) {
1548
+ init.push(assignmentExpression$3("=", decl.id, decl.init));
1549
+ }
1550
+ const ids = Object.keys(getBindingIdentifiers$3(decl, false, true, true));
1551
+ for (const name of ids) {
1552
+ emit(identifier$3(name), decl.init != null);
1553
+ }
1554
+ }
1555
+ if (parentPath.parentPath.isFor({
1556
+ left: parent
1557
+ })) {
1558
+ parentPath.replaceWith(firstId);
1559
+ } else if (init.length === 0) {
1560
+ parentPath.remove();
1561
+ } else {
1562
+ const expr = init.length === 1 ? init[0] : sequenceExpression$2(init);
1563
+ if (parentPath.parentPath.isForStatement({
1564
+ init: parent
1565
+ })) {
1566
+ parentPath.replaceWith(expr);
1567
+ } else {
1568
+ parentPath.replaceWith(expressionStatement$3(expr));
1569
+ }
1570
+ }
1571
+ }
1572
+ }
1500
1573
  }
1501
1574
 
1502
1575
  const {
@@ -1670,7 +1743,7 @@ function getTypeAnnotationBindingConstantViolations(binding, path, name) {
1670
1743
  const testType = getConditionalAnnotation(binding, path, name);
1671
1744
  if (testType) {
1672
1745
  const testConstantViolations = getConstantViolationsBefore(binding, testType.ifStatement);
1673
- constantViolations = constantViolations.filter(path => testConstantViolations.indexOf(path) < 0);
1746
+ constantViolations = constantViolations.filter(path => !testConstantViolations.includes(path));
1674
1747
  types.push(testType.typeAnnotation);
1675
1748
  }
1676
1749
  if (constantViolations.length) {
@@ -1712,7 +1785,7 @@ function inferAnnotationFromBinaryExpression(name, path) {
1712
1785
  if (operator === "===") {
1713
1786
  return target.getTypeAnnotation();
1714
1787
  }
1715
- if (BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) {
1788
+ if (BOOLEAN_NUMBER_BINARY_OPERATORS.includes(operator)) {
1716
1789
  return numberTypeAnnotation$1();
1717
1790
  }
1718
1791
  return;
@@ -1830,19 +1903,19 @@ function UnaryExpression(node) {
1830
1903
  const operator = node.operator;
1831
1904
  if (operator === "void") {
1832
1905
  return voidTypeAnnotation$1();
1833
- } else if (NUMBER_UNARY_OPERATORS.indexOf(operator) >= 0) {
1906
+ } else if (NUMBER_UNARY_OPERATORS.includes(operator)) {
1834
1907
  return numberTypeAnnotation();
1835
- } else if (STRING_UNARY_OPERATORS.indexOf(operator) >= 0) {
1908
+ } else if (STRING_UNARY_OPERATORS.includes(operator)) {
1836
1909
  return stringTypeAnnotation$1();
1837
- } else if (BOOLEAN_UNARY_OPERATORS.indexOf(operator) >= 0) {
1910
+ } else if (BOOLEAN_UNARY_OPERATORS.includes(operator)) {
1838
1911
  return booleanTypeAnnotation();
1839
1912
  }
1840
1913
  }
1841
1914
  function BinaryExpression(node) {
1842
1915
  const operator = node.operator;
1843
- if (NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) {
1916
+ if (NUMBER_BINARY_OPERATORS.includes(operator)) {
1844
1917
  return numberTypeAnnotation();
1845
- } else if (BOOLEAN_BINARY_OPERATORS.indexOf(operator) >= 0) {
1918
+ } else if (BOOLEAN_BINARY_OPERATORS.includes(operator)) {
1846
1919
  return booleanTypeAnnotation();
1847
1920
  } else if (operator === "+") {
1848
1921
  const right = this.get("right");
@@ -2011,7 +2084,7 @@ function getTypeAnnotation() {
2011
2084
  if (type != null) {
2012
2085
  return type;
2013
2086
  }
2014
- type = this._getTypeAnnotation() || anyTypeAnnotation();
2087
+ type = _getTypeAnnotation.call(this) || anyTypeAnnotation();
2015
2088
  if (isTypeAnnotation(type) || isTSTypeAnnotation(type)) {
2016
2089
  type = type.typeAnnotation;
2017
2090
  }
@@ -2119,2040 +2192,2186 @@ function isGenericType(genericName) {
2119
2192
  }
2120
2193
 
2121
2194
  const {
2122
- FUNCTION_TYPES,
2123
- arrowFunctionExpression: arrowFunctionExpression$2,
2124
- assignmentExpression: assignmentExpression$2,
2125
- awaitExpression,
2126
- blockStatement: blockStatement$2,
2127
- buildUndefinedNode,
2128
- callExpression: callExpression$2,
2129
- cloneNode: cloneNode$2,
2130
- conditionalExpression: conditionalExpression$1,
2131
- expressionStatement: expressionStatement$2,
2132
- getBindingIdentifiers: getBindingIdentifiers$2,
2133
- identifier: identifier$1,
2134
- inheritLeadingComments,
2135
- inheritTrailingComments,
2136
- inheritsComments,
2137
- isBlockStatement: isBlockStatement$1,
2138
- isEmptyStatement,
2139
- isExpression: isExpression$2,
2140
- isExpressionStatement,
2141
- isIfStatement,
2142
- isProgram,
2143
- isStatement,
2144
- isVariableDeclaration,
2145
- removeComments,
2146
- returnStatement: returnStatement$1,
2147
- sequenceExpression: sequenceExpression$1,
2148
- validate: validate$1,
2149
- yieldExpression
2195
+ react
2150
2196
  } = _t;
2151
- function replaceWithMultiple(nodes) {
2152
- this.resync();
2153
- nodes = this._verifyNodeList(nodes);
2154
- inheritLeadingComments(nodes[0], this.node);
2155
- inheritTrailingComments(nodes[nodes.length - 1], this.node);
2156
- getCachedPaths(this.hub, this.parent)?.delete(this.node);
2157
- this.node = this.container[this.key] = null;
2158
- const paths = this.insertAfter(nodes);
2159
- if (this.node) {
2160
- this.requeue();
2161
- } else {
2162
- this.remove();
2163
- }
2164
- return paths;
2165
- }
2166
- function replaceWithSourceString(replacement) {
2167
- this.resync();
2168
- let ast;
2169
- try {
2170
- replacement = `(${replacement})`;
2171
- ast = parse(replacement);
2172
- } catch (err) {
2173
- const loc = err.loc;
2174
- if (loc) {
2175
- err.message += " - make sure this is an expression.\n" + codeFrameColumns(replacement, {
2176
- start: {
2177
- line: loc.line,
2178
- column: loc.column + 1
2197
+ const {
2198
+ cloneNode: cloneNode$3,
2199
+ jsxExpressionContainer,
2200
+ variableDeclaration: variableDeclaration$1,
2201
+ variableDeclarator: variableDeclarator$1
2202
+ } = _t;
2203
+ const referenceVisitor = {
2204
+ ReferencedIdentifier(path, state) {
2205
+ if (path.isJSXIdentifier() && react.isCompatTag(path.node.name) && !path.parentPath.isJSXMemberExpression()) {
2206
+ return;
2207
+ }
2208
+ if (path.node.name === "this") {
2209
+ let scope = path.scope;
2210
+ do {
2211
+ if (scope.path.isFunction() && !scope.path.isArrowFunctionExpression()) {
2212
+ break;
2179
2213
  }
2180
- });
2181
- err.code = "BABEL_REPLACE_SOURCE_ERROR";
2214
+ } while (scope = scope.parent);
2215
+ if (scope) state.breakOnScopePaths.push(scope.path);
2182
2216
  }
2183
- throw err;
2217
+ const binding = path.scope.getBinding(path.node.name);
2218
+ if (!binding) return;
2219
+ for (const violation of binding.constantViolations) {
2220
+ if (violation.scope !== binding.path.scope) {
2221
+ state.mutableBinding = true;
2222
+ path.stop();
2223
+ return;
2224
+ }
2225
+ }
2226
+ if (binding !== state.scope.getBinding(path.node.name)) return;
2227
+ state.bindings[path.node.name] = binding;
2184
2228
  }
2185
- const expressionAST = ast.program.body[0].expression;
2186
- traverse.removeProperties(expressionAST);
2187
- return this.replaceWith(expressionAST);
2188
- }
2189
- function replaceWith(replacementPath) {
2190
- this.resync();
2191
- if (this.removed) {
2192
- throw new Error("You can't replace this node, we've already removed it");
2229
+ };
2230
+ class PathHoister {
2231
+ breakOnScopePaths;
2232
+ bindings;
2233
+ mutableBinding;
2234
+ scopes;
2235
+ scope;
2236
+ path;
2237
+ attachAfter;
2238
+ constructor(path, scope) {
2239
+ this.breakOnScopePaths = [];
2240
+ this.bindings = {};
2241
+ this.mutableBinding = false;
2242
+ this.scopes = [];
2243
+ this.scope = scope;
2244
+ this.path = path;
2245
+ this.attachAfter = false;
2193
2246
  }
2194
- let replacement = replacementPath instanceof NodePath_Final ? replacementPath.node : replacementPath;
2195
- if (!replacement) {
2196
- throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead");
2247
+ isCompatibleScope(scope) {
2248
+ for (const key of Object.keys(this.bindings)) {
2249
+ const binding = this.bindings[key];
2250
+ if (!scope.bindingIdentifierEquals(key, binding.identifier)) {
2251
+ return false;
2252
+ }
2253
+ }
2254
+ return true;
2197
2255
  }
2198
- if (this.node === replacement) {
2199
- return [this];
2256
+ getCompatibleScopes() {
2257
+ let scope = this.path.scope;
2258
+ do {
2259
+ if (this.isCompatibleScope(scope)) {
2260
+ this.scopes.push(scope);
2261
+ } else {
2262
+ break;
2263
+ }
2264
+ if (this.breakOnScopePaths.includes(scope.path)) {
2265
+ break;
2266
+ }
2267
+ } while (scope = scope.parent);
2200
2268
  }
2201
- if (this.isProgram() && !isProgram(replacement)) {
2202
- throw new Error("You can only replace a Program root node with another Program node");
2269
+ getAttachmentPath() {
2270
+ let path = this._getAttachmentPath();
2271
+ if (!path) return;
2272
+ let targetScope = path.scope;
2273
+ if (targetScope.path === path) {
2274
+ targetScope = path.scope.parent;
2275
+ }
2276
+ if (targetScope.path.isProgram() || targetScope.path.isFunction()) {
2277
+ for (const name of Object.keys(this.bindings)) {
2278
+ if (!targetScope.hasOwnBinding(name)) continue;
2279
+ const binding = this.bindings[name];
2280
+ if (binding.kind === "param" || binding.path.parentKey === "params") {
2281
+ continue;
2282
+ }
2283
+ const bindingParentPath = this.getAttachmentParentForPath(binding.path);
2284
+ if (bindingParentPath.key >= path.key) {
2285
+ this.attachAfter = true;
2286
+ path = binding.path;
2287
+ for (const violationPath of binding.constantViolations) {
2288
+ if (this.getAttachmentParentForPath(violationPath).key > path.key) {
2289
+ path = violationPath;
2290
+ }
2291
+ }
2292
+ }
2293
+ }
2294
+ }
2295
+ return path;
2203
2296
  }
2204
- if (Array.isArray(replacement)) {
2205
- throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`");
2297
+ _getAttachmentPath() {
2298
+ const scopes = this.scopes;
2299
+ const scope = scopes.pop();
2300
+ if (!scope) return;
2301
+ if (scope.path.isFunction()) {
2302
+ if (this.hasOwnParamBindings(scope)) {
2303
+ if (this.scope === scope) return;
2304
+ const bodies = scope.path.get("body").get("body");
2305
+ for (let i = 0; i < bodies.length; i++) {
2306
+ if (bodies[i].node._blockHoist) continue;
2307
+ return bodies[i];
2308
+ }
2309
+ } else {
2310
+ return this.getNextScopeAttachmentParent();
2311
+ }
2312
+ } else if (scope.path.isProgram()) {
2313
+ return this.getNextScopeAttachmentParent();
2314
+ }
2206
2315
  }
2207
- if (typeof replacement === "string") {
2208
- throw new Error("Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`");
2316
+ getNextScopeAttachmentParent() {
2317
+ const scope = this.scopes.pop();
2318
+ if (scope) return this.getAttachmentParentForPath(scope.path);
2209
2319
  }
2210
- let nodePath = "";
2211
- if (this.isNodeType("Statement") && isExpression$2(replacement)) {
2212
- if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement) && !this.parentPath.isExportDefaultDeclaration()) {
2213
- replacement = expressionStatement$2(replacement);
2214
- nodePath = "expression";
2320
+ getAttachmentParentForPath(path) {
2321
+ do {
2322
+ if (!path.parentPath || Array.isArray(path.container) && path.isStatement()) {
2323
+ return path;
2324
+ }
2325
+ } while (path = path.parentPath);
2326
+ }
2327
+ hasOwnParamBindings(scope) {
2328
+ for (const name of Object.keys(this.bindings)) {
2329
+ if (!scope.hasOwnBinding(name)) continue;
2330
+ const binding = this.bindings[name];
2331
+ if (binding.kind === "param" && binding.constant) return true;
2215
2332
  }
2333
+ return false;
2216
2334
  }
2217
- if (this.isNodeType("Expression") && isStatement(replacement)) {
2218
- if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement)) {
2219
- return this.replaceExpressionWithStatements([replacement]);
2335
+ run() {
2336
+ this.path.traverse(referenceVisitor, this);
2337
+ if (this.mutableBinding) return;
2338
+ this.getCompatibleScopes();
2339
+ const attachTo = this.getAttachmentPath();
2340
+ if (!attachTo) return;
2341
+ if (attachTo.getFunctionParent() === this.path.getFunctionParent()) return;
2342
+ let uid = attachTo.scope.generateUidIdentifier("ref");
2343
+ const declarator = variableDeclarator$1(uid, this.path.node);
2344
+ const insertFn = this.attachAfter ? "insertAfter" : "insertBefore";
2345
+ const [attached] = attachTo[insertFn]([attachTo.isVariableDeclarator() ? declarator : variableDeclaration$1("var", [declarator])]);
2346
+ const parent = this.path.parentPath;
2347
+ if (parent.isJSXElement() && this.path.container === parent.node.children) {
2348
+ uid = jsxExpressionContainer(uid);
2220
2349
  }
2350
+ this.path.replaceWith(cloneNode$3(uid));
2351
+ return attachTo.isVariableDeclarator() ? attached.get("init") : attached.get("declarations.0.init");
2221
2352
  }
2222
- const oldNode = this.node;
2223
- if (oldNode) {
2224
- inheritsComments(replacement, oldNode);
2225
- removeComments(oldNode);
2226
- }
2227
- this._replaceWith(replacement);
2228
- this.type = replacement.type;
2229
- this.setScope();
2230
- this.requeue();
2231
- return [nodePath ? this.get(nodePath) : this];
2232
2353
  }
2233
- function _replaceWith(node) {
2234
- if (!this.container) {
2235
- throw new ReferenceError("Container is falsy");
2236
- }
2237
- if (this.inList) {
2238
- validate$1(this.parent, this.key, [node]);
2239
- } else {
2240
- validate$1(this.parent, this.key, node);
2354
+
2355
+ const hooks = [function (self, parent) {
2356
+ const 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();
2357
+ if (removeParent) {
2358
+ parent.remove();
2359
+ return true;
2241
2360
  }
2242
- this.debug(`Replace with ${node?.type}`);
2243
- getCachedPaths(this.hub, this.parent)?.set(node, this).delete(this.node);
2244
- this.node = this.container[this.key] = node;
2245
- }
2246
- function replaceExpressionWithStatements(nodes) {
2247
- this.resync();
2248
- const declars = [];
2249
- const nodesAsSingleExpression = gatherSequenceExpressions(nodes, declars);
2250
- if (nodesAsSingleExpression) {
2251
- for (const id of declars) this.scope.push({
2252
- id
2253
- });
2254
- return this.replaceWith(nodesAsSingleExpression)[0].get("expressions");
2361
+ }, function (self, parent) {
2362
+ if (parent.isSequenceExpression() && parent.node.expressions.length === 1) {
2363
+ parent.replaceWith(parent.node.expressions[0]);
2364
+ return true;
2255
2365
  }
2256
- const functionParent = this.getFunctionParent();
2257
- const isParentAsync = functionParent?.is("async");
2258
- const isParentGenerator = functionParent?.is("generator");
2259
- const container = arrowFunctionExpression$2([], blockStatement$2(nodes));
2260
- this.replaceWith(callExpression$2(container, []));
2261
- const callee = this.get("callee");
2262
- hoistVariables(callee.get("body"), id => {
2263
- this.scope.push({
2264
- id
2265
- });
2266
- }, "var");
2267
- const completionRecords = this.get("callee").getCompletionRecords();
2268
- for (const path of completionRecords) {
2269
- if (!path.isExpressionStatement()) continue;
2270
- const loop = path.findParent(path => path.isLoop());
2271
- if (loop) {
2272
- let uid = loop.getData("expressionReplacementReturnUid");
2273
- if (!uid) {
2274
- uid = callee.scope.generateDeclaredUidIdentifier("ret");
2275
- callee.get("body").pushContainer("body", returnStatement$1(cloneNode$2(uid)));
2276
- loop.setData("expressionReplacementReturnUid", uid);
2277
- } else {
2278
- uid = identifier$1(uid.name);
2279
- }
2280
- path.get("expression").replaceWith(assignmentExpression$2("=", cloneNode$2(uid), path.node.expression));
2366
+ }, function (self, parent) {
2367
+ if (parent.isBinary()) {
2368
+ if (self.key === "left") {
2369
+ parent.replaceWith(parent.node.right);
2281
2370
  } else {
2282
- path.replaceWith(returnStatement$1(path.node.expression));
2371
+ parent.replaceWith(parent.node.left);
2283
2372
  }
2373
+ return true;
2284
2374
  }
2285
- callee.arrowFunctionToExpression();
2286
- const newCallee = callee;
2287
- const needToAwaitFunction = isParentAsync && traverse.hasType(this.get("callee.body").node, "AwaitExpression", FUNCTION_TYPES);
2288
- const needToYieldFunction = isParentGenerator && traverse.hasType(this.get("callee.body").node, "YieldExpression", FUNCTION_TYPES);
2289
- if (needToAwaitFunction) {
2290
- newCallee.set("async", true);
2291
- if (!needToYieldFunction) {
2292
- this.replaceWith(awaitExpression(this.node));
2293
- }
2375
+ }, function (self, parent) {
2376
+ if (parent.isIfStatement() && self.key === "consequent" || self.key === "body" && (parent.isLoop() || parent.isArrowFunctionExpression())) {
2377
+ self.replaceWith({
2378
+ type: "BlockStatement",
2379
+ body: []
2380
+ });
2381
+ return true;
2294
2382
  }
2295
- if (needToYieldFunction) {
2296
- newCallee.set("generator", true);
2297
- this.replaceWith(yieldExpression(this.node, true));
2383
+ }];
2384
+
2385
+ const {
2386
+ getBindingIdentifiers: getBindingIdentifiers$2
2387
+ } = _t;
2388
+ function remove() {
2389
+ _assertUnremoved.call(this);
2390
+ this.resync();
2391
+ if (!this.opts?.noScope) {
2392
+ _removeFromScope.call(this);
2298
2393
  }
2299
- return newCallee.get("body.body");
2394
+ if (_callRemovalHooks.call(this)) {
2395
+ _markRemoved.call(this);
2396
+ return;
2397
+ }
2398
+ this.shareCommentsWithSiblings();
2399
+ _remove.call(this);
2400
+ _markRemoved.call(this);
2300
2401
  }
2301
- function gatherSequenceExpressions(nodes, declars) {
2302
- const exprs = [];
2303
- let ensureLastUndefined = true;
2304
- for (const node of nodes) {
2305
- if (!isEmptyStatement(node)) {
2306
- ensureLastUndefined = false;
2307
- }
2308
- if (isExpression$2(node)) {
2309
- exprs.push(node);
2310
- } else if (isExpressionStatement(node)) {
2311
- exprs.push(node.expression);
2312
- } else if (isVariableDeclaration(node)) {
2313
- if (node.kind !== "var") return;
2314
- for (const declar of node.declarations) {
2315
- const bindings = getBindingIdentifiers$2(declar);
2316
- for (const key of Object.keys(bindings)) {
2317
- declars.push(cloneNode$2(bindings[key]));
2318
- }
2319
- if (declar.init) {
2320
- exprs.push(assignmentExpression$2("=", declar.id, declar.init));
2321
- }
2322
- }
2323
- ensureLastUndefined = true;
2324
- } else if (isIfStatement(node)) {
2325
- const consequent = node.consequent ? gatherSequenceExpressions([node.consequent], declars) : buildUndefinedNode();
2326
- const alternate = node.alternate ? gatherSequenceExpressions([node.alternate], declars) : buildUndefinedNode();
2327
- if (!consequent || !alternate) return;
2328
- exprs.push(conditionalExpression$1(node.test, consequent, alternate));
2329
- } else if (isBlockStatement$1(node)) {
2330
- const body = gatherSequenceExpressions(node.body, declars);
2331
- if (!body) return;
2332
- exprs.push(body);
2333
- } else if (isEmptyStatement(node)) {
2334
- if (nodes.indexOf(node) === 0) {
2335
- ensureLastUndefined = true;
2336
- }
2337
- } else {
2338
- return;
2402
+ function _removeFromScope() {
2403
+ const bindings = getBindingIdentifiers$2(this.node, false, false, true);
2404
+ Object.keys(bindings).forEach(name => this.scope.removeBinding(name));
2405
+ }
2406
+ function _callRemovalHooks() {
2407
+ if (this.parentPath) {
2408
+ for (const fn of hooks) {
2409
+ if (fn(this, this.parentPath)) return true;
2339
2410
  }
2340
2411
  }
2341
- if (ensureLastUndefined) exprs.push(buildUndefinedNode());
2342
- if (exprs.length === 1) {
2343
- return exprs[0];
2344
- } else {
2345
- return sequenceExpression$1(exprs);
2346
- }
2347
2412
  }
2348
- function replaceInline(nodes) {
2349
- this.resync();
2350
- if (Array.isArray(nodes)) {
2351
- if (Array.isArray(this.container)) {
2352
- nodes = this._verifyNodeList(nodes);
2353
- const paths = this._containerInsertAfter(nodes);
2354
- this.remove();
2355
- return paths;
2356
- } else {
2357
- return this.replaceWithMultiple(nodes);
2358
- }
2413
+ function _remove() {
2414
+ if (Array.isArray(this.container)) {
2415
+ this.container.splice(this.key, 1);
2416
+ this.updateSiblingKeys(this.key, -1);
2359
2417
  } else {
2360
- return this.replaceWith(nodes);
2418
+ _replaceWith.call(this, null);
2361
2419
  }
2362
2420
  }
2363
-
2364
- const VALID_OBJECT_CALLEES = ["Number", "String", "Math"];
2365
- const VALID_IDENTIFIER_CALLEES = ["isFinite", "isNaN", "parseFloat", "parseInt", "decodeURI", "decodeURIComponent", "encodeURI", "encodeURIComponent", "btoa", "atob"];
2366
- const INVALID_METHODS = ["random"];
2367
- function isValidObjectCallee(val) {
2368
- return VALID_OBJECT_CALLEES.includes(val);
2369
- }
2370
- function isValidIdentifierCallee(val) {
2371
- return VALID_IDENTIFIER_CALLEES.includes(val);
2372
- }
2373
- function isInvalidMethod(val) {
2374
- return INVALID_METHODS.includes(val);
2421
+ function _markRemoved() {
2422
+ this._traverseFlags |= SHOULD_SKIP | REMOVED;
2423
+ if (this.parent) {
2424
+ getCachedPaths(this.hub, this.parent).delete(this.node);
2425
+ }
2426
+ this.node = null;
2375
2427
  }
2376
- function evaluateTruthy() {
2377
- const res = this.evaluate();
2378
- if (res.confident) return !!res.value;
2428
+ function _assertUnremoved() {
2429
+ if (this.removed) {
2430
+ throw this.buildCodeFrameError("NodePath has been removed so is read-only.");
2431
+ }
2379
2432
  }
2380
- function deopt(path, state) {
2381
- if (!state.confident) return;
2382
- state.deoptPath = path;
2383
- state.confident = false;
2433
+
2434
+ function call(key) {
2435
+ const opts = this.opts;
2436
+ this.debug(key);
2437
+ if (this.node) {
2438
+ if (_call.call(this, opts[key])) return true;
2439
+ }
2440
+ if (this.node) {
2441
+ return _call.call(this, opts[this.node.type]?.[key]);
2442
+ }
2443
+ return false;
2384
2444
  }
2385
- const Globals = new Map([["undefined", undefined], ["Infinity", Infinity], ["NaN", NaN]]);
2386
- function evaluateCached(path, state) {
2387
- const {
2388
- node
2389
- } = path;
2390
- const {
2391
- seen
2392
- } = state;
2393
- if (seen.has(node)) {
2394
- const existing = seen.get(node);
2395
- if (existing.resolved) {
2396
- return existing.value;
2397
- } else {
2398
- deopt(path, state);
2399
- return;
2445
+ function _call(fns) {
2446
+ if (!fns) return false;
2447
+ for (const fn of fns) {
2448
+ if (!fn) continue;
2449
+ const node = this.node;
2450
+ if (!node) return true;
2451
+ const ret = fn.call(this.state, this, this.state);
2452
+ if (ret && typeof ret === "object" && typeof ret.then === "function") {
2453
+ throw new Error(`You appear to be using a plugin with an async traversal visitor, ` + `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.`);
2400
2454
  }
2401
- } else {
2402
- const item = {
2403
- resolved: false
2404
- };
2405
- seen.set(node, item);
2406
- const val = _evaluate(path, state);
2407
- if (state.confident) {
2408
- item.resolved = true;
2409
- item.value = val;
2455
+ if (ret) {
2456
+ throw new Error(`Unexpected return value from visitor method ${fn}`);
2410
2457
  }
2411
- return val;
2458
+ if (this.node !== node) return true;
2459
+ if (this._traverseFlags > 0) return true;
2412
2460
  }
2461
+ return false;
2413
2462
  }
2414
- function _evaluate(path, state) {
2415
- if (!state.confident) return;
2416
- if (path.isSequenceExpression()) {
2417
- const exprs = path.get("expressions");
2418
- return evaluateCached(exprs[exprs.length - 1], state);
2463
+ function isDenylisted() {
2464
+ const denylist = this.opts.denylist ?? this.opts.blacklist;
2465
+ return denylist && denylist.indexOf(this.node.type) > -1;
2466
+ }
2467
+ function restoreContext(path, context) {
2468
+ if (path.context !== context) {
2469
+ path.context = context;
2470
+ path.state = context.state;
2471
+ path.opts = context.opts;
2419
2472
  }
2420
- if (path.isStringLiteral() || path.isNumericLiteral() || path.isBooleanLiteral()) {
2421
- return path.node.value;
2473
+ }
2474
+ function visit() {
2475
+ if (!this.node) {
2476
+ return false;
2422
2477
  }
2423
- if (path.isNullLiteral()) {
2424
- return null;
2478
+ if (this.isDenylisted()) {
2479
+ return false;
2425
2480
  }
2426
- if (path.isTemplateLiteral()) {
2427
- return evaluateQuasis(path, path.node.quasis, state);
2481
+ if (this.opts.shouldSkip?.(this)) {
2482
+ return false;
2428
2483
  }
2429
- if (path.isTaggedTemplateExpression() && path.get("tag").isMemberExpression()) {
2430
- const object = path.get("tag.object");
2431
- const {
2432
- node: {
2433
- name
2434
- }
2435
- } = object;
2436
- const property = path.get("tag.property");
2437
- if (object.isIdentifier() && name === "String" && !path.scope.getBinding(name) && property.isIdentifier() && property.node.name === "raw") {
2438
- return evaluateQuasis(path, path.node.quasi.quasis, state, true);
2439
- }
2484
+ const currentContext = this.context;
2485
+ if (this.shouldSkip || this.call("enter")) {
2486
+ this.debug("Skip...");
2487
+ return this.shouldStop;
2440
2488
  }
2441
- if (path.isConditionalExpression()) {
2442
- const testResult = evaluateCached(path.get("test"), state);
2443
- if (!state.confident) return;
2444
- if (testResult) {
2445
- return evaluateCached(path.get("consequent"), state);
2446
- } else {
2447
- return evaluateCached(path.get("alternate"), state);
2448
- }
2489
+ restoreContext(this, currentContext);
2490
+ this.debug("Recursing into...");
2491
+ this.shouldStop = traverseNode(this.node, this.opts, this.scope, this.state, this, this.skipKeys);
2492
+ restoreContext(this, currentContext);
2493
+ this.call("exit");
2494
+ return this.shouldStop;
2495
+ }
2496
+ function skip() {
2497
+ this.shouldSkip = true;
2498
+ }
2499
+ function skipKey(key) {
2500
+ if (this.skipKeys == null) {
2501
+ this.skipKeys = {};
2449
2502
  }
2450
- if (path.isExpressionWrapper()) {
2451
- return evaluateCached(path.get("expression"), state);
2503
+ this.skipKeys[key] = true;
2504
+ }
2505
+ function stop() {
2506
+ this._traverseFlags |= SHOULD_SKIP | SHOULD_STOP;
2507
+ }
2508
+ function setScope() {
2509
+ if (this.opts?.noScope) return;
2510
+ let path = this.parentPath;
2511
+ if ((this.key === "key" || this.listKey === "decorators") && path.isMethod() || this.key === "discriminant" && path.isSwitchStatement()) {
2512
+ path = path.parentPath;
2452
2513
  }
2453
- if (path.isMemberExpression() && !path.parentPath.isCallExpression({
2454
- callee: path.node
2455
- })) {
2456
- const property = path.get("property");
2457
- const object = path.get("object");
2458
- if (object.isLiteral()) {
2459
- const value = object.node.value;
2460
- const type = typeof value;
2461
- let key = null;
2462
- if (path.node.computed) {
2463
- key = evaluateCached(property, state);
2464
- if (!state.confident) return;
2465
- } else if (property.isIdentifier()) {
2466
- key = property.node.name;
2467
- }
2468
- if ((type === "number" || type === "string") && key != null && (typeof key === "number" || typeof key === "string")) {
2469
- return value[key];
2470
- }
2471
- }
2514
+ let target;
2515
+ while (path && !target) {
2516
+ if (path.opts?.noScope) return;
2517
+ target = path.scope;
2518
+ path = path.parentPath;
2472
2519
  }
2473
- if (path.isReferencedIdentifier()) {
2474
- const binding = path.scope.getBinding(path.node.name);
2475
- if (binding) {
2476
- if (binding.constantViolations.length > 0 || path.node.start < binding.path.node.end) {
2477
- deopt(binding.path, state);
2478
- return;
2479
- }
2480
- if (binding.hasValue) {
2481
- return binding.value;
2482
- }
2483
- }
2484
- const name = path.node.name;
2485
- if (Globals.has(name)) {
2486
- if (!binding) {
2487
- return Globals.get(name);
2488
- }
2489
- deopt(binding.path, state);
2490
- return;
2491
- }
2492
- const resolved = path.resolve();
2493
- if (resolved === path) {
2494
- deopt(path, state);
2495
- return;
2496
- } else {
2497
- return evaluateCached(resolved, state);
2498
- }
2520
+ this.scope = this.getScope(target);
2521
+ this.scope?.init();
2522
+ }
2523
+ function setContext(context) {
2524
+ if (this.skipKeys != null) {
2525
+ this.skipKeys = {};
2499
2526
  }
2500
- if (path.isUnaryExpression({
2501
- prefix: true
2502
- })) {
2503
- if (path.node.operator === "void") {
2504
- return undefined;
2505
- }
2506
- const argument = path.get("argument");
2507
- if (path.node.operator === "typeof" && (argument.isFunction() || argument.isClass())) {
2508
- return "function";
2509
- }
2510
- const arg = evaluateCached(argument, state);
2511
- if (!state.confident) return;
2512
- switch (path.node.operator) {
2513
- case "!":
2514
- return !arg;
2515
- case "+":
2516
- return +arg;
2517
- case "-":
2518
- return -arg;
2519
- case "~":
2520
- return ~arg;
2521
- case "typeof":
2522
- return typeof arg;
2523
- }
2527
+ this._traverseFlags = 0;
2528
+ if (context) {
2529
+ this.context = context;
2530
+ this.state = context.state;
2531
+ this.opts = context.opts;
2524
2532
  }
2525
- if (path.isArrayExpression()) {
2526
- const arr = [];
2527
- const elems = path.get("elements");
2528
- for (const elem of elems) {
2529
- const elemValue = elem.evaluate();
2530
- if (elemValue.confident) {
2531
- arr.push(elemValue.value);
2532
- } else {
2533
- deopt(elemValue.deopt, state);
2534
- return;
2535
- }
2536
- }
2537
- return arr;
2533
+ this.setScope();
2534
+ return this;
2535
+ }
2536
+ function resync() {
2537
+ if (this.removed) return;
2538
+ _resyncParent.call(this);
2539
+ _resyncList.call(this);
2540
+ _resyncKey.call(this);
2541
+ }
2542
+ function _resyncParent() {
2543
+ if (this.parentPath) {
2544
+ this.parent = this.parentPath.node;
2538
2545
  }
2539
- if (path.isObjectExpression()) {
2540
- const obj = {};
2541
- const props = path.get("properties");
2542
- for (const prop of props) {
2543
- if (prop.isObjectMethod() || prop.isSpreadElement()) {
2544
- deopt(prop, state);
2546
+ }
2547
+ function _resyncKey() {
2548
+ if (!this.container) return;
2549
+ if (this.node === this.container[this.key]) {
2550
+ return;
2551
+ }
2552
+ if (Array.isArray(this.container)) {
2553
+ for (let i = 0; i < this.container.length; i++) {
2554
+ if (this.container[i] === this.node) {
2555
+ this.setKey(i);
2545
2556
  return;
2546
2557
  }
2547
- const keyPath = prop.get("key");
2548
- let key;
2549
- if (prop.node.computed) {
2550
- key = keyPath.evaluate();
2551
- if (!key.confident) {
2552
- deopt(key.deopt, state);
2553
- return;
2554
- }
2555
- key = key.value;
2556
- } else if (keyPath.isIdentifier()) {
2557
- key = keyPath.node.name;
2558
- } else {
2559
- key = keyPath.node.value;
2560
- }
2561
- const valuePath = prop.get("value");
2562
- let value = valuePath.evaluate();
2563
- if (!value.confident) {
2564
- deopt(value.deopt, state);
2558
+ }
2559
+ } else {
2560
+ for (const key of Object.keys(this.container)) {
2561
+ if (this.container[key] === this.node) {
2562
+ this.setKey(key);
2565
2563
  return;
2566
2564
  }
2567
- value = value.value;
2568
- obj[key] = value;
2569
2565
  }
2570
- return obj;
2571
2566
  }
2572
- if (path.isLogicalExpression()) {
2573
- const wasConfident = state.confident;
2574
- const left = evaluateCached(path.get("left"), state);
2575
- const leftConfident = state.confident;
2576
- state.confident = wasConfident;
2577
- const right = evaluateCached(path.get("right"), state);
2578
- const rightConfident = state.confident;
2579
- switch (path.node.operator) {
2580
- case "||":
2581
- state.confident = leftConfident && (!!left || rightConfident);
2582
- if (!state.confident) return;
2583
- return left || right;
2584
- case "&&":
2585
- state.confident = leftConfident && (!left || rightConfident);
2586
- if (!state.confident) return;
2587
- return left && right;
2588
- case "??":
2589
- state.confident = leftConfident && (left != null || rightConfident);
2590
- if (!state.confident) return;
2591
- return left ?? right;
2592
- }
2567
+ this.key = null;
2568
+ }
2569
+ function _resyncList() {
2570
+ if (!this.parent || !this.inList) return;
2571
+ const newContainer = this.parent[this.listKey];
2572
+ if (this.container === newContainer) return;
2573
+ this.container = newContainer || null;
2574
+ }
2575
+ function popContext() {
2576
+ this.contexts.pop();
2577
+ if (this.contexts.length > 0) {
2578
+ this.setContext(this.contexts[this.contexts.length - 1]);
2579
+ } else {
2580
+ this.setContext(undefined);
2593
2581
  }
2594
- if (path.isBinaryExpression()) {
2595
- const left = evaluateCached(path.get("left"), state);
2596
- if (!state.confident) return;
2597
- const right = evaluateCached(path.get("right"), state);
2598
- if (!state.confident) return;
2599
- switch (path.node.operator) {
2600
- case "-":
2601
- return left - right;
2602
- case "+":
2603
- return left + right;
2604
- case "/":
2605
- return left / right;
2606
- case "*":
2607
- return left * right;
2608
- case "%":
2609
- return left % right;
2610
- case "**":
2611
- return left ** right;
2612
- case "<":
2613
- return left < right;
2614
- case ">":
2615
- return left > right;
2616
- case "<=":
2617
- return left <= right;
2618
- case ">=":
2619
- return left >= right;
2620
- case "==":
2621
- return left == right;
2622
- case "!=":
2623
- return left != right;
2624
- case "===":
2625
- return left === right;
2626
- case "!==":
2627
- return left !== right;
2628
- case "|":
2629
- return left | right;
2630
- case "&":
2631
- return left & right;
2632
- case "^":
2633
- return left ^ right;
2634
- case "<<":
2635
- return left << right;
2636
- case ">>":
2637
- return left >> right;
2638
- case ">>>":
2639
- return left >>> right;
2640
- }
2582
+ }
2583
+ function pushContext(context) {
2584
+ this.contexts.push(context);
2585
+ this.setContext(context);
2586
+ }
2587
+ function setup(parentPath, container, listKey, key) {
2588
+ this.listKey = listKey;
2589
+ this.container = container;
2590
+ this.parentPath = parentPath || this.parentPath;
2591
+ this.setKey(key);
2592
+ }
2593
+ function setKey(key) {
2594
+ this.key = key;
2595
+ this.node = this.container[this.key];
2596
+ this.type = this.node?.type;
2597
+ }
2598
+ function requeue(pathToQueue = this) {
2599
+ if (pathToQueue.removed) return;
2600
+ {
2601
+ pathToQueue.shouldSkip = false;
2641
2602
  }
2642
- if (path.isCallExpression()) {
2643
- const callee = path.get("callee");
2644
- let context;
2645
- let func;
2646
- if (callee.isIdentifier() && !path.scope.getBinding(callee.node.name) && (isValidObjectCallee(callee.node.name) || isValidIdentifierCallee(callee.node.name))) {
2647
- func = global[callee.node.name];
2648
- }
2649
- if (callee.isMemberExpression()) {
2650
- const object = callee.get("object");
2651
- const property = callee.get("property");
2652
- if (object.isIdentifier() && property.isIdentifier() && isValidObjectCallee(object.node.name) && !isInvalidMethod(property.node.name)) {
2653
- context = global[object.node.name];
2654
- const key = property.node.name;
2655
- if (Object.hasOwn(context, key)) {
2656
- func = context[key];
2657
- }
2658
- }
2659
- if (object.isLiteral() && property.isIdentifier()) {
2660
- const type = typeof object.node.value;
2661
- if (type === "string" || type === "number") {
2662
- context = object.node.value;
2663
- func = context[property.node.name];
2664
- }
2665
- }
2666
- }
2667
- if (func) {
2668
- const args = path.get("arguments").map(arg => evaluateCached(arg, state));
2669
- if (!state.confident) return;
2670
- return func.apply(context, args);
2671
- }
2603
+ const contexts = this.contexts;
2604
+ for (const context of contexts) {
2605
+ context.maybeQueue(pathToQueue);
2672
2606
  }
2673
- deopt(path, state);
2674
2607
  }
2675
- function evaluateQuasis(path, quasis, state, raw = false) {
2676
- let str = "";
2677
- let i = 0;
2678
- const exprs = path.isTemplateLiteral() ? path.get("expressions") : path.get("quasi.expressions");
2679
- for (const elem of quasis) {
2680
- if (!state.confident) break;
2681
- str += raw ? elem.value.raw : elem.value.cooked;
2682
- const expr = exprs[i++];
2683
- if (expr) str += String(evaluateCached(expr, state));
2608
+ function requeueComputedKeyAndDecorators() {
2609
+ const {
2610
+ context,
2611
+ node
2612
+ } = this;
2613
+ if (!_t.isPrivate(node) && node.computed) {
2614
+ context.maybeQueue(this.get("key"));
2615
+ }
2616
+ if (node.decorators) {
2617
+ for (const decorator of this.get("decorators")) {
2618
+ context.maybeQueue(decorator);
2619
+ }
2684
2620
  }
2685
- if (!state.confident) return;
2686
- return str;
2687
2621
  }
2688
- function evaluate() {
2689
- const state = {
2690
- confident: true,
2691
- deoptPath: null,
2692
- seen: new Map()
2693
- };
2694
- let value = evaluateCached(this, state);
2695
- if (!state.confident) value = undefined;
2696
- return {
2697
- confident: state.confident,
2698
- deopt: state.deoptPath,
2699
- value: value
2700
- };
2622
+ function _getQueueContexts() {
2623
+ let path = this;
2624
+ let contexts = this.contexts;
2625
+ while (!contexts.length) {
2626
+ path = path.parentPath;
2627
+ if (!path) break;
2628
+ contexts = path.contexts;
2629
+ }
2630
+ return contexts;
2701
2631
  }
2702
2632
 
2703
2633
  const {
2704
- arrowFunctionExpression: arrowFunctionExpression$1,
2705
- assignmentExpression: assignmentExpression$1,
2706
- binaryExpression,
2707
- blockStatement: blockStatement$1,
2708
- callExpression: callExpression$1,
2709
- conditionalExpression,
2710
- expressionStatement: expressionStatement$1,
2711
- identifier,
2634
+ arrowFunctionExpression: arrowFunctionExpression$2,
2635
+ assertExpression,
2636
+ assignmentExpression: assignmentExpression$2,
2637
+ blockStatement: blockStatement$2,
2638
+ callExpression: callExpression$2,
2639
+ cloneNode: cloneNode$2,
2640
+ expressionStatement: expressionStatement$2,
2641
+ isAssignmentExpression,
2642
+ isCallExpression,
2643
+ isExportNamedDeclaration,
2644
+ isExpression: isExpression$2,
2712
2645
  isIdentifier: isIdentifier$2,
2713
- jsxIdentifier,
2714
- logicalExpression,
2715
- LOGICAL_OPERATORS,
2716
- memberExpression,
2717
- metaProperty,
2718
- numericLiteral: numericLiteral$1,
2719
- objectExpression,
2720
- restElement,
2721
- returnStatement,
2722
- sequenceExpression,
2723
- spreadElement,
2724
- stringLiteral,
2725
- super: _super,
2726
- thisExpression: thisExpression$1,
2727
- toExpression,
2728
- unaryExpression: unaryExpression$1
2646
+ isSequenceExpression,
2647
+ isSuper,
2648
+ thisExpression: thisExpression$1
2729
2649
  } = _t;
2730
- function toComputedKey() {
2731
- let key;
2732
- if (this.isMemberExpression()) {
2733
- key = this.node.property;
2734
- } else if (this.isProperty() || this.isMethod()) {
2735
- key = this.node.key;
2650
+ function insertBefore(nodes_) {
2651
+ _assertUnremoved.call(this);
2652
+ const nodes = _verifyNodeList.call(this, nodes_);
2653
+ const {
2654
+ parentPath,
2655
+ parent
2656
+ } = this;
2657
+ if (parentPath.isExpressionStatement() || parentPath.isLabeledStatement() || isExportNamedDeclaration(parent) || parentPath.isExportDefaultDeclaration() && this.isDeclaration()) {
2658
+ return parentPath.insertBefore(nodes);
2659
+ } else if (this.isNodeType("Expression") && !this.isJSXElement() || parentPath.isForStatement() && this.key === "init") {
2660
+ if (this.node) nodes.push(this.node);
2661
+ return this.replaceExpressionWithStatements(nodes);
2662
+ } else if (Array.isArray(this.container)) {
2663
+ return _containerInsertBefore.call(this, nodes);
2664
+ } else if (this.isStatementOrBlock()) {
2665
+ const node = this.node;
2666
+ const shouldInsertCurrentNode = node && (!this.isExpressionStatement() || node.expression != null);
2667
+ this.replaceWith(blockStatement$2(shouldInsertCurrentNode ? [node] : []));
2668
+ return this.unshiftContainer("body", nodes);
2736
2669
  } else {
2737
- throw new ReferenceError("todo");
2738
- }
2739
- if (!this.node.computed) {
2740
- if (isIdentifier$2(key)) key = stringLiteral(key.name);
2670
+ 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?");
2741
2671
  }
2742
- return key;
2743
2672
  }
2744
- function ensureBlock() {
2745
- const body = this.get("body");
2746
- const bodyNode = body.node;
2747
- if (Array.isArray(body)) {
2748
- throw new Error("Can't convert array path to a block statement");
2749
- }
2750
- if (!bodyNode) {
2751
- throw new Error("Can't convert node without a body");
2752
- }
2753
- if (body.isBlockStatement()) {
2754
- return bodyNode;
2673
+ function _containerInsert(from, nodes) {
2674
+ this.updateSiblingKeys(from, nodes.length);
2675
+ const paths = [];
2676
+ this.container.splice(from, 0, ...nodes);
2677
+ for (let i = 0; i < nodes.length; i++) {
2678
+ const to = from + i;
2679
+ const path = this.getSibling(to);
2680
+ paths.push(path);
2681
+ if (this.context?.queue) {
2682
+ path.pushContext(this.context);
2683
+ }
2755
2684
  }
2756
- const statements = [];
2757
- let stringPath = "body";
2758
- let key;
2759
- let listKey;
2760
- if (body.isStatement()) {
2761
- listKey = "body";
2762
- key = 0;
2763
- statements.push(body.node);
2764
- } else {
2765
- stringPath += ".body.0";
2766
- if (this.isFunction()) {
2767
- key = "argument";
2768
- statements.push(returnStatement(body.node));
2769
- } else {
2770
- key = "expression";
2771
- statements.push(expressionStatement$1(body.node));
2685
+ const contexts = _getQueueContexts.call(this);
2686
+ for (const path of paths) {
2687
+ path.setScope();
2688
+ path.debug("Inserted.");
2689
+ for (const context of contexts) {
2690
+ context.maybeQueue(path, true);
2772
2691
  }
2773
2692
  }
2774
- this.node.body = blockStatement$1(statements);
2775
- const parentPath = this.get(stringPath);
2776
- body.setup(parentPath, listKey ? parentPath.node[listKey] : parentPath.node, listKey, key);
2777
- return this.node;
2693
+ return paths;
2778
2694
  }
2779
- function unwrapFunctionEnvironment() {
2780
- if (!this.isArrowFunctionExpression() && !this.isFunctionExpression() && !this.isFunctionDeclaration()) {
2781
- throw this.buildCodeFrameError("Can only unwrap the environment of a function.");
2782
- }
2783
- hoistFunctionEnvironment(this);
2695
+ function _containerInsertBefore(nodes) {
2696
+ return _containerInsert.call(this, this.key, nodes);
2784
2697
  }
2785
- function setType(path, type) {
2786
- path.node.type = type;
2698
+ function _containerInsertAfter(nodes) {
2699
+ return _containerInsert.call(this, this.key + 1, nodes);
2787
2700
  }
2788
- function arrowFunctionToExpression({
2789
- allowInsertArrow = true,
2790
- allowInsertArrowWithRest = allowInsertArrow,
2791
- noNewArrows = true
2792
- } = {}) {
2793
- if (!this.isArrowFunctionExpression()) {
2794
- throw this.buildCodeFrameError("Cannot convert non-arrow function to a function expression.");
2701
+ const last = arr => arr[arr.length - 1];
2702
+ function isHiddenInSequenceExpression(path) {
2703
+ return isSequenceExpression(path.parent) && (last(path.parent.expressions) !== path.node || isHiddenInSequenceExpression(path.parentPath));
2704
+ }
2705
+ function isAlmostConstantAssignment(node, scope) {
2706
+ if (!isAssignmentExpression(node) || !isIdentifier$2(node.left)) {
2707
+ return false;
2708
+ }
2709
+ const blockScope = scope.getBlockParent();
2710
+ return blockScope.hasOwnBinding(node.left.name) && blockScope.getOwnBinding(node.left.name).constantViolations.length <= 1;
2711
+ }
2712
+ function insertAfter(nodes_) {
2713
+ _assertUnremoved.call(this);
2714
+ if (this.isSequenceExpression()) {
2715
+ return last(this.get("expressions")).insertAfter(nodes_);
2795
2716
  }
2717
+ const nodes = _verifyNodeList.call(this, nodes_);
2796
2718
  const {
2797
- thisBinding,
2798
- fnPath: fn
2799
- } = hoistFunctionEnvironment(this, noNewArrows, allowInsertArrow, allowInsertArrowWithRest);
2800
- fn.ensureBlock();
2801
- setType(fn, "FunctionExpression");
2802
- if (!noNewArrows) {
2803
- const checkBinding = thisBinding ? null : fn.scope.generateUidIdentifier("arrowCheckId");
2804
- if (checkBinding) {
2805
- fn.parentPath.scope.push({
2806
- id: checkBinding,
2807
- init: objectExpression([])
2808
- });
2719
+ parentPath,
2720
+ parent
2721
+ } = this;
2722
+ if (parentPath.isExpressionStatement() || parentPath.isLabeledStatement() || isExportNamedDeclaration(parent) || parentPath.isExportDefaultDeclaration() && this.isDeclaration()) {
2723
+ return parentPath.insertAfter(nodes.map(node => {
2724
+ return isExpression$2(node) ? expressionStatement$2(node) : node;
2725
+ }));
2726
+ } else if (this.isNodeType("Expression") && !this.isJSXElement() && !parentPath.isJSXElement() || parentPath.isForStatement() && this.key === "init") {
2727
+ const self = this;
2728
+ if (self.node) {
2729
+ const node = self.node;
2730
+ let {
2731
+ scope
2732
+ } = this;
2733
+ if (scope.path.isPattern()) {
2734
+ assertExpression(node);
2735
+ self.replaceWith(callExpression$2(arrowFunctionExpression$2([], node), []));
2736
+ self.get("callee.body").insertAfter(nodes);
2737
+ return [self];
2738
+ }
2739
+ if (isHiddenInSequenceExpression(self)) {
2740
+ nodes.unshift(node);
2741
+ } else if (isCallExpression(node) && isSuper(node.callee)) {
2742
+ nodes.unshift(node);
2743
+ nodes.push(thisExpression$1());
2744
+ } else if (isAlmostConstantAssignment(node, scope)) {
2745
+ nodes.unshift(node);
2746
+ nodes.push(cloneNode$2(node.left));
2747
+ } else if (scope.isPure(node, true)) {
2748
+ nodes.push(node);
2749
+ } else {
2750
+ if (parentPath.isMethod({
2751
+ computed: true,
2752
+ key: node
2753
+ })) {
2754
+ scope = scope.parent;
2755
+ }
2756
+ const temp = scope.generateDeclaredUidIdentifier();
2757
+ nodes.unshift(expressionStatement$2(assignmentExpression$2("=", cloneNode$2(temp), node)));
2758
+ nodes.push(expressionStatement$2(cloneNode$2(temp)));
2759
+ }
2809
2760
  }
2810
- fn.get("body").unshiftContainer("body", expressionStatement$1(callExpression$1(this.hub.addHelper("newArrowCheck"), [thisExpression$1(), checkBinding ? identifier(checkBinding.name) : identifier(thisBinding)])));
2811
- fn.replaceWith(callExpression$1(memberExpression(nameFunction(this, true) || fn.node, identifier("bind")), [checkBinding ? identifier(checkBinding.name) : thisExpression$1()]));
2812
- return fn.get("callee.object");
2761
+ return this.replaceExpressionWithStatements(nodes);
2762
+ } else if (Array.isArray(this.container)) {
2763
+ return _containerInsertAfter.call(this, nodes);
2764
+ } else if (this.isStatementOrBlock()) {
2765
+ const node = this.node;
2766
+ const shouldInsertCurrentNode = node && (!this.isExpressionStatement() || node.expression != null);
2767
+ this.replaceWith(blockStatement$2(shouldInsertCurrentNode ? [node] : []));
2768
+ return this.pushContainer("body", nodes);
2769
+ } else {
2770
+ 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?");
2813
2771
  }
2814
- return fn;
2815
2772
  }
2816
- const getSuperCallsVisitor = merge([{
2817
- CallExpression(child, {
2818
- allSuperCalls
2819
- }) {
2820
- if (!child.get("callee").isSuper()) return;
2821
- allSuperCalls.push(child);
2822
- }
2823
- }, environmentVisitor]);
2824
- function hoistFunctionEnvironment(fnPath, noNewArrows = true, allowInsertArrow = true, allowInsertArrowWithRest = true) {
2825
- let arrowParent;
2826
- let thisEnvFn = fnPath.findParent(p => {
2827
- if (p.isArrowFunctionExpression()) {
2828
- arrowParent ??= p;
2829
- return false;
2830
- }
2831
- return p.isFunction() || p.isProgram() || p.isClassProperty({
2832
- static: false
2833
- }) || p.isClassPrivateProperty({
2834
- static: false
2835
- });
2836
- });
2837
- const inConstructor = thisEnvFn.isClassMethod({
2838
- kind: "constructor"
2839
- });
2840
- if (thisEnvFn.isClassProperty() || thisEnvFn.isClassPrivateProperty()) {
2841
- if (arrowParent) {
2842
- thisEnvFn = arrowParent;
2843
- } else if (allowInsertArrow) {
2844
- fnPath.replaceWith(callExpression$1(arrowFunctionExpression$1([], toExpression(fnPath.node)), []));
2845
- thisEnvFn = fnPath.get("callee");
2846
- fnPath = thisEnvFn.get("body");
2847
- } else {
2848
- throw fnPath.buildCodeFrameError("Unable to transform arrow inside class property");
2773
+ function updateSiblingKeys(fromIndex, incrementBy) {
2774
+ if (!this.parent) return;
2775
+ const paths = getCachedPaths(this.hub, this.parent) || [];
2776
+ for (const [, path] of paths) {
2777
+ if (typeof path.key === "number" && path.key >= fromIndex) {
2778
+ path.key += incrementBy;
2849
2779
  }
2850
2780
  }
2851
- const {
2852
- thisPaths,
2853
- argumentsPaths,
2854
- newTargetPaths,
2855
- superProps,
2856
- superCalls
2857
- } = getScopeInformation(fnPath);
2858
- if (inConstructor && superCalls.length > 0) {
2859
- if (!allowInsertArrow) {
2860
- throw superCalls[0].buildCodeFrameError("When using '@babel/plugin-transform-arrow-functions', " + "it's not possible to compile `super()` in an arrow function without compiling classes.\n" + "Please add '@babel/plugin-transform-classes' to your Babel configuration.");
2861
- }
2862
- if (!allowInsertArrowWithRest) {
2863
- throw superCalls[0].buildCodeFrameError("When using '@babel/plugin-transform-parameters', " + "it's not possible to compile `super()` in an arrow function with default or rest parameters without compiling classes.\n" + "Please add '@babel/plugin-transform-classes' to your Babel configuration.");
2864
- }
2865
- const allSuperCalls = [];
2866
- thisEnvFn.traverse(getSuperCallsVisitor, {
2867
- allSuperCalls
2868
- });
2869
- const superBinding = getSuperBinding(thisEnvFn);
2870
- allSuperCalls.forEach(superCall => {
2871
- const callee = identifier(superBinding);
2872
- callee.loc = superCall.node.callee.loc;
2873
- superCall.get("callee").replaceWith(callee);
2874
- });
2875
- }
2876
- if (argumentsPaths.length > 0) {
2877
- const argumentsBinding = getBinding(thisEnvFn, "arguments", () => {
2878
- const args = () => identifier("arguments");
2879
- if (thisEnvFn.scope.path.isProgram()) {
2880
- return conditionalExpression(binaryExpression("===", unaryExpression$1("typeof", args()), stringLiteral("undefined")), thisEnvFn.scope.buildUndefinedNode(), args());
2881
- } else {
2882
- return args();
2883
- }
2884
- });
2885
- argumentsPaths.forEach(argumentsChild => {
2886
- const argsRef = identifier(argumentsBinding);
2887
- argsRef.loc = argumentsChild.node.loc;
2888
- argumentsChild.replaceWith(argsRef);
2889
- });
2781
+ }
2782
+ function _verifyNodeList(nodes) {
2783
+ if (!nodes) {
2784
+ return [];
2890
2785
  }
2891
- if (newTargetPaths.length > 0) {
2892
- const newTargetBinding = getBinding(thisEnvFn, "newtarget", () => metaProperty(identifier("new"), identifier("target")));
2893
- newTargetPaths.forEach(targetChild => {
2894
- const targetRef = identifier(newTargetBinding);
2895
- targetRef.loc = targetChild.node.loc;
2896
- targetChild.replaceWith(targetRef);
2897
- });
2786
+ if (!Array.isArray(nodes)) {
2787
+ nodes = [nodes];
2898
2788
  }
2899
- if (superProps.length > 0) {
2900
- if (!allowInsertArrow) {
2901
- throw superProps[0].buildCodeFrameError("When using '@babel/plugin-transform-arrow-functions', " + "it's not possible to compile `super.prop` in an arrow function without compiling classes.\n" + "Please add '@babel/plugin-transform-classes' to your Babel configuration.");
2789
+ for (let i = 0; i < nodes.length; i++) {
2790
+ const node = nodes[i];
2791
+ let msg;
2792
+ if (!node) {
2793
+ msg = "has falsy node";
2794
+ } else if (typeof node !== "object") {
2795
+ msg = "contains a non-object node";
2796
+ } else if (!node.type) {
2797
+ msg = "without a type";
2798
+ } else if (node instanceof NodePath_Final) {
2799
+ msg = "has a NodePath when it expected a raw object";
2902
2800
  }
2903
- const flatSuperProps = superProps.reduce((acc, superProp) => acc.concat(standardizeSuperProperty(superProp)), []);
2904
- flatSuperProps.forEach(superProp => {
2905
- const key = superProp.node.computed ? "" : superProp.get("property").node.name;
2906
- const superParentPath = superProp.parentPath;
2907
- const isAssignment = superParentPath.isAssignmentExpression({
2908
- left: superProp.node
2909
- });
2910
- const isCall = superParentPath.isCallExpression({
2911
- callee: superProp.node
2912
- });
2913
- const isTaggedTemplate = superParentPath.isTaggedTemplateExpression({
2914
- tag: superProp.node
2915
- });
2916
- const superBinding = getSuperPropBinding(thisEnvFn, isAssignment, key);
2917
- const args = [];
2918
- if (superProp.node.computed) {
2919
- args.push(superProp.get("property").node);
2920
- }
2921
- if (isAssignment) {
2922
- const value = superParentPath.node.right;
2923
- args.push(value);
2924
- }
2925
- const call = callExpression$1(identifier(superBinding), args);
2926
- if (isCall) {
2927
- superParentPath.unshiftContainer("arguments", thisExpression$1());
2928
- superProp.replaceWith(memberExpression(call, identifier("call")));
2929
- thisPaths.push(superParentPath.get("arguments.0"));
2930
- } else if (isAssignment) {
2931
- superParentPath.replaceWith(call);
2932
- } else if (isTaggedTemplate) {
2933
- superProp.replaceWith(callExpression$1(memberExpression(call, identifier("bind"), false), [thisExpression$1()]));
2934
- thisPaths.push(superProp.get("arguments.0"));
2935
- } else {
2936
- superProp.replaceWith(call);
2937
- }
2938
- });
2939
- }
2940
- let thisBinding;
2941
- if (thisPaths.length > 0 || !noNewArrows) {
2942
- thisBinding = getThisBinding(thisEnvFn, inConstructor);
2943
- if (noNewArrows || inConstructor && hasSuperClass(thisEnvFn)) {
2944
- thisPaths.forEach(thisChild => {
2945
- const thisRef = thisChild.isJSX() ? jsxIdentifier(thisBinding) : identifier(thisBinding);
2946
- thisRef.loc = thisChild.node.loc;
2947
- thisChild.replaceWith(thisRef);
2948
- });
2949
- if (!noNewArrows) thisBinding = null;
2801
+ if (msg) {
2802
+ const type = Array.isArray(node) ? "array" : typeof node;
2803
+ throw new Error(`Node list ${msg} with the index of ${i} and type of ${type}`);
2950
2804
  }
2951
2805
  }
2952
- return {
2953
- thisBinding,
2954
- fnPath
2955
- };
2806
+ return nodes;
2956
2807
  }
2957
- function isLogicalOp(op) {
2958
- return LOGICAL_OPERATORS.includes(op);
2808
+ function unshiftContainer(listKey, nodes) {
2809
+ _assertUnremoved.call(this);
2810
+ nodes = _verifyNodeList.call(this, nodes);
2811
+ const path = NodePath_Final.get({
2812
+ parentPath: this,
2813
+ parent: this.node,
2814
+ container: this.node[listKey],
2815
+ listKey,
2816
+ key: 0
2817
+ }).setContext(this.context);
2818
+ return _containerInsertBefore.call(path, nodes);
2959
2819
  }
2960
- function standardizeSuperProperty(superProp) {
2961
- if (superProp.parentPath.isAssignmentExpression() && superProp.parentPath.node.operator !== "=") {
2962
- const assignmentPath = superProp.parentPath;
2963
- const op = assignmentPath.node.operator.slice(0, -1);
2964
- const value = assignmentPath.node.right;
2965
- const isLogicalAssignment = isLogicalOp(op);
2966
- if (superProp.node.computed) {
2967
- const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
2968
- const object = superProp.node.object;
2969
- const property = superProp.node.property;
2970
- assignmentPath.get("left").replaceWith(memberExpression(object, assignmentExpression$1("=", tmp, property), true));
2971
- assignmentPath.get("right").replaceWith(rightExpression(isLogicalAssignment ? "=" : op, memberExpression(object, identifier(tmp.name), true), value));
2972
- } else {
2973
- const object = superProp.node.object;
2974
- const property = superProp.node.property;
2975
- assignmentPath.get("left").replaceWith(memberExpression(object, property));
2976
- assignmentPath.get("right").replaceWith(rightExpression(isLogicalAssignment ? "=" : op, memberExpression(object, identifier(property.name)), value));
2977
- }
2978
- if (isLogicalAssignment) {
2979
- assignmentPath.replaceWith(logicalExpression(op, assignmentPath.node.left, assignmentPath.node.right));
2980
- } else {
2981
- assignmentPath.node.operator = "=";
2820
+ function pushContainer(listKey, nodes) {
2821
+ _assertUnremoved.call(this);
2822
+ const verifiedNodes = _verifyNodeList.call(this, nodes);
2823
+ const container = this.node[listKey];
2824
+ const path = NodePath_Final.get({
2825
+ parentPath: this,
2826
+ parent: this.node,
2827
+ container: container,
2828
+ listKey,
2829
+ key: container.length
2830
+ }).setContext(this.context);
2831
+ return path.replaceWithMultiple(verifiedNodes);
2832
+ }
2833
+ function hoist(scope = this.scope) {
2834
+ const hoister = new PathHoister(this, scope);
2835
+ return hoister.run();
2836
+ }
2837
+
2838
+ const {
2839
+ FUNCTION_TYPES,
2840
+ arrowFunctionExpression: arrowFunctionExpression$1,
2841
+ assignmentExpression: assignmentExpression$1,
2842
+ awaitExpression,
2843
+ blockStatement: blockStatement$1,
2844
+ buildUndefinedNode,
2845
+ callExpression: callExpression$1,
2846
+ cloneNode: cloneNode$1,
2847
+ conditionalExpression: conditionalExpression$1,
2848
+ expressionStatement: expressionStatement$1,
2849
+ getBindingIdentifiers: getBindingIdentifiers$1,
2850
+ identifier: identifier$1,
2851
+ inheritLeadingComments,
2852
+ inheritTrailingComments,
2853
+ inheritsComments,
2854
+ isBlockStatement: isBlockStatement$1,
2855
+ isEmptyStatement,
2856
+ isExpression: isExpression$1,
2857
+ isExpressionStatement,
2858
+ isIfStatement,
2859
+ isProgram,
2860
+ isStatement,
2861
+ isVariableDeclaration,
2862
+ removeComments,
2863
+ returnStatement: returnStatement$1,
2864
+ sequenceExpression: sequenceExpression$1,
2865
+ validate: validate$1,
2866
+ yieldExpression
2867
+ } = _t;
2868
+ function replaceWithMultiple(nodes) {
2869
+ this.resync();
2870
+ nodes = _verifyNodeList.call(this, nodes);
2871
+ inheritLeadingComments(nodes[0], this.node);
2872
+ inheritTrailingComments(nodes[nodes.length - 1], this.node);
2873
+ getCachedPaths(this.hub, this.parent)?.delete(this.node);
2874
+ this.node = this.container[this.key] = null;
2875
+ const paths = this.insertAfter(nodes);
2876
+ if (this.node) {
2877
+ this.requeue();
2878
+ } else {
2879
+ this.remove();
2880
+ }
2881
+ return paths;
2882
+ }
2883
+ function replaceWithSourceString(replacement) {
2884
+ this.resync();
2885
+ let ast;
2886
+ try {
2887
+ replacement = `(${replacement})`;
2888
+ ast = parse(replacement);
2889
+ } catch (err) {
2890
+ const loc = err.loc;
2891
+ if (loc) {
2892
+ err.message += " - make sure this is an expression.\n" + codeFrameColumns(replacement, {
2893
+ start: {
2894
+ line: loc.line,
2895
+ column: loc.column + 1
2896
+ }
2897
+ });
2898
+ err.code = "BABEL_REPLACE_SOURCE_ERROR";
2982
2899
  }
2983
- return [assignmentPath.get("left"), assignmentPath.get("right").get("left")];
2984
- } else if (superProp.parentPath.isUpdateExpression()) {
2985
- const updateExpr = superProp.parentPath;
2986
- const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
2987
- const computedKey = superProp.node.computed ? superProp.scope.generateDeclaredUidIdentifier("prop") : null;
2988
- const parts = [assignmentExpression$1("=", tmp, memberExpression(superProp.node.object, computedKey ? assignmentExpression$1("=", computedKey, superProp.node.property) : superProp.node.property, superProp.node.computed)), assignmentExpression$1("=", memberExpression(superProp.node.object, computedKey ? identifier(computedKey.name) : superProp.node.property, superProp.node.computed), binaryExpression(superProp.parentPath.node.operator[0], identifier(tmp.name), numericLiteral$1(1)))];
2989
- if (!superProp.parentPath.node.prefix) {
2990
- parts.push(identifier(tmp.name));
2900
+ throw err;
2901
+ }
2902
+ const expressionAST = ast.program.body[0].expression;
2903
+ traverse.removeProperties(expressionAST);
2904
+ return this.replaceWith(expressionAST);
2905
+ }
2906
+ function replaceWith(replacementPath) {
2907
+ this.resync();
2908
+ if (this.removed) {
2909
+ throw new Error("You can't replace this node, we've already removed it");
2910
+ }
2911
+ let replacement = replacementPath instanceof NodePath_Final ? replacementPath.node : replacementPath;
2912
+ if (!replacement) {
2913
+ throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead");
2914
+ }
2915
+ if (this.node === replacement) {
2916
+ return [this];
2917
+ }
2918
+ if (this.isProgram() && !isProgram(replacement)) {
2919
+ throw new Error("You can only replace a Program root node with another Program node");
2920
+ }
2921
+ if (Array.isArray(replacement)) {
2922
+ throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`");
2923
+ }
2924
+ if (typeof replacement === "string") {
2925
+ throw new Error("Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`");
2926
+ }
2927
+ let nodePath = "";
2928
+ if (this.isNodeType("Statement") && isExpression$1(replacement)) {
2929
+ if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement) && !this.parentPath.isExportDefaultDeclaration()) {
2930
+ replacement = expressionStatement$1(replacement);
2931
+ nodePath = "expression";
2991
2932
  }
2992
- updateExpr.replaceWith(sequenceExpression(parts));
2993
- const left = updateExpr.get("expressions.0.right");
2994
- const right = updateExpr.get("expressions.1.left");
2995
- return [left, right];
2996
2933
  }
2997
- return [superProp];
2998
- function rightExpression(op, left, right) {
2999
- if (op === "=") {
3000
- return assignmentExpression$1("=", left, right);
3001
- } else {
3002
- return binaryExpression(op, left, right);
2934
+ if (this.isNodeType("Expression") && isStatement(replacement)) {
2935
+ if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement)) {
2936
+ return this.replaceExpressionWithStatements([replacement]);
3003
2937
  }
3004
2938
  }
3005
- }
3006
- function hasSuperClass(thisEnvFn) {
3007
- return thisEnvFn.isClassMethod() && !!thisEnvFn.parentPath.parentPath.node.superClass;
3008
- }
3009
- const assignSuperThisVisitor = merge([{
3010
- CallExpression(child, {
3011
- supers,
3012
- thisBinding
3013
- }) {
3014
- if (!child.get("callee").isSuper()) return;
3015
- if (supers.has(child.node)) return;
3016
- supers.add(child.node);
3017
- child.replaceWithMultiple([child.node, assignmentExpression$1("=", identifier(thisBinding), identifier("this"))]);
2939
+ const oldNode = this.node;
2940
+ if (oldNode) {
2941
+ inheritsComments(replacement, oldNode);
2942
+ removeComments(oldNode);
3018
2943
  }
3019
- }, environmentVisitor]);
3020
- function getThisBinding(thisEnvFn, inConstructor) {
3021
- return getBinding(thisEnvFn, "this", thisBinding => {
3022
- if (!inConstructor || !hasSuperClass(thisEnvFn)) return thisExpression$1();
3023
- thisEnvFn.traverse(assignSuperThisVisitor, {
3024
- supers: new WeakSet(),
3025
- thisBinding
3026
- });
3027
- });
2944
+ _replaceWith.call(this, replacement);
2945
+ this.type = replacement.type;
2946
+ this.setScope();
2947
+ this.requeue();
2948
+ return [nodePath ? this.get(nodePath) : this];
3028
2949
  }
3029
- function getSuperBinding(thisEnvFn) {
3030
- return getBinding(thisEnvFn, "supercall", () => {
3031
- const argsBinding = thisEnvFn.scope.generateUidIdentifier("args");
3032
- return arrowFunctionExpression$1([restElement(argsBinding)], callExpression$1(_super(), [spreadElement(identifier(argsBinding.name))]));
3033
- });
2950
+ function _replaceWith(node) {
2951
+ if (!this.container) {
2952
+ throw new ReferenceError("Container is falsy");
2953
+ }
2954
+ if (this.inList) {
2955
+ validate$1(this.parent, this.key, [node]);
2956
+ } else {
2957
+ validate$1(this.parent, this.key, node);
2958
+ }
2959
+ this.debug(`Replace with ${node?.type}`);
2960
+ getCachedPaths(this.hub, this.parent)?.set(node, this).delete(this.node);
2961
+ this.node = this.container[this.key] = node;
3034
2962
  }
3035
- function getSuperPropBinding(thisEnvFn, isAssignment, propName) {
3036
- const op = isAssignment ? "set" : "get";
3037
- return getBinding(thisEnvFn, `superprop_${op}:${propName || ""}`, () => {
3038
- const argsList = [];
3039
- let fnBody;
3040
- if (propName) {
3041
- fnBody = memberExpression(_super(), identifier(propName));
2963
+ function replaceExpressionWithStatements(nodes) {
2964
+ this.resync();
2965
+ const declars = [];
2966
+ const nodesAsSingleExpression = gatherSequenceExpressions(nodes, declars);
2967
+ if (nodesAsSingleExpression) {
2968
+ for (const id of declars) this.scope.push({
2969
+ id
2970
+ });
2971
+ return this.replaceWith(nodesAsSingleExpression)[0].get("expressions");
2972
+ }
2973
+ const functionParent = this.getFunctionParent();
2974
+ const isParentAsync = functionParent?.is("async");
2975
+ const isParentGenerator = functionParent?.is("generator");
2976
+ const container = arrowFunctionExpression$1([], blockStatement$1(nodes));
2977
+ this.replaceWith(callExpression$1(container, []));
2978
+ const callee = this.get("callee");
2979
+ callee.get("body").scope.hoistVariables(id => this.scope.push({
2980
+ id
2981
+ }));
2982
+ const completionRecords = callee.getCompletionRecords();
2983
+ for (const path of completionRecords) {
2984
+ if (!path.isExpressionStatement()) continue;
2985
+ const loop = path.findParent(path => path.isLoop());
2986
+ if (loop) {
2987
+ let uid = loop.getData("expressionReplacementReturnUid");
2988
+ if (!uid) {
2989
+ uid = callee.scope.generateDeclaredUidIdentifier("ret");
2990
+ callee.get("body").pushContainer("body", returnStatement$1(cloneNode$1(uid)));
2991
+ loop.setData("expressionReplacementReturnUid", uid);
2992
+ } else {
2993
+ uid = identifier$1(uid.name);
2994
+ }
2995
+ path.get("expression").replaceWith(assignmentExpression$1("=", cloneNode$1(uid), path.node.expression));
3042
2996
  } else {
3043
- const method = thisEnvFn.scope.generateUidIdentifier("prop");
3044
- argsList.unshift(method);
3045
- fnBody = memberExpression(_super(), identifier(method.name), true);
2997
+ path.replaceWith(returnStatement$1(path.node.expression));
3046
2998
  }
3047
- if (isAssignment) {
3048
- const valueIdent = thisEnvFn.scope.generateUidIdentifier("value");
3049
- argsList.push(valueIdent);
3050
- fnBody = assignmentExpression$1("=", fnBody, identifier(valueIdent.name));
2999
+ }
3000
+ callee.arrowFunctionToExpression();
3001
+ const newCallee = callee;
3002
+ const needToAwaitFunction = isParentAsync && traverse.hasType(this.get("callee.body").node, "AwaitExpression", FUNCTION_TYPES);
3003
+ const needToYieldFunction = isParentGenerator && traverse.hasType(this.get("callee.body").node, "YieldExpression", FUNCTION_TYPES);
3004
+ if (needToAwaitFunction) {
3005
+ newCallee.set("async", true);
3006
+ if (!needToYieldFunction) {
3007
+ this.replaceWith(awaitExpression(this.node));
3051
3008
  }
3052
- return arrowFunctionExpression$1(argsList, fnBody);
3053
- });
3054
- }
3055
- function getBinding(thisEnvFn, key, init) {
3056
- const cacheKey = "binding:" + key;
3057
- let data = thisEnvFn.getData(cacheKey);
3058
- if (!data) {
3059
- const id = thisEnvFn.scope.generateUidIdentifier(key);
3060
- data = id.name;
3061
- thisEnvFn.setData(cacheKey, data);
3062
- thisEnvFn.scope.push({
3063
- id: id,
3064
- init: init(data)
3065
- });
3066
3009
  }
3067
- return data;
3010
+ if (needToYieldFunction) {
3011
+ newCallee.set("generator", true);
3012
+ this.replaceWith(yieldExpression(this.node, true));
3013
+ }
3014
+ return newCallee.get("body.body");
3068
3015
  }
3069
- const getScopeInformationVisitor = merge([{
3070
- ThisExpression(child, {
3071
- thisPaths
3072
- }) {
3073
- thisPaths.push(child);
3074
- },
3075
- JSXIdentifier(child, {
3076
- thisPaths
3077
- }) {
3078
- if (child.node.name !== "this") return;
3079
- if (!child.parentPath.isJSXMemberExpression({
3080
- object: child.node
3081
- }) && !child.parentPath.isJSXOpeningElement({
3082
- name: child.node
3083
- })) {
3084
- return;
3016
+ function gatherSequenceExpressions(nodes, declars) {
3017
+ const exprs = [];
3018
+ let ensureLastUndefined = true;
3019
+ for (const node of nodes) {
3020
+ if (!isEmptyStatement(node)) {
3021
+ ensureLastUndefined = false;
3085
3022
  }
3086
- thisPaths.push(child);
3087
- },
3088
- CallExpression(child, {
3089
- superCalls
3090
- }) {
3091
- if (child.get("callee").isSuper()) superCalls.push(child);
3092
- },
3093
- MemberExpression(child, {
3094
- superProps
3095
- }) {
3096
- if (child.get("object").isSuper()) superProps.push(child);
3097
- },
3098
- Identifier(child, {
3099
- argumentsPaths
3100
- }) {
3101
- if (!child.isReferencedIdentifier({
3102
- name: "arguments"
3103
- })) return;
3104
- let curr = child.scope;
3105
- do {
3106
- if (curr.hasOwnBinding("arguments")) {
3107
- curr.rename("arguments");
3108
- return;
3023
+ if (isExpression$1(node)) {
3024
+ exprs.push(node);
3025
+ } else if (isExpressionStatement(node)) {
3026
+ exprs.push(node.expression);
3027
+ } else if (isVariableDeclaration(node)) {
3028
+ if (node.kind !== "var") return;
3029
+ for (const declar of node.declarations) {
3030
+ const bindings = getBindingIdentifiers$1(declar);
3031
+ for (const key of Object.keys(bindings)) {
3032
+ declars.push(cloneNode$1(bindings[key]));
3033
+ }
3034
+ if (declar.init) {
3035
+ exprs.push(assignmentExpression$1("=", declar.id, declar.init));
3036
+ }
3109
3037
  }
3110
- if (curr.path.isFunction() && !curr.path.isArrowFunctionExpression()) {
3111
- break;
3038
+ ensureLastUndefined = true;
3039
+ } else if (isIfStatement(node)) {
3040
+ const consequent = node.consequent ? gatherSequenceExpressions([node.consequent], declars) : buildUndefinedNode();
3041
+ const alternate = node.alternate ? gatherSequenceExpressions([node.alternate], declars) : buildUndefinedNode();
3042
+ if (!consequent || !alternate) return;
3043
+ exprs.push(conditionalExpression$1(node.test, consequent, alternate));
3044
+ } else if (isBlockStatement$1(node)) {
3045
+ const body = gatherSequenceExpressions(node.body, declars);
3046
+ if (!body) return;
3047
+ exprs.push(body);
3048
+ } else if (isEmptyStatement(node)) {
3049
+ if (nodes.indexOf(node) === 0) {
3050
+ ensureLastUndefined = true;
3112
3051
  }
3113
- } while (curr = curr.parent);
3114
- argumentsPaths.push(child);
3115
- },
3116
- MetaProperty(child, {
3117
- newTargetPaths
3118
- }) {
3119
- if (!child.get("meta").isIdentifier({
3120
- name: "new"
3121
- })) return;
3122
- if (!child.get("property").isIdentifier({
3123
- name: "target"
3124
- })) return;
3125
- newTargetPaths.push(child);
3052
+ } else {
3053
+ return;
3054
+ }
3055
+ }
3056
+ if (ensureLastUndefined) exprs.push(buildUndefinedNode());
3057
+ if (exprs.length === 1) {
3058
+ return exprs[0];
3059
+ } else {
3060
+ return sequenceExpression$1(exprs);
3126
3061
  }
3127
- }, environmentVisitor]);
3128
- function getScopeInformation(fnPath) {
3129
- const thisPaths = [];
3130
- const argumentsPaths = [];
3131
- const newTargetPaths = [];
3132
- const superProps = [];
3133
- const superCalls = [];
3134
- fnPath.traverse(getScopeInformationVisitor, {
3135
- thisPaths,
3136
- argumentsPaths,
3137
- newTargetPaths,
3138
- superProps,
3139
- superCalls
3140
- });
3141
- return {
3142
- thisPaths,
3143
- argumentsPaths,
3144
- newTargetPaths,
3145
- superProps,
3146
- superCalls
3147
- };
3148
- }
3149
-
3150
- const {
3151
- STATEMENT_OR_BLOCK_KEYS,
3152
- VISITOR_KEYS: VISITOR_KEYS$3,
3153
- isBlockStatement,
3154
- isExpression: isExpression$1,
3155
- isIdentifier: isIdentifier$1,
3156
- isLiteral,
3157
- isStringLiteral,
3158
- isType,
3159
- matchesPattern: _matchesPattern
3160
- } = _t;
3161
- function matchesPattern(pattern, allowPartial) {
3162
- return _matchesPattern(this.node, pattern, allowPartial);
3163
3062
  }
3164
- function has(key) {
3165
- const val = this.node?.[key];
3166
- if (val && Array.isArray(val)) {
3167
- return !!val.length;
3063
+ function replaceInline(nodes) {
3064
+ this.resync();
3065
+ if (Array.isArray(nodes)) {
3066
+ if (Array.isArray(this.container)) {
3067
+ nodes = _verifyNodeList.call(this, nodes);
3068
+ const paths = _containerInsertAfter.call(this, nodes);
3069
+ this.remove();
3070
+ return paths;
3071
+ } else {
3072
+ return this.replaceWithMultiple(nodes);
3073
+ }
3168
3074
  } else {
3169
- return !!val;
3075
+ return this.replaceWith(nodes);
3170
3076
  }
3171
3077
  }
3172
- function isStatic() {
3173
- return this.scope.isStatic(this.node);
3078
+
3079
+ const VALID_OBJECT_CALLEES = ["Number", "String", "Math"];
3080
+ const VALID_IDENTIFIER_CALLEES = ["isFinite", "isNaN", "parseFloat", "parseInt", "decodeURI", "decodeURIComponent", "encodeURI", "encodeURIComponent", "btoa", "atob"];
3081
+ const INVALID_METHODS = ["random"];
3082
+ function isValidObjectCallee(val) {
3083
+ return VALID_OBJECT_CALLEES.includes(val);
3174
3084
  }
3175
- const is = has;
3176
- function isnt(key) {
3177
- return !this.has(key);
3085
+ function isValidIdentifierCallee(val) {
3086
+ return VALID_IDENTIFIER_CALLEES.includes(val);
3178
3087
  }
3179
- function equals(key, value) {
3180
- return this.node[key] === value;
3088
+ function isInvalidMethod(val) {
3089
+ return INVALID_METHODS.includes(val);
3181
3090
  }
3182
- function isNodeType(type) {
3183
- return isType(this.type, type);
3091
+ function evaluateTruthy() {
3092
+ const res = this.evaluate();
3093
+ if (res.confident) return !!res.value;
3184
3094
  }
3185
- function canHaveVariableDeclarationOrExpression() {
3186
- return (this.key === "init" || this.key === "left") && this.parentPath.isFor();
3095
+ function deopt(path, state) {
3096
+ if (!state.confident) return;
3097
+ state.deoptPath = path;
3098
+ state.confident = false;
3187
3099
  }
3188
- function canSwapBetweenExpressionAndStatement(replacement) {
3189
- if (this.key !== "body" || !this.parentPath.isArrowFunctionExpression()) {
3190
- return false;
3191
- }
3192
- if (this.isExpression()) {
3193
- return isBlockStatement(replacement);
3194
- } else if (this.isBlockStatement()) {
3195
- return isExpression$1(replacement);
3100
+ const Globals = new Map([["undefined", undefined], ["Infinity", Infinity], ["NaN", NaN]]);
3101
+ function evaluateCached(path, state) {
3102
+ const {
3103
+ node
3104
+ } = path;
3105
+ const {
3106
+ seen
3107
+ } = state;
3108
+ if (seen.has(node)) {
3109
+ const existing = seen.get(node);
3110
+ if (existing.resolved) {
3111
+ return existing.value;
3112
+ } else {
3113
+ deopt(path, state);
3114
+ return;
3115
+ }
3116
+ } else {
3117
+ const item = {
3118
+ resolved: false
3119
+ };
3120
+ seen.set(node, item);
3121
+ const val = _evaluate(path, state);
3122
+ if (state.confident) {
3123
+ item.resolved = true;
3124
+ item.value = val;
3125
+ }
3126
+ return val;
3196
3127
  }
3197
- return false;
3198
3128
  }
3199
- function isCompletionRecord(allowInsideFunction) {
3200
- let path = this;
3201
- let first = true;
3202
- do {
3129
+ function _evaluate(path, state) {
3130
+ if (!state.confident) return;
3131
+ if (path.isSequenceExpression()) {
3132
+ const exprs = path.get("expressions");
3133
+ return evaluateCached(exprs[exprs.length - 1], state);
3134
+ }
3135
+ if (path.isStringLiteral() || path.isNumericLiteral() || path.isBooleanLiteral()) {
3136
+ return path.node.value;
3137
+ }
3138
+ if (path.isNullLiteral()) {
3139
+ return null;
3140
+ }
3141
+ if (path.isTemplateLiteral()) {
3142
+ return evaluateQuasis(path, path.node.quasis, state);
3143
+ }
3144
+ if (path.isTaggedTemplateExpression() && path.get("tag").isMemberExpression()) {
3145
+ const object = path.get("tag.object");
3203
3146
  const {
3204
- type,
3205
- container
3206
- } = path;
3207
- if (!first && (path.isFunction() || type === "StaticBlock")) {
3208
- return !!allowInsideFunction;
3209
- }
3210
- first = false;
3211
- if (Array.isArray(container) && path.key !== container.length - 1) {
3212
- return false;
3147
+ node: {
3148
+ name
3149
+ }
3150
+ } = object;
3151
+ const property = path.get("tag.property");
3152
+ if (object.isIdentifier() && name === "String" && !path.scope.getBinding(name) && property.isIdentifier() && property.node.name === "raw") {
3153
+ return evaluateQuasis(path, path.node.quasi.quasis, state, true);
3213
3154
  }
3214
- } while ((path = path.parentPath) && !path.isProgram() && !path.isDoExpression());
3215
- return true;
3216
- }
3217
- function isStatementOrBlock() {
3218
- if (this.parentPath.isLabeledStatement() || isBlockStatement(this.container)) {
3219
- return false;
3220
- } else {
3221
- return STATEMENT_OR_BLOCK_KEYS.includes(this.key);
3222
3155
  }
3223
- }
3224
- function referencesImport(moduleSource, importName) {
3225
- if (!this.isReferencedIdentifier()) {
3226
- if (this.isJSXMemberExpression() && this.node.property.name === importName || (this.isMemberExpression() || this.isOptionalMemberExpression()) && (this.node.computed ? isStringLiteral(this.node.property, {
3227
- value: importName
3228
- }) : this.node.property.name === importName)) {
3229
- const object = this.get("object");
3230
- return object.isReferencedIdentifier() && object.referencesImport(moduleSource, "*");
3156
+ if (path.isConditionalExpression()) {
3157
+ const testResult = evaluateCached(path.get("test"), state);
3158
+ if (!state.confident) return;
3159
+ if (testResult) {
3160
+ return evaluateCached(path.get("consequent"), state);
3161
+ } else {
3162
+ return evaluateCached(path.get("alternate"), state);
3231
3163
  }
3232
- return false;
3233
3164
  }
3234
- const binding = this.scope.getBinding(this.node.name);
3235
- if (!binding || binding.kind !== "module") return false;
3236
- const path = binding.path;
3237
- const parent = path.parentPath;
3238
- if (!parent.isImportDeclaration()) return false;
3239
- if (parent.node.source.value === moduleSource) {
3240
- if (!importName) return true;
3241
- } else {
3242
- return false;
3165
+ if (path.isExpressionWrapper()) {
3166
+ return evaluateCached(path.get("expression"), state);
3243
3167
  }
3244
- if (path.isImportDefaultSpecifier() && importName === "default") {
3245
- return true;
3168
+ if (path.isMemberExpression() && !path.parentPath.isCallExpression({
3169
+ callee: path.node
3170
+ })) {
3171
+ const property = path.get("property");
3172
+ const object = path.get("object");
3173
+ if (object.isLiteral()) {
3174
+ const value = object.node.value;
3175
+ const type = typeof value;
3176
+ let key = null;
3177
+ if (path.node.computed) {
3178
+ key = evaluateCached(property, state);
3179
+ if (!state.confident) return;
3180
+ } else if (property.isIdentifier()) {
3181
+ key = property.node.name;
3182
+ }
3183
+ if ((type === "number" || type === "string") && key != null && (typeof key === "number" || typeof key === "string")) {
3184
+ return value[key];
3185
+ }
3186
+ }
3246
3187
  }
3247
- if (path.isImportNamespaceSpecifier() && importName === "*") {
3248
- return true;
3188
+ if (path.isReferencedIdentifier()) {
3189
+ const binding = path.scope.getBinding(path.node.name);
3190
+ if (binding) {
3191
+ if (binding.constantViolations.length > 0 || path.node.start < binding.path.node.end) {
3192
+ deopt(binding.path, state);
3193
+ return;
3194
+ }
3195
+ if (binding.hasValue) {
3196
+ return binding.value;
3197
+ }
3198
+ }
3199
+ const name = path.node.name;
3200
+ if (Globals.has(name)) {
3201
+ if (!binding) {
3202
+ return Globals.get(name);
3203
+ }
3204
+ deopt(binding.path, state);
3205
+ return;
3206
+ }
3207
+ const resolved = path.resolve();
3208
+ if (resolved === path) {
3209
+ deopt(path, state);
3210
+ return;
3211
+ } else {
3212
+ return evaluateCached(resolved, state);
3213
+ }
3249
3214
  }
3250
- if (path.isImportSpecifier() && isIdentifier$1(path.node.imported, {
3251
- name: importName
3215
+ if (path.isUnaryExpression({
3216
+ prefix: true
3252
3217
  })) {
3253
- return true;
3218
+ if (path.node.operator === "void") {
3219
+ return undefined;
3220
+ }
3221
+ const argument = path.get("argument");
3222
+ if (path.node.operator === "typeof" && (argument.isFunction() || argument.isClass())) {
3223
+ return "function";
3224
+ }
3225
+ const arg = evaluateCached(argument, state);
3226
+ if (!state.confident) return;
3227
+ switch (path.node.operator) {
3228
+ case "!":
3229
+ return !arg;
3230
+ case "+":
3231
+ return +arg;
3232
+ case "-":
3233
+ return -arg;
3234
+ case "~":
3235
+ return ~arg;
3236
+ case "typeof":
3237
+ return typeof arg;
3238
+ }
3254
3239
  }
3255
- return false;
3256
- }
3257
- function getSource() {
3258
- const node = this.node;
3259
- if (node.end) {
3260
- const code = this.hub.getCode();
3261
- if (code) return code.slice(node.start, node.end);
3240
+ if (path.isArrayExpression()) {
3241
+ const arr = [];
3242
+ const elems = path.get("elements");
3243
+ for (const elem of elems) {
3244
+ const elemValue = elem.evaluate();
3245
+ if (elemValue.confident) {
3246
+ arr.push(elemValue.value);
3247
+ } else {
3248
+ deopt(elemValue.deopt, state);
3249
+ return;
3250
+ }
3251
+ }
3252
+ return arr;
3262
3253
  }
3263
- return "";
3264
- }
3265
- function willIMaybeExecuteBefore(target) {
3266
- return this._guessExecutionStatusRelativeTo(target) !== "after";
3267
- }
3268
- function getOuterFunction(path) {
3269
- return path.isProgram() ? path : (path.parentPath.scope.getFunctionParent() || path.parentPath.scope.getProgramParent()).path;
3270
- }
3271
- function isExecutionUncertain(type, key) {
3272
- switch (type) {
3273
- case "LogicalExpression":
3274
- return key === "right";
3275
- case "ConditionalExpression":
3276
- case "IfStatement":
3277
- return key === "consequent" || key === "alternate";
3278
- case "WhileStatement":
3279
- case "DoWhileStatement":
3280
- case "ForInStatement":
3281
- case "ForOfStatement":
3282
- return key === "body";
3283
- case "ForStatement":
3284
- return key === "body" || key === "update";
3285
- case "SwitchStatement":
3286
- return key === "cases";
3287
- case "TryStatement":
3288
- return key === "handler";
3289
- case "AssignmentPattern":
3290
- return key === "right";
3291
- case "OptionalMemberExpression":
3292
- return key === "property";
3293
- case "OptionalCallExpression":
3294
- return key === "arguments";
3295
- default:
3296
- return false;
3254
+ if (path.isObjectExpression()) {
3255
+ const obj = {};
3256
+ const props = path.get("properties");
3257
+ for (const prop of props) {
3258
+ if (prop.isObjectMethod() || prop.isSpreadElement()) {
3259
+ deopt(prop, state);
3260
+ return;
3261
+ }
3262
+ const keyPath = prop.get("key");
3263
+ let key;
3264
+ if (prop.node.computed) {
3265
+ key = keyPath.evaluate();
3266
+ if (!key.confident) {
3267
+ deopt(key.deopt, state);
3268
+ return;
3269
+ }
3270
+ key = key.value;
3271
+ } else if (keyPath.isIdentifier()) {
3272
+ key = keyPath.node.name;
3273
+ } else {
3274
+ key = keyPath.node.value;
3275
+ }
3276
+ const valuePath = prop.get("value");
3277
+ let value = valuePath.evaluate();
3278
+ if (!value.confident) {
3279
+ deopt(value.deopt, state);
3280
+ return;
3281
+ }
3282
+ value = value.value;
3283
+ obj[key] = value;
3284
+ }
3285
+ return obj;
3286
+ }
3287
+ if (path.isLogicalExpression()) {
3288
+ const wasConfident = state.confident;
3289
+ const left = evaluateCached(path.get("left"), state);
3290
+ const leftConfident = state.confident;
3291
+ state.confident = wasConfident;
3292
+ const right = evaluateCached(path.get("right"), state);
3293
+ const rightConfident = state.confident;
3294
+ switch (path.node.operator) {
3295
+ case "||":
3296
+ state.confident = leftConfident && (!!left || rightConfident);
3297
+ if (!state.confident) return;
3298
+ return left || right;
3299
+ case "&&":
3300
+ state.confident = leftConfident && (!left || rightConfident);
3301
+ if (!state.confident) return;
3302
+ return left && right;
3303
+ case "??":
3304
+ state.confident = leftConfident && (left != null || rightConfident);
3305
+ if (!state.confident) return;
3306
+ return left ?? right;
3307
+ }
3297
3308
  }
3298
- }
3299
- function isExecutionUncertainInList(paths, maxIndex) {
3300
- for (let i = 0; i < maxIndex; i++) {
3301
- const path = paths[i];
3302
- if (isExecutionUncertain(path.parent.type, path.parentKey)) {
3303
- return true;
3309
+ if (path.isBinaryExpression()) {
3310
+ const left = evaluateCached(path.get("left"), state);
3311
+ if (!state.confident) return;
3312
+ const right = evaluateCached(path.get("right"), state);
3313
+ if (!state.confident) return;
3314
+ switch (path.node.operator) {
3315
+ case "-":
3316
+ return left - right;
3317
+ case "+":
3318
+ return left + right;
3319
+ case "/":
3320
+ return left / right;
3321
+ case "*":
3322
+ return left * right;
3323
+ case "%":
3324
+ return left % right;
3325
+ case "**":
3326
+ return left ** right;
3327
+ case "<":
3328
+ return left < right;
3329
+ case ">":
3330
+ return left > right;
3331
+ case "<=":
3332
+ return left <= right;
3333
+ case ">=":
3334
+ return left >= right;
3335
+ case "==":
3336
+ return left == right;
3337
+ case "!=":
3338
+ return left != right;
3339
+ case "===":
3340
+ return left === right;
3341
+ case "!==":
3342
+ return left !== right;
3343
+ case "|":
3344
+ return left | right;
3345
+ case "&":
3346
+ return left & right;
3347
+ case "^":
3348
+ return left ^ right;
3349
+ case "<<":
3350
+ return left << right;
3351
+ case ">>":
3352
+ return left >> right;
3353
+ case ">>>":
3354
+ return left >>> right;
3304
3355
  }
3305
3356
  }
3306
- return false;
3307
- }
3308
- const SYMBOL_CHECKING = Symbol();
3309
- function _guessExecutionStatusRelativeTo(target) {
3310
- return _guessExecutionStatusRelativeToCached(this, target, new Map());
3357
+ if (path.isCallExpression()) {
3358
+ const callee = path.get("callee");
3359
+ let context;
3360
+ let func;
3361
+ if (callee.isIdentifier() && !path.scope.getBinding(callee.node.name) && (isValidObjectCallee(callee.node.name) || isValidIdentifierCallee(callee.node.name))) {
3362
+ func = global[callee.node.name];
3363
+ }
3364
+ if (callee.isMemberExpression()) {
3365
+ const object = callee.get("object");
3366
+ const property = callee.get("property");
3367
+ if (object.isIdentifier() && property.isIdentifier() && isValidObjectCallee(object.node.name) && !isInvalidMethod(property.node.name)) {
3368
+ context = global[object.node.name];
3369
+ const key = property.node.name;
3370
+ if (Object.hasOwn(context, key)) {
3371
+ func = context[key];
3372
+ }
3373
+ }
3374
+ if (object.isLiteral() && property.isIdentifier()) {
3375
+ const type = typeof object.node.value;
3376
+ if (type === "string" || type === "number") {
3377
+ context = object.node.value;
3378
+ func = context[property.node.name];
3379
+ }
3380
+ }
3381
+ }
3382
+ if (func) {
3383
+ const args = path.get("arguments").map(arg => evaluateCached(arg, state));
3384
+ if (!state.confident) return;
3385
+ return func.apply(context, args);
3386
+ }
3387
+ }
3388
+ deopt(path, state);
3311
3389
  }
3312
- function _guessExecutionStatusRelativeToCached(base, target, cache) {
3313
- const funcParent = {
3314
- this: getOuterFunction(base),
3315
- target: getOuterFunction(target)
3316
- };
3317
- if (funcParent.target.node !== funcParent.this.node) {
3318
- return _guessExecutionStatusRelativeToDifferentFunctionsCached(base, funcParent.target, cache);
3390
+ function evaluateQuasis(path, quasis, state, raw = false) {
3391
+ let str = "";
3392
+ let i = 0;
3393
+ const exprs = path.isTemplateLiteral() ? path.get("expressions") : path.get("quasi.expressions");
3394
+ for (const elem of quasis) {
3395
+ if (!state.confident) break;
3396
+ str += raw ? elem.value.raw : elem.value.cooked;
3397
+ const expr = exprs[i++];
3398
+ if (expr) str += String(evaluateCached(expr, state));
3319
3399
  }
3320
- const paths = {
3321
- target: target.getAncestry(),
3322
- this: base.getAncestry()
3400
+ if (!state.confident) return;
3401
+ return str;
3402
+ }
3403
+ function evaluate() {
3404
+ const state = {
3405
+ confident: true,
3406
+ deoptPath: null,
3407
+ seen: new Map()
3323
3408
  };
3324
- if (paths.target.indexOf(base) >= 0) return "after";
3325
- if (paths.this.indexOf(target) >= 0) return "before";
3326
- let commonPath;
3327
- const commonIndex = {
3328
- target: 0,
3329
- this: 0
3409
+ let value = evaluateCached(this, state);
3410
+ if (!state.confident) value = undefined;
3411
+ return {
3412
+ confident: state.confident,
3413
+ deopt: state.deoptPath,
3414
+ value: value
3330
3415
  };
3331
- while (!commonPath && commonIndex.this < paths.this.length) {
3332
- const path = paths.this[commonIndex.this];
3333
- commonIndex.target = paths.target.indexOf(path);
3334
- if (commonIndex.target >= 0) {
3335
- commonPath = path;
3336
- } else {
3337
- commonIndex.this++;
3338
- }
3416
+ }
3417
+
3418
+ const {
3419
+ arrowFunctionExpression,
3420
+ assignmentExpression,
3421
+ binaryExpression,
3422
+ blockStatement,
3423
+ callExpression,
3424
+ conditionalExpression,
3425
+ expressionStatement,
3426
+ identifier,
3427
+ isIdentifier: isIdentifier$1,
3428
+ jsxIdentifier,
3429
+ logicalExpression,
3430
+ LOGICAL_OPERATORS,
3431
+ memberExpression,
3432
+ metaProperty,
3433
+ numericLiteral: numericLiteral$1,
3434
+ objectExpression,
3435
+ restElement,
3436
+ returnStatement,
3437
+ sequenceExpression,
3438
+ spreadElement,
3439
+ stringLiteral,
3440
+ super: _super,
3441
+ thisExpression,
3442
+ toExpression,
3443
+ unaryExpression: unaryExpression$1,
3444
+ toBindingIdentifierName,
3445
+ isFunction,
3446
+ isAssignmentPattern,
3447
+ isRestElement,
3448
+ getFunctionName,
3449
+ cloneNode,
3450
+ variableDeclaration,
3451
+ variableDeclarator,
3452
+ exportNamedDeclaration,
3453
+ exportSpecifier,
3454
+ inherits
3455
+ } = _t;
3456
+ function toComputedKey() {
3457
+ let key;
3458
+ if (this.isMemberExpression()) {
3459
+ key = this.node.property;
3460
+ } else if (this.isProperty() || this.isMethod()) {
3461
+ key = this.node.key;
3462
+ } else {
3463
+ throw new ReferenceError("todo");
3339
3464
  }
3340
- if (!commonPath) {
3341
- throw new Error("Internal Babel error - The two compared nodes" + " don't appear to belong to the same program.");
3465
+ if (!this.node.computed) {
3466
+ if (isIdentifier$1(key)) key = stringLiteral(key.name);
3342
3467
  }
3343
- if (isExecutionUncertainInList(paths.this, commonIndex.this - 1) || isExecutionUncertainInList(paths.target, commonIndex.target - 1)) {
3344
- return "unknown";
3468
+ return key;
3469
+ }
3470
+ function ensureBlock() {
3471
+ const body = this.get("body");
3472
+ const bodyNode = body.node;
3473
+ if (Array.isArray(body)) {
3474
+ throw new Error("Can't convert array path to a block statement");
3345
3475
  }
3346
- const divergence = {
3347
- this: paths.this[commonIndex.this - 1],
3348
- target: paths.target[commonIndex.target - 1]
3349
- };
3350
- if (divergence.target.listKey && divergence.this.listKey && divergence.target.container === divergence.this.container) {
3351
- return divergence.target.key > divergence.this.key ? "before" : "after";
3476
+ if (!bodyNode) {
3477
+ throw new Error("Can't convert node without a body");
3352
3478
  }
3353
- const keys = VISITOR_KEYS$3[commonPath.type];
3354
- const keyPosition = {
3355
- this: keys.indexOf(divergence.this.parentKey),
3356
- target: keys.indexOf(divergence.target.parentKey)
3357
- };
3358
- return keyPosition.target > keyPosition.this ? "before" : "after";
3359
- }
3360
- function _guessExecutionStatusRelativeToDifferentFunctionsInternal(base, target, cache) {
3361
- if (!target.isFunctionDeclaration()) {
3362
- if (_guessExecutionStatusRelativeToCached(base, target, cache) === "before") {
3363
- return "before";
3364
- }
3365
- return "unknown";
3366
- } else if (target.parentPath.isExportDeclaration()) {
3367
- return "unknown";
3479
+ if (body.isBlockStatement()) {
3480
+ return bodyNode;
3368
3481
  }
3369
- const binding = target.scope.getBinding(target.node.id.name);
3370
- if (!binding.references) return "before";
3371
- const referencePaths = binding.referencePaths;
3372
- let allStatus;
3373
- for (const path of referencePaths) {
3374
- const childOfFunction = !!path.find(path => path.node === target.node);
3375
- if (childOfFunction) continue;
3376
- if (path.key !== "callee" || !path.parentPath.isCallExpression()) {
3377
- return "unknown";
3378
- }
3379
- const status = _guessExecutionStatusRelativeToCached(base, path, cache);
3380
- if (allStatus && allStatus !== status) {
3381
- return "unknown";
3482
+ const statements = [];
3483
+ let stringPath = "body";
3484
+ let key;
3485
+ let listKey;
3486
+ if (body.isStatement()) {
3487
+ listKey = "body";
3488
+ key = 0;
3489
+ statements.push(body.node);
3490
+ } else {
3491
+ stringPath += ".body.0";
3492
+ if (this.isFunction()) {
3493
+ key = "argument";
3494
+ statements.push(returnStatement(body.node));
3382
3495
  } else {
3383
- allStatus = status;
3496
+ key = "expression";
3497
+ statements.push(expressionStatement(body.node));
3384
3498
  }
3385
3499
  }
3386
- return allStatus;
3500
+ this.node.body = blockStatement(statements);
3501
+ const parentPath = this.get(stringPath);
3502
+ body.setup(parentPath, listKey ? parentPath.node[listKey] : parentPath.node, listKey, key);
3503
+ return this.node;
3387
3504
  }
3388
- function _guessExecutionStatusRelativeToDifferentFunctionsCached(base, target, cache) {
3389
- let nodeMap = cache.get(base.node);
3390
- let cached;
3391
- if (!nodeMap) {
3392
- cache.set(base.node, nodeMap = new Map());
3393
- } else if (cached = nodeMap.get(target.node)) {
3394
- if (cached === SYMBOL_CHECKING) {
3395
- return "unknown";
3396
- }
3397
- return cached;
3505
+ function unwrapFunctionEnvironment() {
3506
+ if (!this.isArrowFunctionExpression() && !this.isFunctionExpression() && !this.isFunctionDeclaration()) {
3507
+ throw this.buildCodeFrameError("Can only unwrap the environment of a function.");
3398
3508
  }
3399
- nodeMap.set(target.node, SYMBOL_CHECKING);
3400
- const result = _guessExecutionStatusRelativeToDifferentFunctionsInternal(base, target, cache);
3401
- nodeMap.set(target.node, result);
3402
- return result;
3509
+ hoistFunctionEnvironment(this);
3403
3510
  }
3404
- function resolve(dangerous, resolved) {
3405
- return this._resolve(dangerous, resolved) || this;
3511
+ function setType(path, type) {
3512
+ path.node.type = type;
3406
3513
  }
3407
- function _resolve(dangerous, resolved) {
3408
- if (resolved && resolved.indexOf(this) >= 0) return;
3409
- resolved = resolved || [];
3410
- resolved.push(this);
3411
- if (this.isVariableDeclarator()) {
3412
- if (this.get("id").isIdentifier()) {
3413
- return this.get("init").resolve(dangerous, resolved);
3414
- }
3415
- } else if (this.isReferencedIdentifier()) {
3416
- const binding = this.scope.getBinding(this.node.name);
3417
- if (!binding) return;
3418
- if (!binding.constant) return;
3419
- if (binding.kind === "module") return;
3420
- if (binding.path !== this) {
3421
- const ret = binding.path.resolve(dangerous, resolved);
3422
- if (this.find(parent => parent.node === ret.node)) return;
3423
- return ret;
3424
- }
3425
- } else if (this.isTypeCastExpression()) {
3426
- return this.get("expression").resolve(dangerous, resolved);
3427
- } else if (dangerous && this.isMemberExpression()) {
3428
- const targetKey = this.toComputedKey();
3429
- if (!isLiteral(targetKey)) return;
3430
- const targetName = targetKey.value;
3431
- const target = this.get("object").resolve(dangerous, resolved);
3432
- if (target.isObjectExpression()) {
3433
- const props = target.get("properties");
3434
- for (const prop of props) {
3435
- if (!prop.isProperty()) continue;
3436
- const key = prop.get("key");
3437
- let match = prop.isnt("computed") && key.isIdentifier({
3438
- name: targetName
3439
- });
3440
- match = match || key.isLiteral({
3441
- value: targetName
3442
- });
3443
- if (match) return prop.get("value").resolve(dangerous, resolved);
3444
- }
3445
- } else if (target.isArrayExpression() && !isNaN(+targetName)) {
3446
- const elems = target.get("elements");
3447
- const elem = elems[targetName];
3448
- if (elem) return elem.resolve(dangerous, resolved);
3514
+ function arrowFunctionToExpression({
3515
+ allowInsertArrow = true,
3516
+ allowInsertArrowWithRest = allowInsertArrow,
3517
+ noNewArrows = true
3518
+ } = {}) {
3519
+ if (!this.isArrowFunctionExpression()) {
3520
+ throw this.buildCodeFrameError("Cannot convert non-arrow function to a function expression.");
3521
+ }
3522
+ let self = this;
3523
+ if (!noNewArrows) {
3524
+ self = self.ensureFunctionName(false) ?? self;
3525
+ }
3526
+ const {
3527
+ thisBinding,
3528
+ fnPath: fn
3529
+ } = hoistFunctionEnvironment(self, noNewArrows, allowInsertArrow, allowInsertArrowWithRest);
3530
+ fn.ensureBlock();
3531
+ setType(fn, "FunctionExpression");
3532
+ if (!noNewArrows) {
3533
+ const checkBinding = thisBinding ? null : fn.scope.generateUidIdentifier("arrowCheckId");
3534
+ if (checkBinding) {
3535
+ fn.parentPath.scope.push({
3536
+ id: checkBinding,
3537
+ init: objectExpression([])
3538
+ });
3449
3539
  }
3540
+ fn.get("body").unshiftContainer("body", expressionStatement(callExpression(this.hub.addHelper("newArrowCheck"), [thisExpression(), checkBinding ? identifier(checkBinding.name) : identifier(thisBinding)])));
3541
+ fn.replaceWith(callExpression(memberExpression(fn.node, identifier("bind")), [checkBinding ? identifier(checkBinding.name) : thisExpression()]));
3542
+ return fn.get("callee.object");
3450
3543
  }
3544
+ return fn;
3451
3545
  }
3452
- function isConstantExpression() {
3453
- if (this.isIdentifier()) {
3454
- const binding = this.scope.getBinding(this.node.name);
3455
- if (!binding) return false;
3456
- return binding.constant;
3546
+ const getSuperCallsVisitor = environmentVisitor({
3547
+ CallExpression(child, {
3548
+ allSuperCalls
3549
+ }) {
3550
+ if (!child.get("callee").isSuper()) return;
3551
+ allSuperCalls.push(child);
3457
3552
  }
3458
- if (this.isLiteral()) {
3459
- if (this.isRegExpLiteral()) {
3553
+ });
3554
+ function hoistFunctionEnvironment(fnPath, noNewArrows = true, allowInsertArrow = true, allowInsertArrowWithRest = true) {
3555
+ let arrowParent;
3556
+ let thisEnvFn = fnPath.findParent(p => {
3557
+ if (p.isArrowFunctionExpression()) {
3558
+ arrowParent ??= p;
3460
3559
  return false;
3461
3560
  }
3462
- if (this.isTemplateLiteral()) {
3463
- return this.get("expressions").every(expression => expression.isConstantExpression());
3561
+ return p.isFunction() || p.isProgram() || p.isClassProperty({
3562
+ static: false
3563
+ }) || p.isClassPrivateProperty({
3564
+ static: false
3565
+ });
3566
+ });
3567
+ const inConstructor = thisEnvFn.isClassMethod({
3568
+ kind: "constructor"
3569
+ });
3570
+ if (thisEnvFn.isClassProperty() || thisEnvFn.isClassPrivateProperty()) {
3571
+ if (arrowParent) {
3572
+ thisEnvFn = arrowParent;
3573
+ } else if (allowInsertArrow) {
3574
+ fnPath.replaceWith(callExpression(arrowFunctionExpression([], toExpression(fnPath.node)), []));
3575
+ thisEnvFn = fnPath.get("callee");
3576
+ fnPath = thisEnvFn.get("body");
3577
+ } else {
3578
+ throw fnPath.buildCodeFrameError("Unable to transform arrow inside class property");
3464
3579
  }
3465
- return true;
3466
3580
  }
3467
- if (this.isUnaryExpression()) {
3468
- if (this.node.operator !== "void") {
3469
- return false;
3581
+ const {
3582
+ thisPaths,
3583
+ argumentsPaths,
3584
+ newTargetPaths,
3585
+ superProps,
3586
+ superCalls
3587
+ } = getScopeInformation(fnPath);
3588
+ if (inConstructor && superCalls.length > 0) {
3589
+ if (!allowInsertArrow) {
3590
+ throw superCalls[0].buildCodeFrameError("When using '@babel/plugin-transform-arrow-functions', " + "it's not possible to compile `super()` in an arrow function without compiling classes.\n" + "Please add '@babel/plugin-transform-classes' to your Babel configuration.");
3470
3591
  }
3471
- return this.get("argument").isConstantExpression();
3472
- }
3473
- if (this.isBinaryExpression()) {
3474
- const {
3475
- operator
3476
- } = this.node;
3477
- return operator !== "in" && operator !== "instanceof" && this.get("left").isConstantExpression() && this.get("right").isConstantExpression();
3592
+ if (!allowInsertArrowWithRest) {
3593
+ throw superCalls[0].buildCodeFrameError("When using '@babel/plugin-transform-parameters', " + "it's not possible to compile `super()` in an arrow function with default or rest parameters without compiling classes.\n" + "Please add '@babel/plugin-transform-classes' to your Babel configuration.");
3594
+ }
3595
+ const allSuperCalls = [];
3596
+ thisEnvFn.traverse(getSuperCallsVisitor, {
3597
+ allSuperCalls
3598
+ });
3599
+ const superBinding = getSuperBinding(thisEnvFn);
3600
+ allSuperCalls.forEach(superCall => {
3601
+ const callee = identifier(superBinding);
3602
+ callee.loc = superCall.node.callee.loc;
3603
+ superCall.get("callee").replaceWith(callee);
3604
+ });
3478
3605
  }
3479
- if (this.isMemberExpression()) {
3480
- return !this.node.computed && this.get("object").isIdentifier({
3481
- name: "Symbol"
3482
- }) && !this.scope.hasBinding("Symbol", {
3483
- noGlobals: true
3606
+ if (argumentsPaths.length > 0) {
3607
+ const argumentsBinding = getBinding(thisEnvFn, "arguments", () => {
3608
+ const args = () => identifier("arguments");
3609
+ if (thisEnvFn.scope.path.isProgram()) {
3610
+ return conditionalExpression(binaryExpression("===", unaryExpression$1("typeof", args()), stringLiteral("undefined")), thisEnvFn.scope.buildUndefinedNode(), args());
3611
+ } else {
3612
+ return args();
3613
+ }
3614
+ });
3615
+ argumentsPaths.forEach(argumentsChild => {
3616
+ const argsRef = identifier(argumentsBinding);
3617
+ argsRef.loc = argumentsChild.node.loc;
3618
+ argumentsChild.replaceWith(argsRef);
3484
3619
  });
3485
3620
  }
3486
- if (this.isCallExpression()) {
3487
- return this.node.arguments.length === 1 && this.get("callee").matchesPattern("Symbol.for") && !this.scope.hasBinding("Symbol", {
3488
- noGlobals: true
3489
- }) && this.get("arguments")[0].isStringLiteral();
3621
+ if (newTargetPaths.length > 0) {
3622
+ const newTargetBinding = getBinding(thisEnvFn, "newtarget", () => metaProperty(identifier("new"), identifier("target")));
3623
+ newTargetPaths.forEach(targetChild => {
3624
+ const targetRef = identifier(newTargetBinding);
3625
+ targetRef.loc = targetChild.node.loc;
3626
+ targetChild.replaceWith(targetRef);
3627
+ });
3490
3628
  }
3491
- return false;
3492
- }
3493
- function isInStrictMode() {
3494
- const start = this.isProgram() ? this : this.parentPath;
3495
- const strictParent = start.find(path => {
3496
- if (path.isProgram({
3497
- sourceType: "module"
3498
- })) return true;
3499
- if (path.isClass()) return true;
3500
- if (path.isArrowFunctionExpression() && !path.get("body").isBlockStatement()) {
3501
- return false;
3502
- }
3503
- let body;
3504
- if (path.isFunction()) {
3505
- body = path.node.body;
3506
- } else if (path.isProgram()) {
3507
- body = path.node;
3508
- } else {
3509
- return false;
3629
+ if (superProps.length > 0) {
3630
+ if (!allowInsertArrow) {
3631
+ throw superProps[0].buildCodeFrameError("When using '@babel/plugin-transform-arrow-functions', " + "it's not possible to compile `super.prop` in an arrow function without compiling classes.\n" + "Please add '@babel/plugin-transform-classes' to your Babel configuration.");
3510
3632
  }
3511
- for (const directive of body.directives) {
3512
- if (directive.value.value === "use strict") {
3513
- return true;
3633
+ const flatSuperProps = superProps.reduce((acc, superProp) => acc.concat(standardizeSuperProperty(superProp)), []);
3634
+ flatSuperProps.forEach(superProp => {
3635
+ const key = superProp.node.computed ? "" : superProp.get("property").node.name;
3636
+ const superParentPath = superProp.parentPath;
3637
+ const isAssignment = superParentPath.isAssignmentExpression({
3638
+ left: superProp.node
3639
+ });
3640
+ const isCall = superParentPath.isCallExpression({
3641
+ callee: superProp.node
3642
+ });
3643
+ const isTaggedTemplate = superParentPath.isTaggedTemplateExpression({
3644
+ tag: superProp.node
3645
+ });
3646
+ const superBinding = getSuperPropBinding(thisEnvFn, isAssignment, key);
3647
+ const args = [];
3648
+ if (superProp.node.computed) {
3649
+ args.push(superProp.get("property").node);
3514
3650
  }
3515
- }
3516
- });
3517
- return !!strictParent;
3518
- }
3519
-
3520
- function call(key) {
3521
- const opts = this.opts;
3522
- this.debug(key);
3523
- if (this.node) {
3524
- if (this._call(opts[key])) return true;
3525
- }
3526
- if (this.node) {
3527
- return this._call(opts[this.node.type]?.[key]);
3651
+ if (isAssignment) {
3652
+ const value = superParentPath.node.right;
3653
+ args.push(value);
3654
+ }
3655
+ const call = callExpression(identifier(superBinding), args);
3656
+ if (isCall) {
3657
+ superParentPath.unshiftContainer("arguments", thisExpression());
3658
+ superProp.replaceWith(memberExpression(call, identifier("call")));
3659
+ thisPaths.push(superParentPath.get("arguments.0"));
3660
+ } else if (isAssignment) {
3661
+ superParentPath.replaceWith(call);
3662
+ } else if (isTaggedTemplate) {
3663
+ superProp.replaceWith(callExpression(memberExpression(call, identifier("bind"), false), [thisExpression()]));
3664
+ thisPaths.push(superProp.get("arguments.0"));
3665
+ } else {
3666
+ superProp.replaceWith(call);
3667
+ }
3668
+ });
3528
3669
  }
3529
- return false;
3530
- }
3531
- function _call(fns) {
3532
- if (!fns) return false;
3533
- for (const fn of fns) {
3534
- if (!fn) continue;
3535
- const node = this.node;
3536
- if (!node) return true;
3537
- const ret = fn.call(this.state, this, this.state);
3538
- if (ret && typeof ret === "object" && typeof ret.then === "function") {
3539
- throw new Error(`You appear to be using a plugin with an async traversal visitor, ` + `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.`);
3540
- }
3541
- if (ret) {
3542
- throw new Error(`Unexpected return value from visitor method ${fn}`);
3670
+ let thisBinding;
3671
+ if (thisPaths.length > 0 || !noNewArrows) {
3672
+ thisBinding = getThisBinding(thisEnvFn, inConstructor);
3673
+ if (noNewArrows || inConstructor && hasSuperClass(thisEnvFn)) {
3674
+ thisPaths.forEach(thisChild => {
3675
+ const thisRef = thisChild.isJSX() ? jsxIdentifier(thisBinding) : identifier(thisBinding);
3676
+ thisRef.loc = thisChild.node.loc;
3677
+ thisChild.replaceWith(thisRef);
3678
+ });
3679
+ if (!noNewArrows) thisBinding = null;
3543
3680
  }
3544
- if (this.node !== node) return true;
3545
- if (this._traverseFlags > 0) return true;
3546
3681
  }
3547
- return false;
3548
- }
3549
- function isDenylisted() {
3550
- const denylist = this.opts.denylist ?? this.opts.blacklist;
3551
- return denylist && denylist.indexOf(this.node.type) > -1;
3682
+ return {
3683
+ thisBinding,
3684
+ fnPath
3685
+ };
3552
3686
  }
3553
- function restoreContext(path, context) {
3554
- if (path.context !== context) {
3555
- path.context = context;
3556
- path.state = context.state;
3557
- path.opts = context.opts;
3558
- }
3687
+ function isLogicalOp(op) {
3688
+ return LOGICAL_OPERATORS.includes(op);
3559
3689
  }
3560
- function visit() {
3561
- if (!this.node) {
3562
- return false;
3563
- }
3564
- if (this.isDenylisted()) {
3565
- return false;
3566
- }
3567
- if (this.opts.shouldSkip?.(this)) {
3568
- return false;
3569
- }
3570
- const currentContext = this.context;
3571
- if (this.shouldSkip || this.call("enter")) {
3572
- this.debug("Skip...");
3573
- return this.shouldStop;
3690
+ function standardizeSuperProperty(superProp) {
3691
+ if (superProp.parentPath.isAssignmentExpression() && superProp.parentPath.node.operator !== "=") {
3692
+ const assignmentPath = superProp.parentPath;
3693
+ const op = assignmentPath.node.operator.slice(0, -1);
3694
+ const value = assignmentPath.node.right;
3695
+ const isLogicalAssignment = isLogicalOp(op);
3696
+ if (superProp.node.computed) {
3697
+ const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
3698
+ const object = superProp.node.object;
3699
+ const property = superProp.node.property;
3700
+ assignmentPath.get("left").replaceWith(memberExpression(object, assignmentExpression("=", tmp, property), true));
3701
+ assignmentPath.get("right").replaceWith(rightExpression(isLogicalAssignment ? "=" : op, memberExpression(object, identifier(tmp.name), true), value));
3702
+ } else {
3703
+ const object = superProp.node.object;
3704
+ const property = superProp.node.property;
3705
+ assignmentPath.get("left").replaceWith(memberExpression(object, property));
3706
+ assignmentPath.get("right").replaceWith(rightExpression(isLogicalAssignment ? "=" : op, memberExpression(object, identifier(property.name)), value));
3707
+ }
3708
+ if (isLogicalAssignment) {
3709
+ assignmentPath.replaceWith(logicalExpression(op, assignmentPath.node.left, assignmentPath.node.right));
3710
+ } else {
3711
+ assignmentPath.node.operator = "=";
3712
+ }
3713
+ return [assignmentPath.get("left"), assignmentPath.get("right").get("left")];
3714
+ } else if (superProp.parentPath.isUpdateExpression()) {
3715
+ const updateExpr = superProp.parentPath;
3716
+ const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
3717
+ const computedKey = superProp.node.computed ? superProp.scope.generateDeclaredUidIdentifier("prop") : null;
3718
+ const parts = [assignmentExpression("=", tmp, memberExpression(superProp.node.object, computedKey ? assignmentExpression("=", computedKey, superProp.node.property) : superProp.node.property, superProp.node.computed)), assignmentExpression("=", memberExpression(superProp.node.object, computedKey ? identifier(computedKey.name) : superProp.node.property, superProp.node.computed), binaryExpression(superProp.parentPath.node.operator[0], identifier(tmp.name), numericLiteral$1(1)))];
3719
+ if (!superProp.parentPath.node.prefix) {
3720
+ parts.push(identifier(tmp.name));
3721
+ }
3722
+ updateExpr.replaceWith(sequenceExpression(parts));
3723
+ const left = updateExpr.get("expressions.0.right");
3724
+ const right = updateExpr.get("expressions.1.left");
3725
+ return [left, right];
3574
3726
  }
3575
- restoreContext(this, currentContext);
3576
- this.debug("Recursing into...");
3577
- this.shouldStop = traverseNode(this.node, this.opts, this.scope, this.state, this, this.skipKeys);
3578
- restoreContext(this, currentContext);
3579
- this.call("exit");
3580
- return this.shouldStop;
3581
- }
3582
- function skip() {
3583
- this.shouldSkip = true;
3584
- }
3585
- function skipKey(key) {
3586
- if (this.skipKeys == null) {
3587
- this.skipKeys = {};
3727
+ return [superProp];
3728
+ function rightExpression(op, left, right) {
3729
+ if (op === "=") {
3730
+ return assignmentExpression("=", left, right);
3731
+ } else {
3732
+ return binaryExpression(op, left, right);
3733
+ }
3588
3734
  }
3589
- this.skipKeys[key] = true;
3590
3735
  }
3591
- function stop() {
3592
- this._traverseFlags |= SHOULD_SKIP | SHOULD_STOP;
3736
+ function hasSuperClass(thisEnvFn) {
3737
+ return thisEnvFn.isClassMethod() && !!thisEnvFn.parentPath.parentPath.node.superClass;
3593
3738
  }
3594
- function setScope() {
3595
- if (this.opts?.noScope) return;
3596
- let path = this.parentPath;
3597
- if ((this.key === "key" || this.listKey === "decorators") && path.isMethod() || this.key === "discriminant" && path.isSwitchStatement()) {
3598
- path = path.parentPath;
3599
- }
3600
- let target;
3601
- while (path && !target) {
3602
- if (path.opts?.noScope) return;
3603
- target = path.scope;
3604
- path = path.parentPath;
3739
+ const assignSuperThisVisitor = environmentVisitor({
3740
+ CallExpression(child, {
3741
+ supers,
3742
+ thisBinding
3743
+ }) {
3744
+ if (!child.get("callee").isSuper()) return;
3745
+ if (supers.has(child.node)) return;
3746
+ supers.add(child.node);
3747
+ child.replaceWithMultiple([child.node, assignmentExpression("=", identifier(thisBinding), identifier("this"))]);
3605
3748
  }
3606
- this.scope = this.getScope(target);
3607
- this.scope?.init();
3749
+ });
3750
+ function getThisBinding(thisEnvFn, inConstructor) {
3751
+ return getBinding(thisEnvFn, "this", thisBinding => {
3752
+ if (!inConstructor || !hasSuperClass(thisEnvFn)) return thisExpression();
3753
+ thisEnvFn.traverse(assignSuperThisVisitor, {
3754
+ supers: new WeakSet(),
3755
+ thisBinding
3756
+ });
3757
+ });
3608
3758
  }
3609
- function setContext(context) {
3610
- if (this.skipKeys != null) {
3611
- this.skipKeys = {};
3612
- }
3613
- this._traverseFlags = 0;
3614
- if (context) {
3615
- this.context = context;
3616
- this.state = context.state;
3617
- this.opts = context.opts;
3618
- }
3619
- this.setScope();
3620
- return this;
3759
+ function getSuperBinding(thisEnvFn) {
3760
+ return getBinding(thisEnvFn, "supercall", () => {
3761
+ const argsBinding = thisEnvFn.scope.generateUidIdentifier("args");
3762
+ return arrowFunctionExpression([restElement(argsBinding)], callExpression(_super(), [spreadElement(identifier(argsBinding.name))]));
3763
+ });
3621
3764
  }
3622
- function resync() {
3623
- if (this.removed) return;
3624
- this._resyncParent();
3625
- this._resyncList();
3626
- this._resyncKey();
3765
+ function getSuperPropBinding(thisEnvFn, isAssignment, propName) {
3766
+ const op = isAssignment ? "set" : "get";
3767
+ return getBinding(thisEnvFn, `superprop_${op}:${propName || ""}`, () => {
3768
+ const argsList = [];
3769
+ let fnBody;
3770
+ if (propName) {
3771
+ fnBody = memberExpression(_super(), identifier(propName));
3772
+ } else {
3773
+ const method = thisEnvFn.scope.generateUidIdentifier("prop");
3774
+ argsList.unshift(method);
3775
+ fnBody = memberExpression(_super(), identifier(method.name), true);
3776
+ }
3777
+ if (isAssignment) {
3778
+ const valueIdent = thisEnvFn.scope.generateUidIdentifier("value");
3779
+ argsList.push(valueIdent);
3780
+ fnBody = assignmentExpression("=", fnBody, identifier(valueIdent.name));
3781
+ }
3782
+ return arrowFunctionExpression(argsList, fnBody);
3783
+ });
3627
3784
  }
3628
- function _resyncParent() {
3629
- if (this.parentPath) {
3630
- this.parent = this.parentPath.node;
3785
+ function getBinding(thisEnvFn, key, init) {
3786
+ const cacheKey = "binding:" + key;
3787
+ let data = thisEnvFn.getData(cacheKey);
3788
+ if (!data) {
3789
+ const id = thisEnvFn.scope.generateUidIdentifier(key);
3790
+ data = id.name;
3791
+ thisEnvFn.setData(cacheKey, data);
3792
+ thisEnvFn.scope.push({
3793
+ id: id,
3794
+ init: init(data)
3795
+ });
3631
3796
  }
3797
+ return data;
3632
3798
  }
3633
- function _resyncKey() {
3634
- if (!this.container) return;
3635
- if (this.node === this.container[this.key]) {
3636
- return;
3637
- }
3638
- if (Array.isArray(this.container)) {
3639
- for (let i = 0; i < this.container.length; i++) {
3640
- if (this.container[i] === this.node) {
3641
- this.setKey(i);
3799
+ const getScopeInformationVisitor = environmentVisitor({
3800
+ ThisExpression(child, {
3801
+ thisPaths
3802
+ }) {
3803
+ thisPaths.push(child);
3804
+ },
3805
+ JSXIdentifier(child, {
3806
+ thisPaths
3807
+ }) {
3808
+ if (child.node.name !== "this") return;
3809
+ if (!child.parentPath.isJSXMemberExpression({
3810
+ object: child.node
3811
+ }) && !child.parentPath.isJSXOpeningElement({
3812
+ name: child.node
3813
+ })) {
3814
+ return;
3815
+ }
3816
+ thisPaths.push(child);
3817
+ },
3818
+ CallExpression(child, {
3819
+ superCalls
3820
+ }) {
3821
+ if (child.get("callee").isSuper()) superCalls.push(child);
3822
+ },
3823
+ MemberExpression(child, {
3824
+ superProps
3825
+ }) {
3826
+ if (child.get("object").isSuper()) superProps.push(child);
3827
+ },
3828
+ Identifier(child, {
3829
+ argumentsPaths
3830
+ }) {
3831
+ if (!child.isReferencedIdentifier({
3832
+ name: "arguments"
3833
+ })) return;
3834
+ let curr = child.scope;
3835
+ do {
3836
+ if (curr.hasOwnBinding("arguments")) {
3837
+ curr.rename("arguments");
3642
3838
  return;
3643
3839
  }
3840
+ if (curr.path.isFunction() && !curr.path.isArrowFunctionExpression()) {
3841
+ break;
3842
+ }
3843
+ } while (curr = curr.parent);
3844
+ argumentsPaths.push(child);
3845
+ },
3846
+ MetaProperty(child, {
3847
+ newTargetPaths
3848
+ }) {
3849
+ if (!child.get("meta").isIdentifier({
3850
+ name: "new"
3851
+ })) return;
3852
+ if (!child.get("property").isIdentifier({
3853
+ name: "target"
3854
+ })) return;
3855
+ newTargetPaths.push(child);
3856
+ }
3857
+ });
3858
+ function getScopeInformation(fnPath) {
3859
+ const thisPaths = [];
3860
+ const argumentsPaths = [];
3861
+ const newTargetPaths = [];
3862
+ const superProps = [];
3863
+ const superCalls = [];
3864
+ fnPath.traverse(getScopeInformationVisitor, {
3865
+ thisPaths,
3866
+ argumentsPaths,
3867
+ newTargetPaths,
3868
+ superProps,
3869
+ superCalls
3870
+ });
3871
+ return {
3872
+ thisPaths,
3873
+ argumentsPaths,
3874
+ newTargetPaths,
3875
+ superProps,
3876
+ superCalls
3877
+ };
3878
+ }
3879
+ function splitExportDeclaration() {
3880
+ if (!this.isExportDeclaration() || this.isExportAllDeclaration()) {
3881
+ throw new Error("Only default and named export declarations can be split.");
3882
+ }
3883
+ if (this.isExportNamedDeclaration() && this.get("specifiers").length > 0) {
3884
+ throw new Error("It doesn't make sense to split exported specifiers.");
3885
+ }
3886
+ const declaration = this.get("declaration");
3887
+ if (this.isExportDefaultDeclaration()) {
3888
+ const standaloneDeclaration = declaration.isFunctionDeclaration() || declaration.isClassDeclaration();
3889
+ const exportExpr = declaration.isFunctionExpression() || declaration.isClassExpression();
3890
+ const scope = declaration.isScope() ? declaration.scope.parent : declaration.scope;
3891
+ let id = declaration.node.id;
3892
+ let needBindingRegistration = false;
3893
+ if (!id) {
3894
+ needBindingRegistration = true;
3895
+ id = scope.generateUidIdentifier("default");
3896
+ if (standaloneDeclaration || exportExpr) {
3897
+ declaration.node.id = cloneNode(id);
3898
+ }
3899
+ } else if (exportExpr && scope.hasBinding(id.name)) {
3900
+ needBindingRegistration = true;
3901
+ id = scope.generateUidIdentifier(id.name);
3644
3902
  }
3645
- } else {
3646
- for (const key of Object.keys(this.container)) {
3647
- if (this.container[key] === this.node) {
3648
- this.setKey(key);
3649
- return;
3650
- }
3903
+ const updatedDeclaration = standaloneDeclaration ? declaration.node : variableDeclaration("var", [variableDeclarator(cloneNode(id), declaration.node)]);
3904
+ const updatedExportDeclaration = exportNamedDeclaration(null, [exportSpecifier(cloneNode(id), identifier("default"))]);
3905
+ this.insertAfter(updatedExportDeclaration);
3906
+ this.replaceWith(updatedDeclaration);
3907
+ if (needBindingRegistration) {
3908
+ scope.registerDeclaration(this);
3651
3909
  }
3910
+ return this;
3911
+ } else if (this.get("specifiers").length > 0) {
3912
+ throw new Error("It doesn't make sense to split exported specifiers.");
3652
3913
  }
3653
- this.key = null;
3654
- }
3655
- function _resyncList() {
3656
- if (!this.parent || !this.inList) return;
3657
- const newContainer = this.parent[this.listKey];
3658
- if (this.container === newContainer) return;
3659
- this.container = newContainer || null;
3660
- }
3661
- function _resyncRemoved() {
3662
- if (this.key == null || !this.container || this.container[this.key] !== this.node) {
3663
- this._markRemoved();
3664
- }
3665
- }
3666
- function popContext() {
3667
- this.contexts.pop();
3668
- if (this.contexts.length > 0) {
3669
- this.setContext(this.contexts[this.contexts.length - 1]);
3670
- } else {
3671
- this.setContext(undefined);
3672
- }
3673
- }
3674
- function pushContext(context) {
3675
- this.contexts.push(context);
3676
- this.setContext(context);
3677
- }
3678
- function setup(parentPath, container, listKey, key) {
3679
- this.listKey = listKey;
3680
- this.container = container;
3681
- this.parentPath = parentPath || this.parentPath;
3682
- this.setKey(key);
3683
- }
3684
- function setKey(key) {
3685
- this.key = key;
3686
- this.node = this.container[this.key];
3687
- this.type = this.node?.type;
3914
+ const bindingIdentifiers = declaration.getOuterBindingIdentifiers();
3915
+ const specifiers = Object.keys(bindingIdentifiers).map(name => {
3916
+ return exportSpecifier(identifier(name), identifier(name));
3917
+ });
3918
+ const aliasDeclar = exportNamedDeclaration(null, specifiers);
3919
+ this.insertAfter(aliasDeclar);
3920
+ this.replaceWith(declaration.node);
3921
+ return this;
3688
3922
  }
3689
- function requeue(pathToQueue = this) {
3690
- if (pathToQueue.removed) return;
3691
- {
3692
- pathToQueue.shouldSkip = false;
3923
+ const refersOuterBindingVisitor = {
3924
+ "ReferencedIdentifier|BindingIdentifier"(path, state) {
3925
+ if (path.node.name !== state.name) return;
3926
+ state.needsRename = true;
3927
+ path.stop();
3928
+ },
3929
+ Scope(path, state) {
3930
+ if (path.scope.hasOwnBinding(state.name)) {
3931
+ path.skip();
3932
+ }
3693
3933
  }
3694
- const contexts = this.contexts;
3695
- for (const context of contexts) {
3696
- context.maybeQueue(pathToQueue);
3934
+ };
3935
+ function ensureFunctionName(supportUnicodeId) {
3936
+ if (this.node.id) return this;
3937
+ const res = getFunctionName(this.node, this.parent);
3938
+ if (res == null) return this;
3939
+ let {
3940
+ name
3941
+ } = res;
3942
+ if (!supportUnicodeId && /[\uD800-\uDFFF]/.test(name)) {
3943
+ return null;
3697
3944
  }
3698
- }
3699
- function _getQueueContexts() {
3700
- let path = this;
3701
- let contexts = this.contexts;
3702
- while (!contexts.length) {
3703
- path = path.parentPath;
3704
- if (!path) break;
3705
- contexts = path.contexts;
3945
+ if (name.startsWith("get ") || name.startsWith("set ")) {
3946
+ return null;
3706
3947
  }
3707
- return contexts;
3708
- }
3709
-
3710
- const hooks = [function (self, parent) {
3711
- const 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();
3712
- if (removeParent) {
3713
- parent.remove();
3714
- return true;
3948
+ name = toBindingIdentifierName(name.replace(/[/ ]/g, "_"));
3949
+ const id = identifier(name);
3950
+ inherits(id, res.originalNode);
3951
+ const state = {
3952
+ needsRename: false,
3953
+ name
3954
+ };
3955
+ const {
3956
+ scope
3957
+ } = this;
3958
+ const binding = scope.getOwnBinding(name);
3959
+ if (binding) {
3960
+ if (binding.kind === "param") {
3961
+ state.needsRename = true;
3962
+ }
3963
+ } else if (scope.parent.hasBinding(name) || scope.hasGlobal(name)) {
3964
+ this.traverse(refersOuterBindingVisitor, state);
3715
3965
  }
3716
- }, function (self, parent) {
3717
- if (parent.isSequenceExpression() && parent.node.expressions.length === 1) {
3718
- parent.replaceWith(parent.node.expressions[0]);
3719
- return true;
3966
+ if (!state.needsRename) {
3967
+ this.node.id = id;
3968
+ scope.getProgramParent().references[id.name] = true;
3969
+ return this;
3720
3970
  }
3721
- }, function (self, parent) {
3722
- if (parent.isBinary()) {
3723
- if (self.key === "left") {
3724
- parent.replaceWith(parent.node.right);
3725
- } else {
3726
- parent.replaceWith(parent.node.left);
3727
- }
3728
- return true;
3971
+ if (scope.hasBinding(id.name) && !scope.hasGlobal(id.name)) {
3972
+ scope.rename(id.name);
3973
+ this.node.id = id;
3974
+ scope.getProgramParent().references[id.name] = true;
3975
+ return this;
3729
3976
  }
3730
- }, function (self, parent) {
3731
- if (parent.isIfStatement() && self.key === "consequent" || self.key === "body" && (parent.isLoop() || parent.isArrowFunctionExpression())) {
3732
- self.replaceWith({
3733
- type: "BlockStatement",
3734
- body: []
3735
- });
3736
- return true;
3977
+ if (!isFunction(this.node)) return null;
3978
+ const key = scope.generateUidIdentifier(id.name);
3979
+ const params = [];
3980
+ for (let i = 0, len = getFunctionArity(this.node); i < len; i++) {
3981
+ params.push(scope.generateUidIdentifier("x"));
3737
3982
  }
3738
- }];
3983
+ const call = template.expression.ast`
3984
+ (function (${key}) {
3985
+ function ${id}(${params}) {
3986
+ return ${cloneNode(key)}.apply(this, arguments);
3987
+ }
3988
+
3989
+ ${cloneNode(id)}.toString = function () {
3990
+ return ${cloneNode(key)}.toString();
3991
+ }
3992
+
3993
+ return ${cloneNode(id)};
3994
+ })(${toExpression(this.node)})
3995
+ `;
3996
+ return this.replaceWith(call)[0].get("arguments.0");
3997
+ }
3998
+ function getFunctionArity(node) {
3999
+ const count = node.params.findIndex(param => isAssignmentPattern(param) || isRestElement(param));
4000
+ return count === -1 ? node.params.length : count;
4001
+ }
3739
4002
 
3740
4003
  const {
3741
- getBindingIdentifiers: getBindingIdentifiers$1
4004
+ STATEMENT_OR_BLOCK_KEYS,
4005
+ VISITOR_KEYS: VISITOR_KEYS$3,
4006
+ isBlockStatement,
4007
+ isExpression,
4008
+ isIdentifier,
4009
+ isLiteral,
4010
+ isStringLiteral,
4011
+ isType,
4012
+ matchesPattern: _matchesPattern
3742
4013
  } = _t;
3743
- function remove() {
3744
- this._assertUnremoved();
3745
- this.resync();
3746
- if (!this.opts?.noScope) {
3747
- this._removeFromScope();
3748
- }
3749
- if (this._callRemovalHooks()) {
3750
- this._markRemoved();
3751
- return;
4014
+ function matchesPattern(pattern, allowPartial) {
4015
+ return _matchesPattern(this.node, pattern, allowPartial);
4016
+ }
4017
+ function has(key) {
4018
+ const val = this.node?.[key];
4019
+ if (val && Array.isArray(val)) {
4020
+ return !!val.length;
4021
+ } else {
4022
+ return !!val;
3752
4023
  }
3753
- this.shareCommentsWithSiblings();
3754
- this._remove();
3755
- this._markRemoved();
3756
4024
  }
3757
- function _removeFromScope() {
3758
- const bindings = getBindingIdentifiers$1(this.node, false, false, true);
3759
- Object.keys(bindings).forEach(name => this.scope.removeBinding(name));
4025
+ function isStatic() {
4026
+ return this.scope.isStatic(this.node);
3760
4027
  }
3761
- function _callRemovalHooks() {
3762
- if (this.parentPath) {
3763
- for (const fn of hooks) {
3764
- if (fn(this, this.parentPath)) return true;
3765
- }
3766
- }
4028
+ const is = has;
4029
+ function isnt(key) {
4030
+ return !this.has(key);
3767
4031
  }
3768
- function _remove() {
3769
- if (Array.isArray(this.container)) {
3770
- this.container.splice(this.key, 1);
3771
- this.updateSiblingKeys(this.key, -1);
3772
- } else {
3773
- this._replaceWith(null);
3774
- }
4032
+ function equals(key, value) {
4033
+ return this.node[key] === value;
3775
4034
  }
3776
- function _markRemoved() {
3777
- this._traverseFlags |= SHOULD_SKIP | REMOVED;
3778
- if (this.parent) {
3779
- getCachedPaths(this.hub, this.parent).delete(this.node);
3780
- }
3781
- this.node = null;
4035
+ function isNodeType(type) {
4036
+ return isType(this.type, type);
3782
4037
  }
3783
- function _assertUnremoved() {
3784
- if (this.removed) {
3785
- throw this.buildCodeFrameError("NodePath has been removed so is read-only.");
4038
+ function canHaveVariableDeclarationOrExpression() {
4039
+ return (this.key === "init" || this.key === "left") && this.parentPath.isFor();
4040
+ }
4041
+ function canSwapBetweenExpressionAndStatement(replacement) {
4042
+ if (this.key !== "body" || !this.parentPath.isArrowFunctionExpression()) {
4043
+ return false;
4044
+ }
4045
+ if (this.isExpression()) {
4046
+ return isBlockStatement(replacement);
4047
+ } else if (this.isBlockStatement()) {
4048
+ return isExpression(replacement);
3786
4049
  }
4050
+ return false;
3787
4051
  }
3788
-
3789
- const {
3790
- react
3791
- } = _t;
3792
- const {
3793
- cloneNode: cloneNode$1,
3794
- jsxExpressionContainer,
3795
- variableDeclaration,
3796
- variableDeclarator
3797
- } = _t;
3798
- const referenceVisitor = {
3799
- ReferencedIdentifier(path, state) {
3800
- if (path.isJSXIdentifier() && react.isCompatTag(path.node.name) && !path.parentPath.isJSXMemberExpression()) {
3801
- return;
4052
+ function isCompletionRecord(allowInsideFunction) {
4053
+ let path = this;
4054
+ let first = true;
4055
+ do {
4056
+ const {
4057
+ type,
4058
+ container
4059
+ } = path;
4060
+ if (!first && (path.isFunction() || type === "StaticBlock")) {
4061
+ return !!allowInsideFunction;
3802
4062
  }
3803
- if (path.node.name === "this") {
3804
- let scope = path.scope;
3805
- do {
3806
- if (scope.path.isFunction() && !scope.path.isArrowFunctionExpression()) {
3807
- break;
3808
- }
3809
- } while (scope = scope.parent);
3810
- if (scope) state.breakOnScopePaths.push(scope.path);
4063
+ first = false;
4064
+ if (Array.isArray(container) && path.key !== container.length - 1) {
4065
+ return false;
3811
4066
  }
3812
- const binding = path.scope.getBinding(path.node.name);
3813
- if (!binding) return;
3814
- for (const violation of binding.constantViolations) {
3815
- if (violation.scope !== binding.path.scope) {
3816
- state.mutableBinding = true;
3817
- path.stop();
3818
- return;
3819
- }
4067
+ } while ((path = path.parentPath) && !path.isProgram() && !path.isDoExpression());
4068
+ return true;
4069
+ }
4070
+ function isStatementOrBlock() {
4071
+ if (this.parentPath.isLabeledStatement() || isBlockStatement(this.container)) {
4072
+ return false;
4073
+ } else {
4074
+ return STATEMENT_OR_BLOCK_KEYS.includes(this.key);
4075
+ }
4076
+ }
4077
+ function referencesImport(moduleSource, importName) {
4078
+ if (!this.isReferencedIdentifier()) {
4079
+ if (this.isJSXMemberExpression() && this.node.property.name === importName || (this.isMemberExpression() || this.isOptionalMemberExpression()) && (this.node.computed ? isStringLiteral(this.node.property, {
4080
+ value: importName
4081
+ }) : this.node.property.name === importName)) {
4082
+ const object = this.get("object");
4083
+ return object.isReferencedIdentifier() && object.referencesImport(moduleSource, "*");
3820
4084
  }
3821
- if (binding !== state.scope.getBinding(path.node.name)) return;
3822
- state.bindings[path.node.name] = binding;
4085
+ return false;
4086
+ }
4087
+ const binding = this.scope.getBinding(this.node.name);
4088
+ if (!binding || binding.kind !== "module") return false;
4089
+ const path = binding.path;
4090
+ const parent = path.parentPath;
4091
+ if (!parent.isImportDeclaration()) return false;
4092
+ if (parent.node.source.value === moduleSource) {
4093
+ if (!importName) return true;
4094
+ } else {
4095
+ return false;
3823
4096
  }
3824
- };
3825
- class PathHoister {
3826
- breakOnScopePaths;
3827
- bindings;
3828
- mutableBinding;
3829
- scopes;
3830
- scope;
3831
- path;
3832
- attachAfter;
3833
- constructor(path, scope) {
3834
- this.breakOnScopePaths = [];
3835
- this.bindings = {};
3836
- this.mutableBinding = false;
3837
- this.scopes = [];
3838
- this.scope = scope;
3839
- this.path = path;
3840
- this.attachAfter = false;
4097
+ if (path.isImportDefaultSpecifier() && importName === "default") {
4098
+ return true;
3841
4099
  }
3842
- isCompatibleScope(scope) {
3843
- for (const key of Object.keys(this.bindings)) {
3844
- const binding = this.bindings[key];
3845
- if (!scope.bindingIdentifierEquals(key, binding.identifier)) {
3846
- return false;
3847
- }
3848
- }
4100
+ if (path.isImportNamespaceSpecifier() && importName === "*") {
3849
4101
  return true;
3850
4102
  }
3851
- getCompatibleScopes() {
3852
- let scope = this.path.scope;
3853
- do {
3854
- if (this.isCompatibleScope(scope)) {
3855
- this.scopes.push(scope);
3856
- } else {
3857
- break;
3858
- }
3859
- if (this.breakOnScopePaths.indexOf(scope.path) >= 0) {
3860
- break;
3861
- }
3862
- } while (scope = scope.parent);
4103
+ if (path.isImportSpecifier() && isIdentifier(path.node.imported, {
4104
+ name: importName
4105
+ })) {
4106
+ return true;
3863
4107
  }
3864
- getAttachmentPath() {
3865
- let path = this._getAttachmentPath();
3866
- if (!path) return;
3867
- let targetScope = path.scope;
3868
- if (targetScope.path === path) {
3869
- targetScope = path.scope.parent;
3870
- }
3871
- if (targetScope.path.isProgram() || targetScope.path.isFunction()) {
3872
- for (const name of Object.keys(this.bindings)) {
3873
- if (!targetScope.hasOwnBinding(name)) continue;
3874
- const binding = this.bindings[name];
3875
- if (binding.kind === "param" || binding.path.parentKey === "params") {
3876
- continue;
3877
- }
3878
- const bindingParentPath = this.getAttachmentParentForPath(binding.path);
3879
- if (bindingParentPath.key >= path.key) {
3880
- this.attachAfter = true;
3881
- path = binding.path;
3882
- for (const violationPath of binding.constantViolations) {
3883
- if (this.getAttachmentParentForPath(violationPath).key > path.key) {
3884
- path = violationPath;
3885
- }
3886
- }
3887
- }
3888
- }
3889
- }
3890
- return path;
4108
+ return false;
4109
+ }
4110
+ function getSource() {
4111
+ const node = this.node;
4112
+ if (node.end) {
4113
+ const code = this.hub.getCode();
4114
+ if (code) return code.slice(node.start, node.end);
3891
4115
  }
3892
- _getAttachmentPath() {
3893
- const scopes = this.scopes;
3894
- const scope = scopes.pop();
3895
- if (!scope) return;
3896
- if (scope.path.isFunction()) {
3897
- if (this.hasOwnParamBindings(scope)) {
3898
- if (this.scope === scope) return;
3899
- const bodies = scope.path.get("body").get("body");
3900
- for (let i = 0; i < bodies.length; i++) {
3901
- if (bodies[i].node._blockHoist) continue;
3902
- return bodies[i];
3903
- }
3904
- } else {
3905
- return this.getNextScopeAttachmentParent();
3906
- }
3907
- } else if (scope.path.isProgram()) {
3908
- return this.getNextScopeAttachmentParent();
3909
- }
4116
+ return "";
4117
+ }
4118
+ function willIMaybeExecuteBefore(target) {
4119
+ return this._guessExecutionStatusRelativeTo(target) !== "after";
4120
+ }
4121
+ function getOuterFunction(path) {
4122
+ return path.isProgram() ? path : (path.parentPath.scope.getFunctionParent() || path.parentPath.scope.getProgramParent()).path;
4123
+ }
4124
+ function isExecutionUncertain(type, key) {
4125
+ switch (type) {
4126
+ case "LogicalExpression":
4127
+ return key === "right";
4128
+ case "ConditionalExpression":
4129
+ case "IfStatement":
4130
+ return key === "consequent" || key === "alternate";
4131
+ case "WhileStatement":
4132
+ case "DoWhileStatement":
4133
+ case "ForInStatement":
4134
+ case "ForOfStatement":
4135
+ return key === "body";
4136
+ case "ForStatement":
4137
+ return key === "body" || key === "update";
4138
+ case "SwitchStatement":
4139
+ return key === "cases";
4140
+ case "TryStatement":
4141
+ return key === "handler";
4142
+ case "AssignmentPattern":
4143
+ return key === "right";
4144
+ case "OptionalMemberExpression":
4145
+ return key === "property";
4146
+ case "OptionalCallExpression":
4147
+ return key === "arguments";
4148
+ default:
4149
+ return false;
3910
4150
  }
3911
- getNextScopeAttachmentParent() {
3912
- const scope = this.scopes.pop();
3913
- if (scope) return this.getAttachmentParentForPath(scope.path);
4151
+ }
4152
+ function isExecutionUncertainInList(paths, maxIndex) {
4153
+ for (let i = 0; i < maxIndex; i++) {
4154
+ const path = paths[i];
4155
+ if (isExecutionUncertain(path.parent.type, path.parentKey)) {
4156
+ return true;
4157
+ }
3914
4158
  }
3915
- getAttachmentParentForPath(path) {
3916
- do {
3917
- if (!path.parentPath || Array.isArray(path.container) && path.isStatement()) {
3918
- return path;
3919
- }
3920
- } while (path = path.parentPath);
4159
+ return false;
4160
+ }
4161
+ const SYMBOL_CHECKING = Symbol();
4162
+ function _guessExecutionStatusRelativeTo(target) {
4163
+ return _guessExecutionStatusRelativeToCached(this, target, new Map());
4164
+ }
4165
+ function _guessExecutionStatusRelativeToCached(base, target, cache) {
4166
+ const funcParent = {
4167
+ this: getOuterFunction(base),
4168
+ target: getOuterFunction(target)
4169
+ };
4170
+ if (funcParent.target.node !== funcParent.this.node) {
4171
+ return _guessExecutionStatusRelativeToDifferentFunctionsCached(base, funcParent.target, cache);
3921
4172
  }
3922
- hasOwnParamBindings(scope) {
3923
- for (const name of Object.keys(this.bindings)) {
3924
- if (!scope.hasOwnBinding(name)) continue;
3925
- const binding = this.bindings[name];
3926
- if (binding.kind === "param" && binding.constant) return true;
4173
+ const paths = {
4174
+ target: target.getAncestry(),
4175
+ this: base.getAncestry()
4176
+ };
4177
+ if (paths.target.includes(base)) return "after";
4178
+ if (paths.this.includes(target)) return "before";
4179
+ let commonPath;
4180
+ const commonIndex = {
4181
+ target: 0,
4182
+ this: 0
4183
+ };
4184
+ while (!commonPath && commonIndex.this < paths.this.length) {
4185
+ const path = paths.this[commonIndex.this];
4186
+ commonIndex.target = paths.target.indexOf(path);
4187
+ if (commonIndex.target >= 0) {
4188
+ commonPath = path;
4189
+ } else {
4190
+ commonIndex.this++;
3927
4191
  }
3928
- return false;
3929
4192
  }
3930
- run() {
3931
- this.path.traverse(referenceVisitor, this);
3932
- if (this.mutableBinding) return;
3933
- this.getCompatibleScopes();
3934
- const attachTo = this.getAttachmentPath();
3935
- if (!attachTo) return;
3936
- if (attachTo.getFunctionParent() === this.path.getFunctionParent()) return;
3937
- let uid = attachTo.scope.generateUidIdentifier("ref");
3938
- const declarator = variableDeclarator(uid, this.path.node);
3939
- const insertFn = this.attachAfter ? "insertAfter" : "insertBefore";
3940
- const [attached] = attachTo[insertFn]([attachTo.isVariableDeclarator() ? declarator : variableDeclaration("var", [declarator])]);
3941
- const parent = this.path.parentPath;
3942
- if (parent.isJSXElement() && this.path.container === parent.node.children) {
3943
- uid = jsxExpressionContainer(uid);
3944
- }
3945
- this.path.replaceWith(cloneNode$1(uid));
3946
- return attachTo.isVariableDeclarator() ? attached.get("init") : attached.get("declarations.0.init");
4193
+ if (!commonPath) {
4194
+ throw new Error("Internal Babel error - The two compared nodes" + " don't appear to belong to the same program.");
3947
4195
  }
3948
- }
3949
-
3950
- const {
3951
- arrowFunctionExpression,
3952
- assertExpression,
3953
- assignmentExpression,
3954
- blockStatement,
3955
- callExpression,
3956
- cloneNode,
3957
- expressionStatement,
3958
- isAssignmentExpression,
3959
- isCallExpression,
3960
- isExportNamedDeclaration,
3961
- isExpression,
3962
- isIdentifier,
3963
- isSequenceExpression,
3964
- isSuper,
3965
- thisExpression
3966
- } = _t;
3967
- function insertBefore(nodes_) {
3968
- this._assertUnremoved();
3969
- const nodes = this._verifyNodeList(nodes_);
3970
- const {
3971
- parentPath,
3972
- parent
3973
- } = this;
3974
- if (parentPath.isExpressionStatement() || parentPath.isLabeledStatement() || isExportNamedDeclaration(parent) || parentPath.isExportDefaultDeclaration() && this.isDeclaration()) {
3975
- return parentPath.insertBefore(nodes);
3976
- } else if (this.isNodeType("Expression") && !this.isJSXElement() || parentPath.isForStatement() && this.key === "init") {
3977
- if (this.node) nodes.push(this.node);
3978
- return this.replaceExpressionWithStatements(nodes);
3979
- } else if (Array.isArray(this.container)) {
3980
- return this._containerInsertBefore(nodes);
3981
- } else if (this.isStatementOrBlock()) {
3982
- const node = this.node;
3983
- const shouldInsertCurrentNode = node && (!this.isExpressionStatement() || node.expression != null);
3984
- this.replaceWith(blockStatement(shouldInsertCurrentNode ? [node] : []));
3985
- return this.unshiftContainer("body", nodes);
3986
- } else {
3987
- 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?");
4196
+ if (isExecutionUncertainInList(paths.this, commonIndex.this - 1) || isExecutionUncertainInList(paths.target, commonIndex.target - 1)) {
4197
+ return "unknown";
3988
4198
  }
3989
- }
3990
- function _containerInsert(from, nodes) {
3991
- this.updateSiblingKeys(from, nodes.length);
3992
- const paths = [];
3993
- this.container.splice(from, 0, ...nodes);
3994
- for (let i = 0; i < nodes.length; i++) {
3995
- const to = from + i;
3996
- const path = this.getSibling(to);
3997
- paths.push(path);
3998
- if (this.context?.queue) {
3999
- path.pushContext(this.context);
4199
+ const divergence = {
4200
+ this: paths.this[commonIndex.this - 1],
4201
+ target: paths.target[commonIndex.target - 1]
4202
+ };
4203
+ if (divergence.target.listKey && divergence.this.listKey && divergence.target.container === divergence.this.container) {
4204
+ return divergence.target.key > divergence.this.key ? "before" : "after";
4205
+ }
4206
+ const keys = VISITOR_KEYS$3[commonPath.type];
4207
+ const keyPosition = {
4208
+ this: keys.indexOf(divergence.this.parentKey),
4209
+ target: keys.indexOf(divergence.target.parentKey)
4210
+ };
4211
+ return keyPosition.target > keyPosition.this ? "before" : "after";
4212
+ }
4213
+ function _guessExecutionStatusRelativeToDifferentFunctionsInternal(base, target, cache) {
4214
+ if (!target.isFunctionDeclaration()) {
4215
+ if (_guessExecutionStatusRelativeToCached(base, target, cache) === "before") {
4216
+ return "before";
4000
4217
  }
4218
+ return "unknown";
4219
+ } else if (target.parentPath.isExportDeclaration()) {
4220
+ return "unknown";
4001
4221
  }
4002
- const contexts = this._getQueueContexts();
4003
- for (const path of paths) {
4004
- path.setScope();
4005
- path.debug("Inserted.");
4006
- for (const context of contexts) {
4007
- context.maybeQueue(path, true);
4222
+ const binding = target.scope.getBinding(target.node.id.name);
4223
+ if (!binding.references) return "before";
4224
+ const referencePaths = binding.referencePaths;
4225
+ let allStatus;
4226
+ for (const path of referencePaths) {
4227
+ const childOfFunction = !!path.find(path => path.node === target.node);
4228
+ if (childOfFunction) continue;
4229
+ if (path.key !== "callee" || !path.parentPath.isCallExpression()) {
4230
+ return "unknown";
4231
+ }
4232
+ const status = _guessExecutionStatusRelativeToCached(base, path, cache);
4233
+ if (allStatus && allStatus !== status) {
4234
+ return "unknown";
4235
+ } else {
4236
+ allStatus = status;
4008
4237
  }
4009
4238
  }
4010
- return paths;
4011
- }
4012
- function _containerInsertBefore(nodes) {
4013
- return this._containerInsert(this.key, nodes);
4239
+ return allStatus;
4014
4240
  }
4015
- function _containerInsertAfter(nodes) {
4016
- return this._containerInsert(this.key + 1, nodes);
4241
+ function _guessExecutionStatusRelativeToDifferentFunctionsCached(base, target, cache) {
4242
+ let nodeMap = cache.get(base.node);
4243
+ let cached;
4244
+ if (!nodeMap) {
4245
+ cache.set(base.node, nodeMap = new Map());
4246
+ } else if (cached = nodeMap.get(target.node)) {
4247
+ if (cached === SYMBOL_CHECKING) {
4248
+ return "unknown";
4249
+ }
4250
+ return cached;
4251
+ }
4252
+ nodeMap.set(target.node, SYMBOL_CHECKING);
4253
+ const result = _guessExecutionStatusRelativeToDifferentFunctionsInternal(base, target, cache);
4254
+ nodeMap.set(target.node, result);
4255
+ return result;
4017
4256
  }
4018
- const last = arr => arr[arr.length - 1];
4019
- function isHiddenInSequenceExpression(path) {
4020
- return isSequenceExpression(path.parent) && (last(path.parent.expressions) !== path.node || isHiddenInSequenceExpression(path.parentPath));
4257
+ function resolve(dangerous, resolved) {
4258
+ return _resolve.call(this, dangerous, resolved) || this;
4021
4259
  }
4022
- function isAlmostConstantAssignment(node, scope) {
4023
- if (!isAssignmentExpression(node) || !isIdentifier(node.left)) {
4024
- return false;
4260
+ function _resolve(dangerous, resolved) {
4261
+ if (resolved?.includes(this)) return;
4262
+ resolved = resolved || [];
4263
+ resolved.push(this);
4264
+ if (this.isVariableDeclarator()) {
4265
+ if (this.get("id").isIdentifier()) {
4266
+ return this.get("init").resolve(dangerous, resolved);
4267
+ }
4268
+ } else if (this.isReferencedIdentifier()) {
4269
+ const binding = this.scope.getBinding(this.node.name);
4270
+ if (!binding) return;
4271
+ if (!binding.constant) return;
4272
+ if (binding.kind === "module") return;
4273
+ if (binding.path !== this) {
4274
+ const ret = binding.path.resolve(dangerous, resolved);
4275
+ if (this.find(parent => parent.node === ret.node)) return;
4276
+ return ret;
4277
+ }
4278
+ } else if (this.isTypeCastExpression()) {
4279
+ return this.get("expression").resolve(dangerous, resolved);
4280
+ } else if (dangerous && this.isMemberExpression()) {
4281
+ const targetKey = this.toComputedKey();
4282
+ if (!isLiteral(targetKey)) return;
4283
+ const targetName = targetKey.value;
4284
+ const target = this.get("object").resolve(dangerous, resolved);
4285
+ if (target.isObjectExpression()) {
4286
+ const props = target.get("properties");
4287
+ for (const prop of props) {
4288
+ if (!prop.isProperty()) continue;
4289
+ const key = prop.get("key");
4290
+ let match = prop.isnt("computed") && key.isIdentifier({
4291
+ name: targetName
4292
+ });
4293
+ match = match || key.isLiteral({
4294
+ value: targetName
4295
+ });
4296
+ if (match) return prop.get("value").resolve(dangerous, resolved);
4297
+ }
4298
+ } else if (target.isArrayExpression() && !isNaN(+targetName)) {
4299
+ const elems = target.get("elements");
4300
+ const elem = elems[targetName];
4301
+ if (elem) return elem.resolve(dangerous, resolved);
4302
+ }
4025
4303
  }
4026
- const blockScope = scope.getBlockParent();
4027
- return blockScope.hasOwnBinding(node.left.name) && blockScope.getOwnBinding(node.left.name).constantViolations.length <= 1;
4028
4304
  }
4029
- function insertAfter(nodes_) {
4030
- this._assertUnremoved();
4031
- if (this.isSequenceExpression()) {
4032
- return last(this.get("expressions")).insertAfter(nodes_);
4305
+ function isConstantExpression() {
4306
+ if (this.isIdentifier()) {
4307
+ const binding = this.scope.getBinding(this.node.name);
4308
+ if (!binding) return false;
4309
+ return binding.constant;
4033
4310
  }
4034
- const nodes = this._verifyNodeList(nodes_);
4035
- const {
4036
- parentPath,
4037
- parent
4038
- } = this;
4039
- if (parentPath.isExpressionStatement() || parentPath.isLabeledStatement() || isExportNamedDeclaration(parent) || parentPath.isExportDefaultDeclaration() && this.isDeclaration()) {
4040
- return parentPath.insertAfter(nodes.map(node => {
4041
- return isExpression(node) ? expressionStatement(node) : node;
4042
- }));
4043
- } else if (this.isNodeType("Expression") && !this.isJSXElement() && !parentPath.isJSXElement() || parentPath.isForStatement() && this.key === "init") {
4044
- const self = this;
4045
- if (self.node) {
4046
- const node = self.node;
4047
- let {
4048
- scope
4049
- } = this;
4050
- if (scope.path.isPattern()) {
4051
- assertExpression(node);
4052
- self.replaceWith(callExpression(arrowFunctionExpression([], node), []));
4053
- self.get("callee.body").insertAfter(nodes);
4054
- return [self];
4055
- }
4056
- if (isHiddenInSequenceExpression(self)) {
4057
- nodes.unshift(node);
4058
- } else if (isCallExpression(node) && isSuper(node.callee)) {
4059
- nodes.unshift(node);
4060
- nodes.push(thisExpression());
4061
- } else if (isAlmostConstantAssignment(node, scope)) {
4062
- nodes.unshift(node);
4063
- nodes.push(cloneNode(node.left));
4064
- } else if (scope.isPure(node, true)) {
4065
- nodes.push(node);
4066
- } else {
4067
- if (parentPath.isMethod({
4068
- computed: true,
4069
- key: node
4070
- })) {
4071
- scope = scope.parent;
4072
- }
4073
- const temp = scope.generateDeclaredUidIdentifier();
4074
- nodes.unshift(expressionStatement(assignmentExpression("=", cloneNode(temp), node)));
4075
- nodes.push(expressionStatement(cloneNode(temp)));
4076
- }
4311
+ if (this.isLiteral()) {
4312
+ if (this.isRegExpLiteral()) {
4313
+ return false;
4077
4314
  }
4078
- return this.replaceExpressionWithStatements(nodes);
4079
- } else if (Array.isArray(this.container)) {
4080
- return this._containerInsertAfter(nodes);
4081
- } else if (this.isStatementOrBlock()) {
4082
- const node = this.node;
4083
- const shouldInsertCurrentNode = node && (!this.isExpressionStatement() || node.expression != null);
4084
- this.replaceWith(blockStatement(shouldInsertCurrentNode ? [node] : []));
4085
- return this.pushContainer("body", nodes);
4086
- } else {
4087
- 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?");
4315
+ if (this.isTemplateLiteral()) {
4316
+ return this.get("expressions").every(expression => expression.isConstantExpression());
4317
+ }
4318
+ return true;
4088
4319
  }
4089
- }
4090
- function updateSiblingKeys(fromIndex, incrementBy) {
4091
- if (!this.parent) return;
4092
- const paths = getCachedPaths(this.hub, this.parent) || [];
4093
- for (const [, path] of paths) {
4094
- if (typeof path.key === "number" && path.key >= fromIndex) {
4095
- path.key += incrementBy;
4320
+ if (this.isUnaryExpression()) {
4321
+ if (this.node.operator !== "void") {
4322
+ return false;
4096
4323
  }
4324
+ return this.get("argument").isConstantExpression();
4097
4325
  }
4098
- }
4099
- function _verifyNodeList(nodes) {
4100
- if (!nodes) {
4101
- return [];
4326
+ if (this.isBinaryExpression()) {
4327
+ const {
4328
+ operator
4329
+ } = this.node;
4330
+ return operator !== "in" && operator !== "instanceof" && this.get("left").isConstantExpression() && this.get("right").isConstantExpression();
4102
4331
  }
4103
- if (!Array.isArray(nodes)) {
4104
- nodes = [nodes];
4332
+ if (this.isMemberExpression()) {
4333
+ return !this.node.computed && this.get("object").isIdentifier({
4334
+ name: "Symbol"
4335
+ }) && !this.scope.hasBinding("Symbol", {
4336
+ noGlobals: true
4337
+ });
4105
4338
  }
4106
- for (let i = 0; i < nodes.length; i++) {
4107
- const node = nodes[i];
4108
- let msg;
4109
- if (!node) {
4110
- msg = "has falsy node";
4111
- } else if (typeof node !== "object") {
4112
- msg = "contains a non-object node";
4113
- } else if (!node.type) {
4114
- msg = "without a type";
4115
- } else if (node instanceof NodePath_Final) {
4116
- msg = "has a NodePath when it expected a raw object";
4117
- }
4118
- if (msg) {
4119
- const type = Array.isArray(node) ? "array" : typeof node;
4120
- throw new Error(`Node list ${msg} with the index of ${i} and type of ${type}`);
4121
- }
4339
+ if (this.isCallExpression()) {
4340
+ return this.node.arguments.length === 1 && this.get("callee").matchesPattern("Symbol.for") && !this.scope.hasBinding("Symbol", {
4341
+ noGlobals: true
4342
+ }) && this.get("arguments")[0].isStringLiteral();
4122
4343
  }
4123
- return nodes;
4124
- }
4125
- function unshiftContainer(listKey, nodes) {
4126
- this._assertUnremoved();
4127
- nodes = this._verifyNodeList(nodes);
4128
- const path = NodePath_Final.get({
4129
- parentPath: this,
4130
- parent: this.node,
4131
- container: this.node[listKey],
4132
- listKey,
4133
- key: 0
4134
- }).setContext(this.context);
4135
- return path._containerInsertBefore(nodes);
4136
- }
4137
- function pushContainer(listKey, nodes) {
4138
- this._assertUnremoved();
4139
- const verifiedNodes = this._verifyNodeList(nodes);
4140
- const container = this.node[listKey];
4141
- const path = NodePath_Final.get({
4142
- parentPath: this,
4143
- parent: this.node,
4144
- container: container,
4145
- listKey,
4146
- key: container.length
4147
- }).setContext(this.context);
4148
- return path.replaceWithMultiple(verifiedNodes);
4344
+ return false;
4149
4345
  }
4150
- function hoist(scope = this.scope) {
4151
- const hoister = new PathHoister(this, scope);
4152
- return hoister.run();
4346
+ function isInStrictMode() {
4347
+ const start = this.isProgram() ? this : this.parentPath;
4348
+ const strictParent = start.find(path => {
4349
+ if (path.isProgram({
4350
+ sourceType: "module"
4351
+ })) return true;
4352
+ if (path.isClass()) return true;
4353
+ if (path.isArrowFunctionExpression() && !path.get("body").isBlockStatement()) {
4354
+ return false;
4355
+ }
4356
+ let body;
4357
+ if (path.isFunction()) {
4358
+ body = path.node.body;
4359
+ } else if (path.isProgram()) {
4360
+ body = path.node;
4361
+ } else {
4362
+ return false;
4363
+ }
4364
+ for (const directive of body.directives) {
4365
+ if (directive.value.value === "use strict") {
4366
+ return true;
4367
+ }
4368
+ }
4369
+ });
4370
+ return !!strictParent;
4153
4371
  }
4154
4372
 
4155
4373
  const {
4374
+ getAssignmentIdentifiers: _getAssignmentIdentifiers,
4156
4375
  getBindingIdentifiers: _getBindingIdentifiers,
4157
4376
  getOuterBindingIdentifiers: _getOuterBindingIdentifiers,
4158
4377
  numericLiteral,
@@ -4365,9 +4584,9 @@ function get(key, context = true) {
4365
4584
  if (context === true) context = this.context;
4366
4585
  const parts = key.split(".");
4367
4586
  if (parts.length === 1) {
4368
- return this._getKey(key, context);
4587
+ return _getKey.call(this, key, context);
4369
4588
  } else {
4370
- return this._getPattern(parts, context);
4589
+ return _getPattern.call(this, parts, context);
4371
4590
  }
4372
4591
  }
4373
4592
  function _getKey(key, context) {
@@ -4407,6 +4626,9 @@ function _getPattern(parts, context) {
4407
4626
  }
4408
4627
  return path;
4409
4628
  }
4629
+ function getAssignmentIdentifiers() {
4630
+ return _getAssignmentIdentifiers(this.node);
4631
+ }
4410
4632
  function getBindingIdentifiers(duplicates) {
4411
4633
  return _getBindingIdentifiers(this.node, duplicates);
4412
4634
  }
@@ -4646,7 +4868,6 @@ const methods = {
4646
4868
  isDescendant: isDescendant,
4647
4869
  inType: inType,
4648
4870
  getTypeAnnotation: getTypeAnnotation,
4649
- _getTypeAnnotation: _getTypeAnnotation,
4650
4871
  isBaseType: isBaseType,
4651
4872
  couldBeBaseType: couldBeBaseType,
4652
4873
  baseTypeStrictlyMatches: baseTypeStrictlyMatches,
@@ -4654,7 +4875,6 @@ const methods = {
4654
4875
  replaceWithMultiple: replaceWithMultiple,
4655
4876
  replaceWithSourceString: replaceWithSourceString,
4656
4877
  replaceWith: replaceWith,
4657
- _replaceWith: _replaceWith,
4658
4878
  replaceExpressionWithStatements: replaceExpressionWithStatements,
4659
4879
  replaceInline: replaceInline,
4660
4880
  evaluateTruthy: evaluateTruthy,
@@ -4663,6 +4883,8 @@ const methods = {
4663
4883
  ensureBlock: ensureBlock,
4664
4884
  unwrapFunctionEnvironment: unwrapFunctionEnvironment,
4665
4885
  arrowFunctionToExpression: arrowFunctionToExpression,
4886
+ splitExportDeclaration: splitExportDeclaration,
4887
+ ensureFunctionName: ensureFunctionName,
4666
4888
  matchesPattern: matchesPattern,
4667
4889
  has: has,
4668
4890
  isStatic: isStatic,
@@ -4679,11 +4901,9 @@ const methods = {
4679
4901
  willIMaybeExecuteBefore: willIMaybeExecuteBefore,
4680
4902
  _guessExecutionStatusRelativeTo: _guessExecutionStatusRelativeTo,
4681
4903
  resolve: resolve,
4682
- _resolve: _resolve,
4683
4904
  isConstantExpression: isConstantExpression,
4684
4905
  isInStrictMode: isInStrictMode,
4685
4906
  call: call,
4686
- _call: _call,
4687
4907
  isDenylisted: isDenylisted,
4688
4908
  isBlacklisted: isDenylisted,
4689
4909
  visit: visit,
@@ -4693,29 +4913,16 @@ const methods = {
4693
4913
  setScope: setScope,
4694
4914
  setContext: setContext,
4695
4915
  resync: resync,
4696
- _resyncParent: _resyncParent,
4697
- _resyncKey: _resyncKey,
4698
- _resyncList: _resyncList,
4699
- _resyncRemoved: _resyncRemoved,
4700
4916
  popContext: popContext,
4701
4917
  pushContext: pushContext,
4702
4918
  setup: setup,
4703
4919
  setKey: setKey,
4704
4920
  requeue: requeue,
4705
- _getQueueContexts: _getQueueContexts,
4921
+ requeueComputedKeyAndDecorators: requeueComputedKeyAndDecorators,
4706
4922
  remove: remove,
4707
- _removeFromScope: _removeFromScope,
4708
- _callRemovalHooks: _callRemovalHooks,
4709
- _remove: _remove,
4710
- _markRemoved: _markRemoved,
4711
- _assertUnremoved: _assertUnremoved,
4712
4923
  insertBefore: insertBefore,
4713
- _containerInsert: _containerInsert,
4714
- _containerInsertBefore: _containerInsertBefore,
4715
- _containerInsertAfter: _containerInsertAfter,
4716
4924
  insertAfter: insertAfter,
4717
4925
  updateSiblingKeys: updateSiblingKeys,
4718
- _verifyNodeList: _verifyNodeList,
4719
4926
  unshiftContainer: unshiftContainer,
4720
4927
  pushContainer: pushContainer,
4721
4928
  hoist: hoist,
@@ -4727,8 +4934,7 @@ const methods = {
4727
4934
  getAllNextSiblings: getAllNextSiblings,
4728
4935
  getAllPrevSiblings: getAllPrevSiblings,
4729
4936
  get: get,
4730
- _getKey: _getKey,
4731
- _getPattern: _getPattern,
4937
+ getAssignmentIdentifiers: getAssignmentIdentifiers,
4732
4938
  getBindingIdentifiers: getBindingIdentifiers,
4733
4939
  getOuterBindingIdentifiers: getOuterBindingIdentifiers,
4734
4940
  getBindingIdentifierPaths: getBindingIdentifierPaths,