CommonJsExportRequireDependency.js 12 KB

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