rewrite-live-references.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = rewriteLiveReferences;
  6. var _assert = require("assert");
  7. var _core = require("@babel/core");
  8. var _helperSimpleAccess = require("@babel/helper-simple-access");
  9. function isInType(path) {
  10. do {
  11. switch (path.parent.type) {
  12. case "TSTypeAnnotation":
  13. case "TSTypeAliasDeclaration":
  14. case "TSTypeReference":
  15. case "TypeAnnotation":
  16. case "TypeAlias":
  17. return true;
  18. case "ExportSpecifier":
  19. return path.parentPath.parent.exportKind === "type";
  20. default:
  21. if (path.parentPath.isStatement() || path.parentPath.isExpression()) {
  22. return false;
  23. }
  24. }
  25. } while (path = path.parentPath);
  26. }
  27. function rewriteLiveReferences(programPath, metadata, wrapReference) {
  28. const imported = new Map();
  29. const exported = new Map();
  30. const requeueInParent = path => {
  31. programPath.requeue(path);
  32. };
  33. for (const [source, data] of metadata.source) {
  34. for (const [localName, importName] of data.imports) {
  35. imported.set(localName, [source, importName, null]);
  36. }
  37. for (const localName of data.importsNamespace) {
  38. imported.set(localName, [source, null, localName]);
  39. }
  40. }
  41. for (const [local, data] of metadata.local) {
  42. let exportMeta = exported.get(local);
  43. if (!exportMeta) {
  44. exportMeta = [];
  45. exported.set(local, exportMeta);
  46. }
  47. exportMeta.push(...data.names);
  48. }
  49. const rewriteBindingInitVisitorState = {
  50. metadata,
  51. requeueInParent,
  52. scope: programPath.scope,
  53. exported
  54. };
  55. programPath.traverse(rewriteBindingInitVisitor, rewriteBindingInitVisitorState);
  56. const bindingNames = new Set([...Array.from(imported.keys()), ...Array.from(exported.keys())]);
  57. {
  58. (0, _helperSimpleAccess.default)(programPath, bindingNames, false);
  59. }
  60. const rewriteReferencesVisitorState = {
  61. seen: new WeakSet(),
  62. metadata,
  63. requeueInParent,
  64. scope: programPath.scope,
  65. imported,
  66. exported,
  67. buildImportReference([source, importName, localName], identNode) {
  68. const meta = metadata.source.get(source);
  69. meta.referenced = true;
  70. if (localName) {
  71. if (meta.wrap) {
  72. var _wrapReference;
  73. identNode = (_wrapReference = wrapReference(identNode, meta.wrap)) != null ? _wrapReference : identNode;
  74. }
  75. return identNode;
  76. }
  77. let namespace = _core.types.identifier(meta.name);
  78. if (meta.wrap) {
  79. var _wrapReference2;
  80. namespace = (_wrapReference2 = wrapReference(namespace, meta.wrap)) != null ? _wrapReference2 : namespace;
  81. }
  82. if (importName === "default" && meta.interop === "node-default") {
  83. return namespace;
  84. }
  85. const computed = metadata.stringSpecifiers.has(importName);
  86. return _core.types.memberExpression(namespace, computed ? _core.types.stringLiteral(importName) : _core.types.identifier(importName), computed);
  87. }
  88. };
  89. programPath.traverse(rewriteReferencesVisitor, rewriteReferencesVisitorState);
  90. }
  91. const rewriteBindingInitVisitor = {
  92. Scope(path) {
  93. path.skip();
  94. },
  95. ClassDeclaration(path) {
  96. const {
  97. requeueInParent,
  98. exported,
  99. metadata
  100. } = this;
  101. const {
  102. id
  103. } = path.node;
  104. if (!id) throw new Error("Expected class to have a name");
  105. const localName = id.name;
  106. const exportNames = exported.get(localName) || [];
  107. if (exportNames.length > 0) {
  108. const statement = _core.types.expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, _core.types.identifier(localName), path.scope));
  109. statement._blockHoist = path.node._blockHoist;
  110. requeueInParent(path.insertAfter(statement)[0]);
  111. }
  112. },
  113. VariableDeclaration(path) {
  114. const {
  115. requeueInParent,
  116. exported,
  117. metadata
  118. } = this;
  119. const isVar = path.node.kind === "var";
  120. for (const decl of path.get("declarations")) {
  121. const {
  122. id
  123. } = decl.node;
  124. let {
  125. init
  126. } = decl.node;
  127. if (_core.types.isIdentifier(id) && exported.has(id.name) && !_core.types.isArrowFunctionExpression(init) && (!_core.types.isFunctionExpression(init) || init.id) && (!_core.types.isClassExpression(init) || init.id)) {
  128. if (!init) {
  129. if (isVar) {
  130. continue;
  131. } else {
  132. init = path.scope.buildUndefinedNode();
  133. }
  134. }
  135. decl.node.init = buildBindingExportAssignmentExpression(metadata, exported.get(id.name), init, path.scope);
  136. requeueInParent(decl.get("init"));
  137. } else {
  138. for (const localName of Object.keys(decl.getOuterBindingIdentifiers())) {
  139. if (exported.has(localName)) {
  140. const statement = _core.types.expressionStatement(buildBindingExportAssignmentExpression(metadata, exported.get(localName), _core.types.identifier(localName), path.scope));
  141. statement._blockHoist = path.node._blockHoist;
  142. requeueInParent(path.insertAfter(statement)[0]);
  143. }
  144. }
  145. }
  146. }
  147. }
  148. };
  149. const buildBindingExportAssignmentExpression = (metadata, exportNames, localExpr, scope) => {
  150. const exportsObjectName = metadata.exportName;
  151. for (let currentScope = scope; currentScope != null; currentScope = currentScope.parent) {
  152. if (currentScope.hasOwnBinding(exportsObjectName)) {
  153. currentScope.rename(exportsObjectName);
  154. }
  155. }
  156. return (exportNames || []).reduce((expr, exportName) => {
  157. const {
  158. stringSpecifiers
  159. } = metadata;
  160. const computed = stringSpecifiers.has(exportName);
  161. return _core.types.assignmentExpression("=", _core.types.memberExpression(_core.types.identifier(exportsObjectName), computed ? _core.types.stringLiteral(exportName) : _core.types.identifier(exportName), computed), expr);
  162. }, localExpr);
  163. };
  164. const buildImportThrow = localName => {
  165. return _core.template.expression.ast`
  166. (function() {
  167. throw new Error('"' + '${localName}' + '" is read-only.');
  168. })()
  169. `;
  170. };
  171. const rewriteReferencesVisitor = {
  172. ReferencedIdentifier(path) {
  173. const {
  174. seen,
  175. buildImportReference,
  176. scope,
  177. imported,
  178. requeueInParent
  179. } = this;
  180. if (seen.has(path.node)) return;
  181. seen.add(path.node);
  182. const localName = path.node.name;
  183. const importData = imported.get(localName);
  184. if (importData) {
  185. if (isInType(path)) {
  186. throw path.buildCodeFrameError(`Cannot transform the imported binding "${localName}" since it's also used in a type annotation. ` + `Please strip type annotations using @babel/preset-typescript or @babel/preset-flow.`);
  187. }
  188. const localBinding = path.scope.getBinding(localName);
  189. const rootBinding = scope.getBinding(localName);
  190. if (rootBinding !== localBinding) return;
  191. const ref = buildImportReference(importData, path.node);
  192. ref.loc = path.node.loc;
  193. if ((path.parentPath.isCallExpression({
  194. callee: path.node
  195. }) || path.parentPath.isOptionalCallExpression({
  196. callee: path.node
  197. }) || path.parentPath.isTaggedTemplateExpression({
  198. tag: path.node
  199. })) && _core.types.isMemberExpression(ref)) {
  200. path.replaceWith(_core.types.sequenceExpression([_core.types.numericLiteral(0), ref]));
  201. } else if (path.isJSXIdentifier() && _core.types.isMemberExpression(ref)) {
  202. const {
  203. object,
  204. property
  205. } = ref;
  206. path.replaceWith(_core.types.jsxMemberExpression(_core.types.jsxIdentifier(object.name), _core.types.jsxIdentifier(property.name)));
  207. } else {
  208. path.replaceWith(ref);
  209. }
  210. requeueInParent(path);
  211. path.skip();
  212. }
  213. },
  214. UpdateExpression(path) {
  215. const {
  216. scope,
  217. seen,
  218. imported,
  219. exported,
  220. requeueInParent,
  221. buildImportReference
  222. } = this;
  223. if (seen.has(path.node)) return;
  224. seen.add(path.node);
  225. const arg = path.get("argument");
  226. if (arg.isMemberExpression()) return;
  227. const update = path.node;
  228. if (arg.isIdentifier()) {
  229. const localName = arg.node.name;
  230. if (scope.getBinding(localName) !== path.scope.getBinding(localName)) {
  231. return;
  232. }
  233. const exportedNames = exported.get(localName);
  234. const importData = imported.get(localName);
  235. if ((exportedNames == null ? void 0 : exportedNames.length) > 0 || importData) {
  236. if (importData) {
  237. path.replaceWith(_core.types.assignmentExpression(update.operator[0] + "=", buildImportReference(importData, arg.node), buildImportThrow(localName)));
  238. } else if (update.prefix) {
  239. path.replaceWith(buildBindingExportAssignmentExpression(this.metadata, exportedNames, _core.types.cloneNode(update), path.scope));
  240. } else {
  241. const ref = scope.generateDeclaredUidIdentifier(localName);
  242. path.replaceWith(_core.types.sequenceExpression([_core.types.assignmentExpression("=", _core.types.cloneNode(ref), _core.types.cloneNode(update)), buildBindingExportAssignmentExpression(this.metadata, exportedNames, _core.types.identifier(localName), path.scope), _core.types.cloneNode(ref)]));
  243. }
  244. }
  245. }
  246. requeueInParent(path);
  247. path.skip();
  248. },
  249. AssignmentExpression: {
  250. exit(path) {
  251. const {
  252. scope,
  253. seen,
  254. imported,
  255. exported,
  256. requeueInParent,
  257. buildImportReference
  258. } = this;
  259. if (seen.has(path.node)) return;
  260. seen.add(path.node);
  261. const left = path.get("left");
  262. if (left.isMemberExpression()) return;
  263. if (left.isIdentifier()) {
  264. const localName = left.node.name;
  265. if (scope.getBinding(localName) !== path.scope.getBinding(localName)) {
  266. return;
  267. }
  268. const exportedNames = exported.get(localName);
  269. const importData = imported.get(localName);
  270. if ((exportedNames == null ? void 0 : exportedNames.length) > 0 || importData) {
  271. _assert(path.node.operator === "=", "Path was not simplified");
  272. const assignment = path.node;
  273. if (importData) {
  274. assignment.left = buildImportReference(importData, left.node);
  275. assignment.right = _core.types.sequenceExpression([assignment.right, buildImportThrow(localName)]);
  276. }
  277. path.replaceWith(buildBindingExportAssignmentExpression(this.metadata, exportedNames, assignment, path.scope));
  278. requeueInParent(path);
  279. }
  280. } else {
  281. const ids = left.getOuterBindingIdentifiers();
  282. const programScopeIds = Object.keys(ids).filter(localName => scope.getBinding(localName) === path.scope.getBinding(localName));
  283. const id = programScopeIds.find(localName => imported.has(localName));
  284. if (id) {
  285. path.node.right = _core.types.sequenceExpression([path.node.right, buildImportThrow(id)]);
  286. }
  287. const items = [];
  288. programScopeIds.forEach(localName => {
  289. const exportedNames = exported.get(localName) || [];
  290. if (exportedNames.length > 0) {
  291. items.push(buildBindingExportAssignmentExpression(this.metadata, exportedNames, _core.types.identifier(localName), path.scope));
  292. }
  293. });
  294. if (items.length > 0) {
  295. let node = _core.types.sequenceExpression(items);
  296. if (path.parentPath.isExpressionStatement()) {
  297. node = _core.types.expressionStatement(node);
  298. node._blockHoist = path.parentPath.node._blockHoist;
  299. }
  300. const statement = path.insertAfter(node)[0];
  301. requeueInParent(statement);
  302. }
  303. }
  304. }
  305. },
  306. "ForOfStatement|ForInStatement"(path) {
  307. const {
  308. scope,
  309. node
  310. } = path;
  311. const {
  312. left
  313. } = node;
  314. const {
  315. exported,
  316. imported,
  317. scope: programScope
  318. } = this;
  319. if (!_core.types.isVariableDeclaration(left)) {
  320. let didTransformExport = false,
  321. importConstViolationName;
  322. const loopBodyScope = path.get("body").scope;
  323. for (const name of Object.keys(_core.types.getOuterBindingIdentifiers(left))) {
  324. if (programScope.getBinding(name) === scope.getBinding(name)) {
  325. if (exported.has(name)) {
  326. didTransformExport = true;
  327. if (loopBodyScope.hasOwnBinding(name)) {
  328. loopBodyScope.rename(name);
  329. }
  330. }
  331. if (imported.has(name) && !importConstViolationName) {
  332. importConstViolationName = name;
  333. }
  334. }
  335. }
  336. if (!didTransformExport && !importConstViolationName) {
  337. return;
  338. }
  339. path.ensureBlock();
  340. const bodyPath = path.get("body");
  341. const newLoopId = scope.generateUidIdentifierBasedOnNode(left);
  342. path.get("left").replaceWith(_core.types.variableDeclaration("let", [_core.types.variableDeclarator(_core.types.cloneNode(newLoopId))]));
  343. scope.registerDeclaration(path.get("left"));
  344. if (didTransformExport) {
  345. bodyPath.unshiftContainer("body", _core.types.expressionStatement(_core.types.assignmentExpression("=", left, newLoopId)));
  346. }
  347. if (importConstViolationName) {
  348. bodyPath.unshiftContainer("body", _core.types.expressionStatement(buildImportThrow(importConstViolationName)));
  349. }
  350. }
  351. }
  352. };
  353. //# sourceMappingURL=rewrite-live-references.js.map