index.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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 _helperModuleTransforms = require("@babel/helper-module-transforms");
  8. var _helperSimpleAccess = require("@babel/helper-simple-access");
  9. var _core = require("@babel/core");
  10. var _utils = require("babel-plugin-dynamic-import-node/utils");
  11. var _default = (0, _helperPluginUtils.declare)((api, options) => {
  12. var _api$assumption, _api$assumption2, _api$assumption3;
  13. api.assertVersion(7);
  14. const transformImportCall = (0, _utils.createDynamicImportTransform)(api);
  15. const {
  16. strictNamespace = false,
  17. mjsStrictNamespace = strictNamespace,
  18. allowTopLevelThis,
  19. strict,
  20. strictMode,
  21. noInterop,
  22. importInterop,
  23. lazy = false,
  24. allowCommonJSExports = true
  25. } = options;
  26. const constantReexports = (_api$assumption = api.assumption("constantReexports")) != null ? _api$assumption : options.loose;
  27. const enumerableModuleMeta = (_api$assumption2 = api.assumption("enumerableModuleMeta")) != null ? _api$assumption2 : options.loose;
  28. const noIncompleteNsImportDetection = (_api$assumption3 = api.assumption("noIncompleteNsImportDetection")) != null ? _api$assumption3 : false;
  29. if (typeof lazy !== "boolean" && typeof lazy !== "function" && (!Array.isArray(lazy) || !lazy.every(item => typeof item === "string"))) {
  30. throw new Error(`.lazy must be a boolean, array of strings, or a function`);
  31. }
  32. if (typeof strictNamespace !== "boolean") {
  33. throw new Error(`.strictNamespace must be a boolean, or undefined`);
  34. }
  35. if (typeof mjsStrictNamespace !== "boolean") {
  36. throw new Error(`.mjsStrictNamespace must be a boolean, or undefined`);
  37. }
  38. const getAssertion = localName => _core.template.expression.ast`
  39. (function(){
  40. throw new Error(
  41. "The CommonJS '" + "${localName}" + "' variable is not available in ES6 modules." +
  42. "Consider setting setting sourceType:script or sourceType:unambiguous in your " +
  43. "Babel config for this file.");
  44. })()
  45. `;
  46. const moduleExportsVisitor = {
  47. ReferencedIdentifier(path) {
  48. const localName = path.node.name;
  49. if (localName !== "module" && localName !== "exports") return;
  50. const localBinding = path.scope.getBinding(localName);
  51. const rootBinding = this.scope.getBinding(localName);
  52. if (rootBinding !== localBinding || path.parentPath.isObjectProperty({
  53. value: path.node
  54. }) && path.parentPath.parentPath.isObjectPattern() || path.parentPath.isAssignmentExpression({
  55. left: path.node
  56. }) || path.isAssignmentExpression({
  57. left: path.node
  58. })) {
  59. return;
  60. }
  61. path.replaceWith(getAssertion(localName));
  62. },
  63. UpdateExpression(path) {
  64. const arg = path.get("argument");
  65. const localName = arg.node.name;
  66. if (localName !== "module" && localName !== "exports") return;
  67. const localBinding = path.scope.getBinding(localName);
  68. const rootBinding = this.scope.getBinding(localName);
  69. if (rootBinding !== localBinding) return;
  70. path.replaceWith(_core.types.assignmentExpression(path.node.operator[0] + "=", arg.node, getAssertion(localName)));
  71. },
  72. AssignmentExpression(path) {
  73. const left = path.get("left");
  74. if (left.isIdentifier()) {
  75. const localName = path.node.name;
  76. if (localName !== "module" && localName !== "exports") return;
  77. const localBinding = path.scope.getBinding(localName);
  78. const rootBinding = this.scope.getBinding(localName);
  79. if (rootBinding !== localBinding) return;
  80. const right = path.get("right");
  81. right.replaceWith(_core.types.sequenceExpression([right.node, getAssertion(localName)]));
  82. } else if (left.isPattern()) {
  83. const ids = left.getOuterBindingIdentifiers();
  84. const localName = Object.keys(ids).filter(localName => {
  85. if (localName !== "module" && localName !== "exports") return false;
  86. return this.scope.getBinding(localName) === path.scope.getBinding(localName);
  87. })[0];
  88. if (localName) {
  89. const right = path.get("right");
  90. right.replaceWith(_core.types.sequenceExpression([right.node, getAssertion(localName)]));
  91. }
  92. }
  93. }
  94. };
  95. return {
  96. name: "transform-modules-commonjs",
  97. pre() {
  98. this.file.set("@babel/plugin-transform-modules-*", "commonjs");
  99. },
  100. visitor: {
  101. CallExpression(path) {
  102. if (!this.file.has("@babel/plugin-proposal-dynamic-import")) return;
  103. if (!path.get("callee").isImport()) return;
  104. let {
  105. scope
  106. } = path;
  107. do {
  108. scope.rename("require");
  109. } while (scope = scope.parent);
  110. transformImportCall(this, path.get("callee"));
  111. },
  112. Program: {
  113. exit(path, state) {
  114. if (!(0, _helperModuleTransforms.isModule)(path)) return;
  115. path.scope.rename("exports");
  116. path.scope.rename("module");
  117. path.scope.rename("require");
  118. path.scope.rename("__filename");
  119. path.scope.rename("__dirname");
  120. if (!allowCommonJSExports) {
  121. (0, _helperSimpleAccess.default)(path, new Set(["module", "exports"]), false);
  122. path.traverse(moduleExportsVisitor, {
  123. scope: path.scope
  124. });
  125. }
  126. let moduleName = (0, _helperModuleTransforms.getModuleName)(this.file.opts, options);
  127. if (moduleName) moduleName = _core.types.stringLiteral(moduleName);
  128. const {
  129. meta,
  130. headers
  131. } = (0, _helperModuleTransforms.rewriteModuleStatementsAndPrepareHeader)(path, {
  132. exportName: "exports",
  133. constantReexports,
  134. enumerableModuleMeta,
  135. strict,
  136. strictMode,
  137. allowTopLevelThis,
  138. noInterop,
  139. importInterop,
  140. lazy,
  141. esNamespaceOnly: typeof state.filename === "string" && /\.mjs$/.test(state.filename) ? mjsStrictNamespace : strictNamespace,
  142. noIncompleteNsImportDetection
  143. });
  144. for (const [source, metadata] of meta.source) {
  145. const loadExpr = _core.types.callExpression(_core.types.identifier("require"), [_core.types.stringLiteral(source)]);
  146. let header;
  147. if ((0, _helperModuleTransforms.isSideEffectImport)(metadata)) {
  148. if (metadata.lazy) throw new Error("Assertion failure");
  149. header = _core.types.expressionStatement(loadExpr);
  150. } else {
  151. const init = (0, _helperModuleTransforms.wrapInterop)(path, loadExpr, metadata.interop) || loadExpr;
  152. if (metadata.lazy) {
  153. header = _core.template.ast`
  154. function ${metadata.name}() {
  155. const data = ${init};
  156. ${metadata.name} = function(){ return data; };
  157. return data;
  158. }
  159. `;
  160. } else {
  161. header = _core.template.ast`
  162. var ${metadata.name} = ${init};
  163. `;
  164. }
  165. }
  166. header.loc = metadata.loc;
  167. headers.push(header);
  168. headers.push(...(0, _helperModuleTransforms.buildNamespaceInitStatements)(meta, metadata, constantReexports));
  169. }
  170. (0, _helperModuleTransforms.ensureStatementsHoisted)(headers);
  171. path.unshiftContainer("body", headers);
  172. path.get("body").forEach(path => {
  173. if (headers.indexOf(path.node) === -1) return;
  174. if (path.isVariableDeclaration()) {
  175. path.scope.registerDeclaration(path);
  176. }
  177. });
  178. }
  179. }
  180. }
  181. };
  182. });
  183. exports.default = _default;