index.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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 _pluginSyntaxObjectRestSpread = require("@babel/plugin-syntax-object-rest-spread");
  8. var _core = require("@babel/core");
  9. var _pluginTransformParameters = require("@babel/plugin-transform-parameters");
  10. var _helperCompilationTargets = require("@babel/helper-compilation-targets");
  11. var _corejs2BuiltIns = require("@babel/compat-data/corejs2-built-ins");
  12. const ZERO_REFS = (() => {
  13. const node = _core.types.identifier("a");
  14. const property = _core.types.objectProperty(_core.types.identifier("key"), node);
  15. const pattern = _core.types.objectPattern([property]);
  16. return _core.types.isReferenced(node, property, pattern) ? 1 : 0;
  17. })();
  18. var _default = (0, _helperPluginUtils.declare)((api, opts) => {
  19. var _api$assumption, _api$assumption2, _api$assumption3, _api$assumption4;
  20. api.assertVersion(7);
  21. const targets = api.targets();
  22. const supportsObjectAssign = !(0, _helperCompilationTargets.isRequired)("es6.object.assign", targets, {
  23. compatData: _corejs2BuiltIns
  24. });
  25. const {
  26. useBuiltIns = supportsObjectAssign,
  27. loose = false
  28. } = opts;
  29. if (typeof loose !== "boolean") {
  30. throw new Error(".loose must be a boolean, or undefined");
  31. }
  32. const ignoreFunctionLength = (_api$assumption = api.assumption("ignoreFunctionLength")) != null ? _api$assumption : loose;
  33. const objectRestNoSymbols = (_api$assumption2 = api.assumption("objectRestNoSymbols")) != null ? _api$assumption2 : loose;
  34. const pureGetters = (_api$assumption3 = api.assumption("pureGetters")) != null ? _api$assumption3 : loose;
  35. const setSpreadProperties = (_api$assumption4 = api.assumption("setSpreadProperties")) != null ? _api$assumption4 : loose;
  36. function getExtendsHelper(file) {
  37. return useBuiltIns ? _core.types.memberExpression(_core.types.identifier("Object"), _core.types.identifier("assign")) : file.addHelper("extends");
  38. }
  39. function hasRestElement(path) {
  40. let foundRestElement = false;
  41. visitRestElements(path, restElement => {
  42. foundRestElement = true;
  43. restElement.stop();
  44. });
  45. return foundRestElement;
  46. }
  47. function hasObjectPatternRestElement(path) {
  48. let foundRestElement = false;
  49. visitRestElements(path, restElement => {
  50. if (restElement.parentPath.isObjectPattern()) {
  51. foundRestElement = true;
  52. restElement.stop();
  53. }
  54. });
  55. return foundRestElement;
  56. }
  57. function visitRestElements(path, visitor) {
  58. path.traverse({
  59. Expression(path) {
  60. const parentType = path.parent.type;
  61. if (parentType === "AssignmentPattern" && path.key === "right" || parentType === "ObjectProperty" && path.parent.computed && path.key === "key") {
  62. path.skip();
  63. }
  64. },
  65. RestElement: visitor
  66. });
  67. }
  68. function hasSpread(node) {
  69. for (const prop of node.properties) {
  70. if (_core.types.isSpreadElement(prop)) {
  71. return true;
  72. }
  73. }
  74. return false;
  75. }
  76. function extractNormalizedKeys(path) {
  77. const props = path.node.properties;
  78. const keys = [];
  79. let allLiteral = true;
  80. for (const prop of props) {
  81. if (_core.types.isIdentifier(prop.key) && !prop.computed) {
  82. keys.push(_core.types.stringLiteral(prop.key.name));
  83. } else if (_core.types.isTemplateLiteral(prop.key)) {
  84. keys.push(_core.types.cloneNode(prop.key));
  85. } else if (_core.types.isLiteral(prop.key)) {
  86. keys.push(_core.types.stringLiteral(String(prop.key.value)));
  87. } else {
  88. keys.push(_core.types.cloneNode(prop.key));
  89. allLiteral = false;
  90. }
  91. }
  92. return {
  93. keys,
  94. allLiteral
  95. };
  96. }
  97. function replaceImpureComputedKeys(properties, scope) {
  98. const impureComputedPropertyDeclarators = [];
  99. for (const propPath of properties) {
  100. const key = propPath.get("key");
  101. if (propPath.node.computed && !key.isPure()) {
  102. const name = scope.generateUidBasedOnNode(key.node);
  103. const declarator = _core.types.variableDeclarator(_core.types.identifier(name), key.node);
  104. impureComputedPropertyDeclarators.push(declarator);
  105. key.replaceWith(_core.types.identifier(name));
  106. }
  107. }
  108. return impureComputedPropertyDeclarators;
  109. }
  110. function removeUnusedExcludedKeys(path) {
  111. const bindings = path.getOuterBindingIdentifierPaths();
  112. Object.keys(bindings).forEach(bindingName => {
  113. const bindingParentPath = bindings[bindingName].parentPath;
  114. if (path.scope.getBinding(bindingName).references > ZERO_REFS || !bindingParentPath.isObjectProperty()) {
  115. return;
  116. }
  117. bindingParentPath.remove();
  118. });
  119. }
  120. function createObjectRest(path, file, objRef) {
  121. const props = path.get("properties");
  122. const last = props[props.length - 1];
  123. _core.types.assertRestElement(last.node);
  124. const restElement = _core.types.cloneNode(last.node);
  125. last.remove();
  126. const impureComputedPropertyDeclarators = replaceImpureComputedKeys(path.get("properties"), path.scope);
  127. const {
  128. keys,
  129. allLiteral
  130. } = extractNormalizedKeys(path);
  131. if (keys.length === 0) {
  132. return [impureComputedPropertyDeclarators, restElement.argument, _core.types.callExpression(getExtendsHelper(file), [_core.types.objectExpression([]), _core.types.cloneNode(objRef)])];
  133. }
  134. let keyExpression;
  135. if (!allLiteral) {
  136. keyExpression = _core.types.callExpression(_core.types.memberExpression(_core.types.arrayExpression(keys), _core.types.identifier("map")), [file.addHelper("toPropertyKey")]);
  137. } else {
  138. keyExpression = _core.types.arrayExpression(keys);
  139. if (!_core.types.isProgram(path.scope.block)) {
  140. const program = path.findParent(path => path.isProgram());
  141. const id = path.scope.generateUidIdentifier("excluded");
  142. program.scope.push({
  143. id,
  144. init: keyExpression,
  145. kind: "const"
  146. });
  147. keyExpression = _core.types.cloneNode(id);
  148. }
  149. }
  150. return [impureComputedPropertyDeclarators, restElement.argument, _core.types.callExpression(file.addHelper(`objectWithoutProperties${objectRestNoSymbols ? "Loose" : ""}`), [_core.types.cloneNode(objRef), keyExpression])];
  151. }
  152. function replaceRestElement(parentPath, paramPath, container) {
  153. if (paramPath.isAssignmentPattern()) {
  154. replaceRestElement(parentPath, paramPath.get("left"), container);
  155. return;
  156. }
  157. if (paramPath.isArrayPattern() && hasRestElement(paramPath)) {
  158. const elements = paramPath.get("elements");
  159. for (let i = 0; i < elements.length; i++) {
  160. replaceRestElement(parentPath, elements[i], container);
  161. }
  162. }
  163. if (paramPath.isObjectPattern() && hasRestElement(paramPath)) {
  164. const uid = parentPath.scope.generateUidIdentifier("ref");
  165. const declar = _core.types.variableDeclaration("let", [_core.types.variableDeclarator(paramPath.node, uid)]);
  166. if (container) {
  167. container.push(declar);
  168. } else {
  169. parentPath.ensureBlock();
  170. parentPath.get("body").unshiftContainer("body", declar);
  171. }
  172. paramPath.replaceWith(_core.types.cloneNode(uid));
  173. }
  174. }
  175. return {
  176. name: "proposal-object-rest-spread",
  177. inherits: _pluginSyntaxObjectRestSpread.default,
  178. visitor: {
  179. Function(path) {
  180. const params = path.get("params");
  181. const paramsWithRestElement = new Set();
  182. const idsInRestParams = new Set();
  183. for (let i = 0; i < params.length; ++i) {
  184. const param = params[i];
  185. if (hasRestElement(param)) {
  186. paramsWithRestElement.add(i);
  187. for (const name of Object.keys(param.getBindingIdentifiers())) {
  188. idsInRestParams.add(name);
  189. }
  190. }
  191. }
  192. let idInRest = false;
  193. const IdentifierHandler = function (path, functionScope) {
  194. const name = path.node.name;
  195. if (path.scope.getBinding(name) === functionScope.getBinding(name) && idsInRestParams.has(name)) {
  196. idInRest = true;
  197. path.stop();
  198. }
  199. };
  200. let i;
  201. for (i = 0; i < params.length && !idInRest; ++i) {
  202. const param = params[i];
  203. if (!paramsWithRestElement.has(i)) {
  204. if (param.isReferencedIdentifier() || param.isBindingIdentifier()) {
  205. IdentifierHandler(path, path.scope);
  206. } else {
  207. param.traverse({
  208. "Scope|TypeAnnotation|TSTypeAnnotation": path => path.skip(),
  209. "ReferencedIdentifier|BindingIdentifier": IdentifierHandler
  210. }, path.scope);
  211. }
  212. }
  213. }
  214. if (!idInRest) {
  215. for (let i = 0; i < params.length; ++i) {
  216. const param = params[i];
  217. if (paramsWithRestElement.has(i)) {
  218. replaceRestElement(param.parentPath, param);
  219. }
  220. }
  221. } else {
  222. const shouldTransformParam = idx => idx >= i - 1 || paramsWithRestElement.has(idx);
  223. (0, _pluginTransformParameters.convertFunctionParams)(path, ignoreFunctionLength, shouldTransformParam, replaceRestElement);
  224. }
  225. },
  226. VariableDeclarator(path, file) {
  227. if (!path.get("id").isObjectPattern()) {
  228. return;
  229. }
  230. let insertionPath = path;
  231. const originalPath = path;
  232. visitRestElements(path.get("id"), path => {
  233. if (!path.parentPath.isObjectPattern()) {
  234. return;
  235. }
  236. if (originalPath.node.id.properties.length > 1 && !_core.types.isIdentifier(originalPath.node.init)) {
  237. const initRef = path.scope.generateUidIdentifierBasedOnNode(originalPath.node.init, "ref");
  238. originalPath.insertBefore(_core.types.variableDeclarator(initRef, originalPath.node.init));
  239. originalPath.replaceWith(_core.types.variableDeclarator(originalPath.node.id, _core.types.cloneNode(initRef)));
  240. return;
  241. }
  242. let ref = originalPath.node.init;
  243. const refPropertyPath = [];
  244. let kind;
  245. path.findParent(path => {
  246. if (path.isObjectProperty()) {
  247. refPropertyPath.unshift(path);
  248. } else if (path.isVariableDeclarator()) {
  249. kind = path.parentPath.node.kind;
  250. return true;
  251. }
  252. });
  253. const impureObjRefComputedDeclarators = replaceImpureComputedKeys(refPropertyPath, path.scope);
  254. refPropertyPath.forEach(prop => {
  255. const {
  256. node
  257. } = prop;
  258. ref = _core.types.memberExpression(ref, _core.types.cloneNode(node.key), node.computed || _core.types.isLiteral(node.key));
  259. });
  260. const objectPatternPath = path.findParent(path => path.isObjectPattern());
  261. const [impureComputedPropertyDeclarators, argument, callExpression] = createObjectRest(objectPatternPath, file, ref);
  262. if (pureGetters) {
  263. removeUnusedExcludedKeys(objectPatternPath);
  264. }
  265. _core.types.assertIdentifier(argument);
  266. insertionPath.insertBefore(impureComputedPropertyDeclarators);
  267. insertionPath.insertBefore(impureObjRefComputedDeclarators);
  268. insertionPath.insertAfter(_core.types.variableDeclarator(argument, callExpression));
  269. insertionPath = insertionPath.getSibling(insertionPath.key + 1);
  270. path.scope.registerBinding(kind, insertionPath);
  271. if (objectPatternPath.node.properties.length === 0) {
  272. objectPatternPath.findParent(path => path.isObjectProperty() || path.isVariableDeclarator()).remove();
  273. }
  274. });
  275. },
  276. ExportNamedDeclaration(path) {
  277. const declaration = path.get("declaration");
  278. if (!declaration.isVariableDeclaration()) return;
  279. const hasRest = declaration.get("declarations").some(path => hasObjectPatternRestElement(path.get("id")));
  280. if (!hasRest) return;
  281. const specifiers = [];
  282. for (const name of Object.keys(path.getOuterBindingIdentifiers(path))) {
  283. specifiers.push(_core.types.exportSpecifier(_core.types.identifier(name), _core.types.identifier(name)));
  284. }
  285. path.replaceWith(declaration.node);
  286. path.insertAfter(_core.types.exportNamedDeclaration(null, specifiers));
  287. },
  288. CatchClause(path) {
  289. const paramPath = path.get("param");
  290. replaceRestElement(paramPath.parentPath, paramPath);
  291. },
  292. AssignmentExpression(path, file) {
  293. const leftPath = path.get("left");
  294. if (leftPath.isObjectPattern() && hasRestElement(leftPath)) {
  295. const nodes = [];
  296. const refName = path.scope.generateUidBasedOnNode(path.node.right, "ref");
  297. nodes.push(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(_core.types.identifier(refName), path.node.right)]));
  298. const [impureComputedPropertyDeclarators, argument, callExpression] = createObjectRest(leftPath, file, _core.types.identifier(refName));
  299. if (impureComputedPropertyDeclarators.length > 0) {
  300. nodes.push(_core.types.variableDeclaration("var", impureComputedPropertyDeclarators));
  301. }
  302. const nodeWithoutSpread = _core.types.cloneNode(path.node);
  303. nodeWithoutSpread.right = _core.types.identifier(refName);
  304. nodes.push(_core.types.expressionStatement(nodeWithoutSpread));
  305. nodes.push(_core.types.toStatement(_core.types.assignmentExpression("=", argument, callExpression)));
  306. nodes.push(_core.types.expressionStatement(_core.types.identifier(refName)));
  307. path.replaceWithMultiple(nodes);
  308. }
  309. },
  310. ForXStatement(path) {
  311. const {
  312. node,
  313. scope
  314. } = path;
  315. const leftPath = path.get("left");
  316. const left = node.left;
  317. if (!hasObjectPatternRestElement(leftPath)) {
  318. return;
  319. }
  320. if (!_core.types.isVariableDeclaration(left)) {
  321. const temp = scope.generateUidIdentifier("ref");
  322. node.left = _core.types.variableDeclaration("var", [_core.types.variableDeclarator(temp)]);
  323. path.ensureBlock();
  324. if (node.body.body.length === 0 && path.isCompletionRecord()) {
  325. node.body.body.unshift(_core.types.expressionStatement(scope.buildUndefinedNode()));
  326. }
  327. node.body.body.unshift(_core.types.expressionStatement(_core.types.assignmentExpression("=", left, _core.types.cloneNode(temp))));
  328. } else {
  329. const pattern = left.declarations[0].id;
  330. const key = scope.generateUidIdentifier("ref");
  331. node.left = _core.types.variableDeclaration(left.kind, [_core.types.variableDeclarator(key, null)]);
  332. path.ensureBlock();
  333. node.body.body.unshift(_core.types.variableDeclaration(node.left.kind, [_core.types.variableDeclarator(pattern, _core.types.cloneNode(key))]));
  334. }
  335. },
  336. ArrayPattern(path) {
  337. const objectPatterns = [];
  338. visitRestElements(path, path => {
  339. if (!path.parentPath.isObjectPattern()) {
  340. return;
  341. }
  342. const objectPattern = path.parentPath;
  343. const uid = path.scope.generateUidIdentifier("ref");
  344. objectPatterns.push(_core.types.variableDeclarator(objectPattern.node, uid));
  345. objectPattern.replaceWith(_core.types.cloneNode(uid));
  346. path.skip();
  347. });
  348. if (objectPatterns.length > 0) {
  349. const statementPath = path.getStatementParent();
  350. statementPath.insertAfter(_core.types.variableDeclaration(statementPath.node.kind || "var", objectPatterns));
  351. }
  352. },
  353. ObjectExpression(path, file) {
  354. if (!hasSpread(path.node)) return;
  355. let helper;
  356. if (setSpreadProperties) {
  357. helper = getExtendsHelper(file);
  358. } else {
  359. try {
  360. helper = file.addHelper("objectSpread2");
  361. } catch (_unused) {
  362. this.file.declarations["objectSpread2"] = null;
  363. helper = file.addHelper("objectSpread");
  364. }
  365. }
  366. let exp = null;
  367. let props = [];
  368. function make() {
  369. const hadProps = props.length > 0;
  370. const obj = _core.types.objectExpression(props);
  371. props = [];
  372. if (!exp) {
  373. exp = _core.types.callExpression(helper, [obj]);
  374. return;
  375. }
  376. if (pureGetters) {
  377. if (hadProps) {
  378. exp.arguments.push(obj);
  379. }
  380. return;
  381. }
  382. exp = _core.types.callExpression(_core.types.cloneNode(helper), [exp, ...(hadProps ? [_core.types.objectExpression([]), obj] : [])]);
  383. }
  384. for (const prop of path.node.properties) {
  385. if (_core.types.isSpreadElement(prop)) {
  386. make();
  387. exp.arguments.push(prop.argument);
  388. } else {
  389. props.push(prop);
  390. }
  391. }
  392. if (props.length) make();
  393. path.replaceWith(exp);
  394. }
  395. }
  396. };
  397. });
  398. exports.default = _default;