index.js 8.7 KB

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