index.js 17 KB

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