index.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _helperPluginUtils = require("@babel/helper-plugin-utils");
  7. var _core = require("@babel/core");
  8. var _default = (0, _helperPluginUtils.declare)((api, options) => {
  9. var _api$assumption, _options$allowArrayLi, _api$assumption2;
  10. api.assertVersion(7);
  11. const {
  12. useBuiltIns = false
  13. } = options;
  14. const iterableIsArray = (_api$assumption = api.assumption("iterableIsArray")) != null ? _api$assumption : options.loose;
  15. const arrayLikeIsIterable = (_options$allowArrayLi = options.allowArrayLike) != null ? _options$allowArrayLi : api.assumption("arrayLikeIsIterable");
  16. const objectRestNoSymbols = (_api$assumption2 = api.assumption("objectRestNoSymbols")) != null ? _api$assumption2 : options.loose;
  17. function getExtendsHelper(file) {
  18. return useBuiltIns ? _core.types.memberExpression(_core.types.identifier("Object"), _core.types.identifier("assign")) : file.addHelper("extends");
  19. }
  20. function variableDeclarationHasPattern(node) {
  21. for (const declar of node.declarations) {
  22. if (_core.types.isPattern(declar.id)) {
  23. return true;
  24. }
  25. }
  26. return false;
  27. }
  28. function hasRest(pattern) {
  29. for (const elem of pattern.elements) {
  30. if (_core.types.isRestElement(elem)) {
  31. return true;
  32. }
  33. }
  34. return false;
  35. }
  36. function hasObjectRest(pattern) {
  37. for (const elem of pattern.properties) {
  38. if (_core.types.isRestElement(elem)) {
  39. return true;
  40. }
  41. }
  42. return false;
  43. }
  44. const STOP_TRAVERSAL = {};
  45. const arrayUnpackVisitor = (node, ancestors, state) => {
  46. if (!ancestors.length) {
  47. return;
  48. }
  49. if (_core.types.isIdentifier(node) && _core.types.isReferenced(node, ancestors[ancestors.length - 1]) && state.bindings[node.name]) {
  50. state.deopt = true;
  51. throw STOP_TRAVERSAL;
  52. }
  53. };
  54. class DestructuringTransformer {
  55. constructor(opts) {
  56. this.blockHoist = void 0;
  57. this.operator = void 0;
  58. this.arrays = void 0;
  59. this.nodes = void 0;
  60. this.scope = void 0;
  61. this.kind = void 0;
  62. this.iterableIsArray = void 0;
  63. this.arrayLikeIsIterable = void 0;
  64. this.addHelper = void 0;
  65. this.blockHoist = opts.blockHoist;
  66. this.operator = opts.operator;
  67. this.arrays = {};
  68. this.nodes = opts.nodes || [];
  69. this.scope = opts.scope;
  70. this.kind = opts.kind;
  71. this.iterableIsArray = opts.iterableIsArray;
  72. this.arrayLikeIsIterable = opts.arrayLikeIsIterable;
  73. this.addHelper = opts.addHelper;
  74. }
  75. buildVariableAssignment(id, init) {
  76. let op = this.operator;
  77. if (_core.types.isMemberExpression(id)) op = "=";
  78. let node;
  79. if (op) {
  80. node = _core.types.expressionStatement(_core.types.assignmentExpression(op, id, _core.types.cloneNode(init) || this.scope.buildUndefinedNode()));
  81. } else {
  82. let nodeInit;
  83. if (this.kind === "const" && init === null) {
  84. nodeInit = this.scope.buildUndefinedNode();
  85. } else {
  86. nodeInit = _core.types.cloneNode(init);
  87. }
  88. node = _core.types.variableDeclaration(this.kind, [_core.types.variableDeclarator(id, nodeInit)]);
  89. }
  90. node._blockHoist = this.blockHoist;
  91. return node;
  92. }
  93. buildVariableDeclaration(id, init) {
  94. const declar = _core.types.variableDeclaration("var", [_core.types.variableDeclarator(_core.types.cloneNode(id), _core.types.cloneNode(init))]);
  95. declar._blockHoist = this.blockHoist;
  96. return declar;
  97. }
  98. push(id, _init) {
  99. const init = _core.types.cloneNode(_init);
  100. if (_core.types.isObjectPattern(id)) {
  101. this.pushObjectPattern(id, init);
  102. } else if (_core.types.isArrayPattern(id)) {
  103. this.pushArrayPattern(id, init);
  104. } else if (_core.types.isAssignmentPattern(id)) {
  105. this.pushAssignmentPattern(id, init);
  106. } else {
  107. this.nodes.push(this.buildVariableAssignment(id, init));
  108. }
  109. }
  110. toArray(node, count) {
  111. if (this.iterableIsArray || _core.types.isIdentifier(node) && this.arrays[node.name]) {
  112. return node;
  113. } else {
  114. return this.scope.toArray(node, count, this.arrayLikeIsIterable);
  115. }
  116. }
  117. pushAssignmentPattern({
  118. left,
  119. right
  120. }, valueRef) {
  121. if (valueRef === null) {
  122. this.nodes.push(this.buildVariableAssignment(left, right));
  123. return;
  124. }
  125. const tempId = this.scope.generateUidIdentifierBasedOnNode(valueRef);
  126. this.nodes.push(this.buildVariableDeclaration(tempId, valueRef));
  127. const tempConditional = _core.types.conditionalExpression(_core.types.binaryExpression("===", _core.types.cloneNode(tempId), this.scope.buildUndefinedNode()), right, _core.types.cloneNode(tempId));
  128. if (_core.types.isPattern(left)) {
  129. let patternId;
  130. let node;
  131. if (this.kind === "const" || this.kind === "let") {
  132. patternId = this.scope.generateUidIdentifier(tempId.name);
  133. node = this.buildVariableDeclaration(patternId, tempConditional);
  134. } else {
  135. patternId = tempId;
  136. node = _core.types.expressionStatement(_core.types.assignmentExpression("=", _core.types.cloneNode(tempId), tempConditional));
  137. }
  138. this.nodes.push(node);
  139. this.push(left, patternId);
  140. } else {
  141. this.nodes.push(this.buildVariableAssignment(left, tempConditional));
  142. }
  143. }
  144. pushObjectRest(pattern, objRef, spreadProp, spreadPropIndex) {
  145. const keys = [];
  146. let allLiteral = true;
  147. let hasTemplateLiteral = false;
  148. for (let i = 0; i < pattern.properties.length; i++) {
  149. const prop = pattern.properties[i];
  150. if (i >= spreadPropIndex) break;
  151. if (_core.types.isRestElement(prop)) continue;
  152. const key = prop.key;
  153. if (_core.types.isIdentifier(key) && !prop.computed) {
  154. keys.push(_core.types.stringLiteral(key.name));
  155. } else if (_core.types.isTemplateLiteral(key)) {
  156. keys.push(_core.types.cloneNode(key));
  157. hasTemplateLiteral = true;
  158. } else if (_core.types.isLiteral(key)) {
  159. keys.push(_core.types.stringLiteral(String(key.value)));
  160. } else {
  161. keys.push(_core.types.cloneNode(key));
  162. allLiteral = false;
  163. }
  164. }
  165. let value;
  166. if (keys.length === 0) {
  167. value = _core.types.callExpression(getExtendsHelper(this), [_core.types.objectExpression([]), _core.types.cloneNode(objRef)]);
  168. } else {
  169. let keyExpression = _core.types.arrayExpression(keys);
  170. if (!allLiteral) {
  171. keyExpression = _core.types.callExpression(_core.types.memberExpression(keyExpression, _core.types.identifier("map")), [this.addHelper("toPropertyKey")]);
  172. } else if (!hasTemplateLiteral && !_core.types.isProgram(this.scope.block)) {
  173. const program = this.scope.path.findParent(path => path.isProgram());
  174. const id = this.scope.generateUidIdentifier("excluded");
  175. program.scope.push({
  176. id,
  177. init: keyExpression,
  178. kind: "const"
  179. });
  180. keyExpression = _core.types.cloneNode(id);
  181. }
  182. value = _core.types.callExpression(this.addHelper(`objectWithoutProperties${objectRestNoSymbols ? "Loose" : ""}`), [_core.types.cloneNode(objRef), keyExpression]);
  183. }
  184. this.nodes.push(this.buildVariableAssignment(spreadProp.argument, value));
  185. }
  186. pushObjectProperty(prop, propRef) {
  187. if (_core.types.isLiteral(prop.key)) prop.computed = true;
  188. const pattern = prop.value;
  189. const objRef = _core.types.memberExpression(_core.types.cloneNode(propRef), prop.key, prop.computed);
  190. if (_core.types.isPattern(pattern)) {
  191. this.push(pattern, objRef);
  192. } else {
  193. this.nodes.push(this.buildVariableAssignment(pattern, objRef));
  194. }
  195. }
  196. pushObjectPattern(pattern, objRef) {
  197. if (!pattern.properties.length) {
  198. this.nodes.push(_core.types.expressionStatement(_core.types.callExpression(this.addHelper("objectDestructuringEmpty"), [objRef])));
  199. }
  200. if (pattern.properties.length > 1 && !this.scope.isStatic(objRef)) {
  201. const temp = this.scope.generateUidIdentifierBasedOnNode(objRef);
  202. this.nodes.push(this.buildVariableDeclaration(temp, objRef));
  203. objRef = temp;
  204. }
  205. if (hasObjectRest(pattern)) {
  206. let copiedPattern;
  207. for (let i = 0; i < pattern.properties.length; i++) {
  208. const prop = pattern.properties[i];
  209. if (_core.types.isRestElement(prop)) {
  210. break;
  211. }
  212. const key = prop.key;
  213. if (prop.computed && !this.scope.isPure(key)) {
  214. const name = this.scope.generateUidIdentifierBasedOnNode(key);
  215. this.nodes.push(this.buildVariableDeclaration(name, key));
  216. if (!copiedPattern) {
  217. copiedPattern = pattern = Object.assign({}, pattern, {
  218. properties: pattern.properties.slice()
  219. });
  220. }
  221. copiedPattern.properties[i] = Object.assign({}, copiedPattern.properties[i], {
  222. key: name
  223. });
  224. }
  225. }
  226. }
  227. for (let i = 0; i < pattern.properties.length; i++) {
  228. const prop = pattern.properties[i];
  229. if (_core.types.isRestElement(prop)) {
  230. this.pushObjectRest(pattern, objRef, prop, i);
  231. } else {
  232. this.pushObjectProperty(prop, objRef);
  233. }
  234. }
  235. }
  236. canUnpackArrayPattern(pattern, arr) {
  237. if (!_core.types.isArrayExpression(arr)) return false;
  238. if (pattern.elements.length > arr.elements.length) return;
  239. if (pattern.elements.length < arr.elements.length && !hasRest(pattern)) {
  240. return false;
  241. }
  242. for (const elem of pattern.elements) {
  243. if (!elem) return false;
  244. if (_core.types.isMemberExpression(elem)) return false;
  245. }
  246. for (const elem of arr.elements) {
  247. if (_core.types.isSpreadElement(elem)) return false;
  248. if (_core.types.isCallExpression(elem)) return false;
  249. if (_core.types.isMemberExpression(elem)) return false;
  250. }
  251. const bindings = _core.types.getBindingIdentifiers(pattern);
  252. const state = {
  253. deopt: false,
  254. bindings
  255. };
  256. try {
  257. _core.types.traverse(arr, arrayUnpackVisitor, state);
  258. } catch (e) {
  259. if (e !== STOP_TRAVERSAL) throw e;
  260. }
  261. return !state.deopt;
  262. }
  263. pushUnpackedArrayPattern(pattern, arr) {
  264. for (let i = 0; i < pattern.elements.length; i++) {
  265. const elem = pattern.elements[i];
  266. if (_core.types.isRestElement(elem)) {
  267. this.push(elem.argument, _core.types.arrayExpression(arr.elements.slice(i)));
  268. } else {
  269. this.push(elem, arr.elements[i]);
  270. }
  271. }
  272. }
  273. pushArrayPattern(pattern, arrayRef) {
  274. if (!pattern.elements) return;
  275. if (this.canUnpackArrayPattern(pattern, arrayRef)) {
  276. return this.pushUnpackedArrayPattern(pattern, arrayRef);
  277. }
  278. const count = !hasRest(pattern) && pattern.elements.length;
  279. const toArray = this.toArray(arrayRef, count);
  280. if (_core.types.isIdentifier(toArray)) {
  281. arrayRef = toArray;
  282. } else {
  283. arrayRef = this.scope.generateUidIdentifierBasedOnNode(arrayRef);
  284. this.arrays[arrayRef.name] = true;
  285. this.nodes.push(this.buildVariableDeclaration(arrayRef, toArray));
  286. }
  287. for (let i = 0; i < pattern.elements.length; i++) {
  288. let elem = pattern.elements[i];
  289. if (!elem) continue;
  290. let elemRef;
  291. if (_core.types.isRestElement(elem)) {
  292. elemRef = this.toArray(arrayRef);
  293. elemRef = _core.types.callExpression(_core.types.memberExpression(elemRef, _core.types.identifier("slice")), [_core.types.numericLiteral(i)]);
  294. elem = elem.argument;
  295. } else {
  296. elemRef = _core.types.memberExpression(arrayRef, _core.types.numericLiteral(i), true);
  297. }
  298. this.push(elem, elemRef);
  299. }
  300. }
  301. init(pattern, ref) {
  302. if (!_core.types.isArrayExpression(ref) && !_core.types.isMemberExpression(ref)) {
  303. const memo = this.scope.maybeGenerateMemoised(ref, true);
  304. if (memo) {
  305. this.nodes.push(this.buildVariableDeclaration(memo, _core.types.cloneNode(ref)));
  306. ref = memo;
  307. }
  308. }
  309. this.push(pattern, ref);
  310. return this.nodes;
  311. }
  312. }
  313. return {
  314. name: "transform-destructuring",
  315. visitor: {
  316. ExportNamedDeclaration(path) {
  317. const declaration = path.get("declaration");
  318. if (!declaration.isVariableDeclaration()) return;
  319. if (!variableDeclarationHasPattern(declaration.node)) return;
  320. const specifiers = [];
  321. for (const name of Object.keys(path.getOuterBindingIdentifiers(path))) {
  322. specifiers.push(_core.types.exportSpecifier(_core.types.identifier(name), _core.types.identifier(name)));
  323. }
  324. path.replaceWith(declaration.node);
  325. path.insertAfter(_core.types.exportNamedDeclaration(null, specifiers));
  326. },
  327. ForXStatement(path) {
  328. const {
  329. node,
  330. scope
  331. } = path;
  332. const left = node.left;
  333. if (_core.types.isPattern(left)) {
  334. const temp = scope.generateUidIdentifier("ref");
  335. node.left = _core.types.variableDeclaration("var", [_core.types.variableDeclarator(temp)]);
  336. path.ensureBlock();
  337. if (node.body.body.length === 0 && path.isCompletionRecord()) {
  338. node.body.body.unshift(_core.types.expressionStatement(scope.buildUndefinedNode()));
  339. }
  340. node.body.body.unshift(_core.types.expressionStatement(_core.types.assignmentExpression("=", left, temp)));
  341. return;
  342. }
  343. if (!_core.types.isVariableDeclaration(left)) return;
  344. const pattern = left.declarations[0].id;
  345. if (!_core.types.isPattern(pattern)) return;
  346. const key = scope.generateUidIdentifier("ref");
  347. node.left = _core.types.variableDeclaration(left.kind, [_core.types.variableDeclarator(key, null)]);
  348. const nodes = [];
  349. const destructuring = new DestructuringTransformer({
  350. kind: left.kind,
  351. scope: scope,
  352. nodes: nodes,
  353. iterableIsArray,
  354. arrayLikeIsIterable,
  355. addHelper: name => this.addHelper(name)
  356. });
  357. destructuring.init(pattern, key);
  358. path.ensureBlock();
  359. const block = node.body;
  360. block.body = nodes.concat(block.body);
  361. },
  362. CatchClause({
  363. node,
  364. scope
  365. }) {
  366. const pattern = node.param;
  367. if (!_core.types.isPattern(pattern)) return;
  368. const ref = scope.generateUidIdentifier("ref");
  369. node.param = ref;
  370. const nodes = [];
  371. const destructuring = new DestructuringTransformer({
  372. kind: "let",
  373. scope: scope,
  374. nodes: nodes,
  375. iterableIsArray,
  376. arrayLikeIsIterable,
  377. addHelper: name => this.addHelper(name)
  378. });
  379. destructuring.init(pattern, ref);
  380. node.body.body = nodes.concat(node.body.body);
  381. },
  382. AssignmentExpression(path) {
  383. const {
  384. node,
  385. scope
  386. } = path;
  387. if (!_core.types.isPattern(node.left)) return;
  388. const nodes = [];
  389. const destructuring = new DestructuringTransformer({
  390. operator: node.operator,
  391. scope: scope,
  392. nodes: nodes,
  393. iterableIsArray,
  394. arrayLikeIsIterable,
  395. addHelper: name => this.addHelper(name)
  396. });
  397. let ref;
  398. if (path.isCompletionRecord() || !path.parentPath.isExpressionStatement()) {
  399. ref = scope.generateUidIdentifierBasedOnNode(node.right, "ref");
  400. nodes.push(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(ref, node.right)]));
  401. if (_core.types.isArrayExpression(node.right)) {
  402. destructuring.arrays[ref.name] = true;
  403. }
  404. }
  405. destructuring.init(node.left, ref || node.right);
  406. if (ref) {
  407. if (path.parentPath.isArrowFunctionExpression()) {
  408. path.replaceWith(_core.types.blockStatement([]));
  409. nodes.push(_core.types.returnStatement(_core.types.cloneNode(ref)));
  410. } else {
  411. nodes.push(_core.types.expressionStatement(_core.types.cloneNode(ref)));
  412. }
  413. }
  414. path.replaceWithMultiple(nodes);
  415. path.scope.crawl();
  416. },
  417. VariableDeclaration(path) {
  418. const {
  419. node,
  420. scope,
  421. parent
  422. } = path;
  423. if (_core.types.isForXStatement(parent)) return;
  424. if (!parent || !path.container) return;
  425. if (!variableDeclarationHasPattern(node)) return;
  426. const nodeKind = node.kind;
  427. const nodeLoc = node.loc;
  428. const nodes = [];
  429. let declar;
  430. for (let i = 0; i < node.declarations.length; i++) {
  431. declar = node.declarations[i];
  432. const patternId = declar.init;
  433. const pattern = declar.id;
  434. const destructuring = new DestructuringTransformer({
  435. blockHoist: node._blockHoist,
  436. nodes: nodes,
  437. scope: scope,
  438. kind: node.kind,
  439. iterableIsArray,
  440. arrayLikeIsIterable,
  441. addHelper: name => this.addHelper(name)
  442. });
  443. if (_core.types.isPattern(pattern)) {
  444. destructuring.init(pattern, patternId);
  445. if (+i !== node.declarations.length - 1) {
  446. _core.types.inherits(nodes[nodes.length - 1], declar);
  447. }
  448. } else {
  449. nodes.push(_core.types.inherits(destructuring.buildVariableAssignment(declar.id, _core.types.cloneNode(declar.init)), declar));
  450. }
  451. }
  452. let tail = null;
  453. const nodesOut = [];
  454. for (const node of nodes) {
  455. if (tail !== null && _core.types.isVariableDeclaration(node)) {
  456. tail.declarations.push(...node.declarations);
  457. } else {
  458. node.kind = nodeKind;
  459. if (!node.loc) {
  460. node.loc = nodeLoc;
  461. }
  462. nodesOut.push(node);
  463. tail = _core.types.isVariableDeclaration(node) ? node : null;
  464. }
  465. }
  466. for (const nodeOut of nodesOut) {
  467. if (!nodeOut.declarations) continue;
  468. for (const declaration of nodeOut.declarations) {
  469. const {
  470. name
  471. } = declaration.id;
  472. if (scope.bindings[name]) {
  473. scope.bindings[name].kind = nodeOut.kind;
  474. }
  475. }
  476. }
  477. if (nodesOut.length === 1) {
  478. path.replaceWith(nodesOut[0]);
  479. } else {
  480. path.replaceWithMultiple(nodesOut);
  481. }
  482. }
  483. }
  484. };
  485. });
  486. exports.default = _default;