You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

275 lines
8.3 KiB

4 years ago
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.get = get;
  6. exports.minVersion = minVersion;
  7. exports.getDependencies = getDependencies;
  8. exports.ensure = ensure;
  9. exports.default = exports.list = void 0;
  10. var _traverse = _interopRequireDefault(require("@babel/traverse"));
  11. var t = _interopRequireWildcard(require("@babel/types"));
  12. var _helpers = _interopRequireDefault(require("./helpers"));
  13. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  14. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  15. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  16. function makePath(path) {
  17. const parts = [];
  18. for (; path.parentPath; path = path.parentPath) {
  19. parts.push(path.key);
  20. if (path.inList) parts.push(path.listKey);
  21. }
  22. return parts.reverse().join(".");
  23. }
  24. function getHelperMetadata(file) {
  25. const globals = new Set();
  26. const localBindingNames = new Set();
  27. const dependencies = new Map();
  28. let exportName;
  29. let exportPath;
  30. const exportBindingAssignments = [];
  31. const importPaths = [];
  32. const importBindingsReferences = [];
  33. (0, _traverse.default)(file, {
  34. ImportDeclaration(child) {
  35. const name = child.node.source.value;
  36. if (!_helpers.default[name]) {
  37. throw child.buildCodeFrameError(`Unknown helper ${name}`);
  38. }
  39. if (child.get("specifiers").length !== 1 || !child.get("specifiers.0").isImportDefaultSpecifier()) {
  40. throw child.buildCodeFrameError("Helpers can only import a default value");
  41. }
  42. const bindingIdentifier = child.node.specifiers[0].local;
  43. dependencies.set(bindingIdentifier, name);
  44. importPaths.push(makePath(child));
  45. },
  46. ExportDefaultDeclaration(child) {
  47. const decl = child.get("declaration");
  48. if (decl.isFunctionDeclaration()) {
  49. if (!decl.node.id) {
  50. throw decl.buildCodeFrameError("Helpers should give names to their exported func declaration");
  51. }
  52. exportName = decl.node.id.name;
  53. }
  54. exportPath = makePath(child);
  55. },
  56. ExportAllDeclaration(child) {
  57. throw child.buildCodeFrameError("Helpers can only export default");
  58. },
  59. ExportNamedDeclaration(child) {
  60. throw child.buildCodeFrameError("Helpers can only export default");
  61. },
  62. Statement(child) {
  63. if (child.isModuleDeclaration()) return;
  64. child.skip();
  65. }
  66. });
  67. (0, _traverse.default)(file, {
  68. Program(path) {
  69. const bindings = path.scope.getAllBindings();
  70. Object.keys(bindings).forEach(name => {
  71. if (name === exportName) return;
  72. if (dependencies.has(bindings[name].identifier)) return;
  73. localBindingNames.add(name);
  74. });
  75. },
  76. ReferencedIdentifier(child) {
  77. const name = child.node.name;
  78. const binding = child.scope.getBinding(name, true);
  79. if (!binding) {
  80. globals.add(name);
  81. } else if (dependencies.has(binding.identifier)) {
  82. importBindingsReferences.push(makePath(child));
  83. }
  84. },
  85. AssignmentExpression(child) {
  86. const left = child.get("left");
  87. if (!(exportName in left.getBindingIdentifiers())) return;
  88. if (!left.isIdentifier()) {
  89. throw left.buildCodeFrameError("Only simple assignments to exports are allowed in helpers");
  90. }
  91. const binding = child.scope.getBinding(exportName);
  92. if (binding && binding.scope.path.isProgram()) {
  93. exportBindingAssignments.push(makePath(child));
  94. }
  95. }
  96. });
  97. if (!exportPath) throw new Error("Helpers must default-export something.");
  98. exportBindingAssignments.reverse();
  99. return {
  100. globals: Array.from(globals),
  101. localBindingNames: Array.from(localBindingNames),
  102. dependencies,
  103. exportBindingAssignments,
  104. exportPath,
  105. exportName,
  106. importBindingsReferences,
  107. importPaths
  108. };
  109. }
  110. function permuteHelperAST(file, metadata, id, localBindings, getDependency) {
  111. if (localBindings && !id) {
  112. throw new Error("Unexpected local bindings for module-based helpers.");
  113. }
  114. if (!id) return;
  115. const {
  116. localBindingNames,
  117. dependencies,
  118. exportBindingAssignments,
  119. exportPath,
  120. exportName,
  121. importBindingsReferences,
  122. importPaths
  123. } = metadata;
  124. const dependenciesRefs = {};
  125. dependencies.forEach((name, id) => {
  126. dependenciesRefs[id.name] = typeof getDependency === "function" && getDependency(name) || id;
  127. });
  128. const toRename = {};
  129. const bindings = new Set(localBindings || []);
  130. localBindingNames.forEach(name => {
  131. let newName = name;
  132. while (bindings.has(newName)) newName = "_" + newName;
  133. if (newName !== name) toRename[name] = newName;
  134. });
  135. if (id.type === "Identifier" && exportName !== id.name) {
  136. toRename[exportName] = id.name;
  137. }
  138. (0, _traverse.default)(file, {
  139. Program(path) {
  140. const exp = path.get(exportPath);
  141. const imps = importPaths.map(p => path.get(p));
  142. const impsBindingRefs = importBindingsReferences.map(p => path.get(p));
  143. const decl = exp.get("declaration");
  144. if (id.type === "Identifier") {
  145. if (decl.isFunctionDeclaration()) {
  146. exp.replaceWith(decl);
  147. } else {
  148. exp.replaceWith(t.variableDeclaration("var", [t.variableDeclarator(id, decl.node)]));
  149. }
  150. } else if (id.type === "MemberExpression") {
  151. if (decl.isFunctionDeclaration()) {
  152. exportBindingAssignments.forEach(assignPath => {
  153. const assign = path.get(assignPath);
  154. assign.replaceWith(t.assignmentExpression("=", id, assign.node));
  155. });
  156. exp.replaceWith(decl);
  157. path.pushContainer("body", t.expressionStatement(t.assignmentExpression("=", id, t.identifier(exportName))));
  158. } else {
  159. exp.replaceWith(t.expressionStatement(t.assignmentExpression("=", id, decl.node)));
  160. }
  161. } else {
  162. throw new Error("Unexpected helper format.");
  163. }
  164. Object.keys(toRename).forEach(name => {
  165. path.scope.rename(name, toRename[name]);
  166. });
  167. for (const path of imps) path.remove();
  168. for (const path of impsBindingRefs) {
  169. const node = t.cloneNode(dependenciesRefs[path.node.name]);
  170. path.replaceWith(node);
  171. }
  172. path.stop();
  173. }
  174. });
  175. }
  176. const helperData = Object.create(null);
  177. function loadHelper(name) {
  178. if (!helperData[name]) {
  179. const helper = _helpers.default[name];
  180. if (!helper) {
  181. throw Object.assign(new ReferenceError(`Unknown helper ${name}`), {
  182. code: "BABEL_HELPER_UNKNOWN",
  183. helper: name
  184. });
  185. }
  186. const fn = () => {
  187. return t.file(helper.ast());
  188. };
  189. const metadata = getHelperMetadata(fn());
  190. helperData[name] = {
  191. build(getDependency, id, localBindings) {
  192. const file = fn();
  193. permuteHelperAST(file, metadata, id, localBindings, getDependency);
  194. return {
  195. nodes: file.program.body,
  196. globals: metadata.globals
  197. };
  198. },
  199. minVersion() {
  200. return helper.minVersion;
  201. },
  202. dependencies: metadata.dependencies
  203. };
  204. }
  205. return helperData[name];
  206. }
  207. function get(name, getDependency, id, localBindings) {
  208. return loadHelper(name).build(getDependency, id, localBindings);
  209. }
  210. function minVersion(name) {
  211. return loadHelper(name).minVersion();
  212. }
  213. function getDependencies(name) {
  214. return Array.from(loadHelper(name).dependencies.values());
  215. }
  216. function ensure(name) {
  217. loadHelper(name);
  218. }
  219. const list = Object.keys(_helpers.default).map(name => name.replace(/^_/, "")).filter(name => name !== "__esModule");
  220. exports.list = list;
  221. var _default = get;
  222. exports.default = _default;