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.

195 lines
6.4 KiB

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