CommonJsExportRequireDependency.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const Dependency = require("../Dependency");
  7. const { UsageState } = require("../ExportsInfo");
  8. const Template = require("../Template");
  9. const { equals } = require("../util/ArrayHelpers");
  10. const makeSerializable = require("../util/makeSerializable");
  11. const propertyAccess = require("../util/propertyAccess");
  12. const { handleDependencyBase } = require("./CommonJsDependencyHelpers");
  13. const ModuleDependency = require("./ModuleDependency");
  14. const processExportInfo = require("./processExportInfo");
  15. /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
  16. /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
  17. /** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */
  18. /** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */
  19. /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
  20. /** @typedef {import("../ExportsInfo")} ExportsInfo */
  21. /** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */
  22. /** @typedef {import("../Module")} Module */
  23. /** @typedef {import("../ModuleGraph")} ModuleGraph */
  24. /** @typedef {import("../javascript/JavascriptParser").Range} Range */
  25. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  26. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  27. /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
  28. /** @typedef {import("./CommonJsDependencyHelpers").CommonJSDependencyBaseKeywords} CommonJSDependencyBaseKeywords */
  29. const idsSymbol = Symbol("CommonJsExportRequireDependency.ids");
  30. const EMPTY_OBJECT = {};
  31. class CommonJsExportRequireDependency extends ModuleDependency {
  32. /**
  33. * @param {Range} range range
  34. * @param {Range | null} valueRange value range
  35. * @param {CommonJSDependencyBaseKeywords} base base
  36. * @param {string[]} names names
  37. * @param {string} request request
  38. * @param {string[]} ids ids
  39. * @param {boolean} resultUsed true, when the result is used
  40. */
  41. constructor(range, valueRange, base, names, request, ids, resultUsed) {
  42. super(request);
  43. this.range = range;
  44. this.valueRange = valueRange;
  45. this.base = base;
  46. this.names = names;
  47. this.ids = ids;
  48. this.resultUsed = resultUsed;
  49. this.asiSafe = undefined;
  50. }
  51. get type() {
  52. return "cjs export require";
  53. }
  54. /**
  55. * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module
  56. */
  57. couldAffectReferencingModule() {
  58. return Dependency.TRANSITIVE;
  59. }
  60. /**
  61. * @param {ModuleGraph} moduleGraph the module graph
  62. * @returns {string[]} the imported id
  63. */
  64. getIds(moduleGraph) {
  65. return moduleGraph.getMeta(this)[idsSymbol] || this.ids;
  66. }
  67. /**
  68. * @param {ModuleGraph} moduleGraph the module graph
  69. * @param {string[]} ids the imported ids
  70. * @returns {void}
  71. */
  72. setIds(moduleGraph, ids) {
  73. moduleGraph.getMeta(this)[idsSymbol] = ids;
  74. }
  75. /**
  76. * Returns list of exports referenced by this dependency
  77. * @param {ModuleGraph} moduleGraph module graph
  78. * @param {RuntimeSpec} runtime the runtime for which the module is analysed
  79. * @returns {(string[] | ReferencedExport)[]} referenced exports
  80. */
  81. getReferencedExports(moduleGraph, runtime) {
  82. const ids = this.getIds(moduleGraph);
  83. const getFullResult = () => {
  84. if (ids.length === 0) {
  85. return Dependency.EXPORTS_OBJECT_REFERENCED;
  86. }
  87. return [
  88. {
  89. name: ids,
  90. canMangle: false
  91. }
  92. ];
  93. };
  94. if (this.resultUsed) return getFullResult();
  95. /** @type {ExportsInfo | undefined} */
  96. let exportsInfo = moduleGraph.getExportsInfo(
  97. /** @type {Module} */ (moduleGraph.getParentModule(this))
  98. );
  99. for (const name of this.names) {
  100. const exportInfo = /** @type {ExportInfo} */ (
  101. exportsInfo.getReadOnlyExportInfo(name)
  102. );
  103. const used = exportInfo.getUsed(runtime);
  104. if (used === UsageState.Unused) return Dependency.NO_EXPORTS_REFERENCED;
  105. if (used !== UsageState.OnlyPropertiesUsed) return getFullResult();
  106. exportsInfo = exportInfo.exportsInfo;
  107. if (!exportsInfo) return getFullResult();
  108. }
  109. if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) {
  110. return getFullResult();
  111. }
  112. /** @type {string[][]} */
  113. const referencedExports = [];
  114. for (const exportInfo of exportsInfo.orderedExports) {
  115. processExportInfo(
  116. runtime,
  117. referencedExports,
  118. ids.concat(exportInfo.name),
  119. exportInfo,
  120. false
  121. );
  122. }
  123. return referencedExports.map(name => ({
  124. name,
  125. canMangle: false
  126. }));
  127. }
  128. /**
  129. * Returns the exported names
  130. * @param {ModuleGraph} moduleGraph module graph
  131. * @returns {ExportsSpec | undefined} export names
  132. */
  133. getExports(moduleGraph) {
  134. if (this.names.length === 1) {
  135. const ids = this.getIds(moduleGraph);
  136. const name = this.names[0];
  137. const from = moduleGraph.getConnection(this);
  138. if (!from) return;
  139. return {
  140. exports: [
  141. {
  142. name,
  143. from,
  144. export: ids.length === 0 ? null : ids,
  145. // we can't mangle names that are in an empty object
  146. // because one could access the prototype property
  147. // when export isn't set yet
  148. canMangle: !(name in EMPTY_OBJECT) && false
  149. }
  150. ],
  151. dependencies: [from.module]
  152. };
  153. } else if (this.names.length > 0) {
  154. const name = this.names[0];
  155. return {
  156. exports: [
  157. {
  158. name,
  159. // we can't mangle names that are in an empty object
  160. // because one could access the prototype property
  161. // when export isn't set yet
  162. canMangle: !(name in EMPTY_OBJECT) && false
  163. }
  164. ],
  165. dependencies: undefined
  166. };
  167. }
  168. const from = moduleGraph.getConnection(this);
  169. if (!from) return;
  170. const reexportInfo = this.getStarReexports(
  171. moduleGraph,
  172. undefined,
  173. from.module
  174. );
  175. const ids = this.getIds(moduleGraph);
  176. if (reexportInfo) {
  177. return {
  178. exports: Array.from(
  179. /** @type {Set<string>} */
  180. (reexportInfo.exports),
  181. name => ({
  182. name,
  183. from,
  184. export: ids.concat(name),
  185. canMangle: !(name in EMPTY_OBJECT) && false
  186. })
  187. ),
  188. // TODO handle deep reexports
  189. dependencies: [from.module]
  190. };
  191. }
  192. return {
  193. exports: true,
  194. from: ids.length === 0 ? from : undefined,
  195. canMangle: false,
  196. dependencies: [from.module]
  197. };
  198. }
  199. /**
  200. * @param {ModuleGraph} moduleGraph the module graph
  201. * @param {RuntimeSpec} runtime the runtime
  202. * @param {Module} importedModule the imported module (optional)
  203. * @returns {{exports?: Set<string>, checked?: Set<string>} | undefined} information
  204. */
  205. getStarReexports(
  206. moduleGraph,
  207. runtime,
  208. importedModule = /** @type {Module} */ (moduleGraph.getModule(this))
  209. ) {
  210. /** @type {ExportsInfo | undefined} */
  211. let importedExportsInfo = moduleGraph.getExportsInfo(importedModule);
  212. const ids = this.getIds(moduleGraph);
  213. if (ids.length > 0)
  214. importedExportsInfo = importedExportsInfo.getNestedExportsInfo(ids);
  215. /** @type {ExportsInfo | undefined} */
  216. let exportsInfo = moduleGraph.getExportsInfo(
  217. /** @type {Module} */ (moduleGraph.getParentModule(this))
  218. );
  219. if (this.names.length > 0)
  220. exportsInfo = exportsInfo.getNestedExportsInfo(this.names);
  221. const noExtraExports =
  222. importedExportsInfo &&
  223. importedExportsInfo.otherExportsInfo.provided === false;
  224. const noExtraImports =
  225. exportsInfo &&
  226. exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused;
  227. if (!noExtraExports && !noExtraImports) {
  228. return;
  229. }
  230. const isNamespaceImport =
  231. importedModule.getExportsType(moduleGraph, false) === "namespace";
  232. /** @type {Set<string>} */
  233. const exports = new Set();
  234. /** @type {Set<string>} */
  235. const checked = new Set();
  236. if (noExtraImports) {
  237. for (const exportInfo of /** @type {ExportsInfo} */ (exportsInfo)
  238. .orderedExports) {
  239. const name = exportInfo.name;
  240. if (exportInfo.getUsed(runtime) === UsageState.Unused) continue;
  241. if (name === "__esModule" && isNamespaceImport) {
  242. exports.add(name);
  243. } else if (importedExportsInfo) {
  244. const importedExportInfo =
  245. importedExportsInfo.getReadOnlyExportInfo(name);
  246. if (importedExportInfo.provided === false) continue;
  247. exports.add(name);
  248. if (importedExportInfo.provided === true) continue;
  249. checked.add(name);
  250. } else {
  251. exports.add(name);
  252. checked.add(name);
  253. }
  254. }
  255. } else if (noExtraExports) {
  256. for (const importedExportInfo of /** @type {ExportsInfo} */ (
  257. importedExportsInfo
  258. ).orderedExports) {
  259. const name = importedExportInfo.name;
  260. if (importedExportInfo.provided === false) continue;
  261. if (exportsInfo) {
  262. const exportInfo = exportsInfo.getReadOnlyExportInfo(name);
  263. if (exportInfo.getUsed(runtime) === UsageState.Unused) continue;
  264. }
  265. exports.add(name);
  266. if (importedExportInfo.provided === true) continue;
  267. checked.add(name);
  268. }
  269. if (isNamespaceImport) {
  270. exports.add("__esModule");
  271. checked.delete("__esModule");
  272. }
  273. }
  274. return { exports, checked };
  275. }
  276. /**
  277. * @param {ObjectSerializerContext} context context
  278. */
  279. serialize(context) {
  280. const { write } = context;
  281. write(this.asiSafe);
  282. write(this.range);
  283. write(this.valueRange);
  284. write(this.base);
  285. write(this.names);
  286. write(this.ids);
  287. write(this.resultUsed);
  288. super.serialize(context);
  289. }
  290. /**
  291. * @param {ObjectDeserializerContext} context context
  292. */
  293. deserialize(context) {
  294. const { read } = context;
  295. this.asiSafe = read();
  296. this.range = read();
  297. this.valueRange = read();
  298. this.base = read();
  299. this.names = read();
  300. this.ids = read();
  301. this.resultUsed = read();
  302. super.deserialize(context);
  303. }
  304. }
  305. makeSerializable(
  306. CommonJsExportRequireDependency,
  307. "webpack/lib/dependencies/CommonJsExportRequireDependency"
  308. );
  309. CommonJsExportRequireDependency.Template = class CommonJsExportRequireDependencyTemplate extends (
  310. ModuleDependency.Template
  311. ) {
  312. /**
  313. * @param {Dependency} dependency the dependency for which the template should be applied
  314. * @param {ReplaceSource} source the current replace source which can be modified
  315. * @param {DependencyTemplateContext} templateContext the context object
  316. * @returns {void}
  317. */
  318. apply(
  319. dependency,
  320. source,
  321. {
  322. module,
  323. runtimeTemplate,
  324. chunkGraph,
  325. moduleGraph,
  326. runtimeRequirements,
  327. runtime
  328. }
  329. ) {
  330. const dep = /** @type {CommonJsExportRequireDependency} */ (dependency);
  331. const used = moduleGraph
  332. .getExportsInfo(module)
  333. .getUsedName(dep.names, runtime);
  334. const [type, base] = handleDependencyBase(
  335. dep.base,
  336. module,
  337. runtimeRequirements
  338. );
  339. const importedModule = moduleGraph.getModule(dep);
  340. let requireExpr = runtimeTemplate.moduleExports({
  341. module: importedModule,
  342. chunkGraph,
  343. request: dep.request,
  344. weak: dep.weak,
  345. runtimeRequirements
  346. });
  347. if (importedModule) {
  348. const ids = dep.getIds(moduleGraph);
  349. const usedImported = moduleGraph
  350. .getExportsInfo(importedModule)
  351. .getUsedName(ids, runtime);
  352. if (usedImported) {
  353. const comment = equals(usedImported, ids)
  354. ? ""
  355. : `${Template.toNormalComment(propertyAccess(ids))} `;
  356. requireExpr += `${comment}${propertyAccess(usedImported)}`;
  357. }
  358. }
  359. switch (type) {
  360. case "expression":
  361. source.replace(
  362. dep.range[0],
  363. dep.range[1] - 1,
  364. used
  365. ? `${base}${propertyAccess(used)} = ${requireExpr}`
  366. : `/* unused reexport */ ${requireExpr}`
  367. );
  368. return;
  369. case "Object.defineProperty":
  370. throw new Error("TODO");
  371. default:
  372. throw new Error("Unexpected type");
  373. }
  374. }
  375. };
  376. module.exports = CommonJsExportRequireDependency;