index.js 18 KB

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