index.js 18 KB

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