HarmonyImportSpecifierDependency.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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 Template = require("../Template");
  8. const {
  9. getDependencyUsedByExportsCondition
  10. } = require("../optimize/InnerGraph");
  11. const { getTrimmedIdsAndRange } = require("../util/chainedImports");
  12. const makeSerializable = require("../util/makeSerializable");
  13. const propertyAccess = require("../util/propertyAccess");
  14. const HarmonyImportDependency = require("./HarmonyImportDependency");
  15. /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
  16. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  17. /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
  18. /** @typedef {import("../Dependency").GetConditionFn} GetConditionFn */
  19. /** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */
  20. /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
  21. /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
  22. /** @typedef {import("../Module")} Module */
  23. /** @typedef {import("../Module").BuildMeta} BuildMeta */
  24. /** @typedef {import("../ModuleGraph")} ModuleGraph */
  25. /** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */
  26. /** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */
  27. /** @typedef {import("../WebpackError")} WebpackError */
  28. /** @typedef {import("../javascript/JavascriptParser").DestructuringAssignmentProperty} DestructuringAssignmentProperty */
  29. /** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */
  30. /** @typedef {import("../javascript/JavascriptParser").Range} Range */
  31. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  32. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  33. /** @typedef {import("../util/Hash")} Hash */
  34. /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
  35. const idsSymbol = Symbol("HarmonyImportSpecifierDependency.ids");
  36. const { ExportPresenceModes } = HarmonyImportDependency;
  37. class HarmonyImportSpecifierDependency extends HarmonyImportDependency {
  38. /**
  39. * @param {string} request request
  40. * @param {number} sourceOrder source order
  41. * @param {string[]} ids ids
  42. * @param {string} name name
  43. * @param {Range} range range
  44. * @param {TODO} exportPresenceMode export presence mode
  45. * @param {ImportAttributes | undefined} attributes import attributes
  46. * @param {Range[] | undefined} idRanges ranges for members of ids; the two arrays are right-aligned
  47. */
  48. constructor(
  49. request,
  50. sourceOrder,
  51. ids,
  52. name,
  53. range,
  54. exportPresenceMode,
  55. attributes,
  56. idRanges // TODO webpack 6 make this non-optional. It must always be set to properly trim ids.
  57. ) {
  58. super(request, sourceOrder, attributes);
  59. this.ids = ids;
  60. this.name = name;
  61. this.range = range;
  62. this.idRanges = idRanges;
  63. this.exportPresenceMode = exportPresenceMode;
  64. this.namespaceObjectAsContext = false;
  65. this.call = undefined;
  66. this.directImport = undefined;
  67. this.shorthand = undefined;
  68. this.asiSafe = undefined;
  69. /** @type {Set<string> | boolean | undefined} */
  70. this.usedByExports = undefined;
  71. /** @type {Set<DestructuringAssignmentProperty> | undefined} */
  72. this.referencedPropertiesInDestructuring = undefined;
  73. }
  74. // TODO webpack 6 remove
  75. get id() {
  76. throw new Error("id was renamed to ids and type changed to string[]");
  77. }
  78. // TODO webpack 6 remove
  79. getId() {
  80. throw new Error("id was renamed to ids and type changed to string[]");
  81. }
  82. // TODO webpack 6 remove
  83. setId() {
  84. throw new Error("id was renamed to ids and type changed to string[]");
  85. }
  86. get type() {
  87. return "harmony import specifier";
  88. }
  89. /**
  90. * @param {ModuleGraph} moduleGraph the module graph
  91. * @returns {string[]} the imported ids
  92. */
  93. getIds(moduleGraph) {
  94. const meta = moduleGraph.getMetaIfExisting(this);
  95. if (meta === undefined) return this.ids;
  96. const ids = meta[/** @type {keyof object} */ (idsSymbol)];
  97. return ids !== undefined ? ids : this.ids;
  98. }
  99. /**
  100. * @param {ModuleGraph} moduleGraph the module graph
  101. * @param {string[]} ids the imported ids
  102. * @returns {void}
  103. */
  104. setIds(moduleGraph, ids) {
  105. /** @type {TODO} */
  106. (moduleGraph.getMeta(this))[idsSymbol] = ids;
  107. }
  108. /**
  109. * @param {ModuleGraph} moduleGraph module graph
  110. * @returns {null | false | GetConditionFn} function to determine if the connection is active
  111. */
  112. getCondition(moduleGraph) {
  113. return getDependencyUsedByExportsCondition(
  114. this,
  115. this.usedByExports,
  116. moduleGraph
  117. );
  118. }
  119. /**
  120. * @param {ModuleGraph} moduleGraph the module graph
  121. * @returns {ConnectionState} how this dependency connects the module to referencing modules
  122. */
  123. getModuleEvaluationSideEffectsState(moduleGraph) {
  124. return false;
  125. }
  126. /**
  127. * Returns list of exports referenced by this dependency
  128. * @param {ModuleGraph} moduleGraph module graph
  129. * @param {RuntimeSpec} runtime the runtime for which the module is analysed
  130. * @returns {(string[] | ReferencedExport)[]} referenced exports
  131. */
  132. getReferencedExports(moduleGraph, runtime) {
  133. let ids = this.getIds(moduleGraph);
  134. if (ids.length === 0) return this._getReferencedExportsInDestructuring();
  135. let namespaceObjectAsContext = this.namespaceObjectAsContext;
  136. if (ids[0] === "default") {
  137. const selfModule =
  138. /** @type {Module} */
  139. (moduleGraph.getParentModule(this));
  140. const importedModule =
  141. /** @type {Module} */
  142. (moduleGraph.getModule(this));
  143. switch (
  144. importedModule.getExportsType(
  145. moduleGraph,
  146. /** @type {BuildMeta} */
  147. (selfModule.buildMeta).strictHarmonyModule
  148. )
  149. ) {
  150. case "default-only":
  151. case "default-with-named":
  152. if (ids.length === 1)
  153. return this._getReferencedExportsInDestructuring();
  154. ids = ids.slice(1);
  155. namespaceObjectAsContext = true;
  156. break;
  157. case "dynamic":
  158. return Dependency.EXPORTS_OBJECT_REFERENCED;
  159. }
  160. }
  161. if (
  162. this.call &&
  163. !this.directImport &&
  164. (namespaceObjectAsContext || ids.length > 1)
  165. ) {
  166. if (ids.length === 1) return Dependency.EXPORTS_OBJECT_REFERENCED;
  167. ids = ids.slice(0, -1);
  168. }
  169. return this._getReferencedExportsInDestructuring(ids);
  170. }
  171. /**
  172. * @param {string[]=} ids ids
  173. * @returns {string[][]} referenced exports
  174. */
  175. _getReferencedExportsInDestructuring(ids) {
  176. if (this.referencedPropertiesInDestructuring) {
  177. /** @type {string[][]} */
  178. const refs = [];
  179. for (const { id } of this.referencedPropertiesInDestructuring) {
  180. refs.push(ids ? ids.concat([id]) : [id]);
  181. }
  182. return refs;
  183. }
  184. return ids ? [ids] : Dependency.EXPORTS_OBJECT_REFERENCED;
  185. }
  186. /**
  187. * @param {ModuleGraph} moduleGraph module graph
  188. * @returns {number} effective mode
  189. */
  190. _getEffectiveExportPresenceLevel(moduleGraph) {
  191. if (this.exportPresenceMode !== ExportPresenceModes.AUTO)
  192. return this.exportPresenceMode;
  193. const buildMeta =
  194. /** @type {BuildMeta} */
  195. (
  196. /** @type {Module} */
  197. (moduleGraph.getParentModule(this)).buildMeta
  198. );
  199. return buildMeta.strictHarmonyModule
  200. ? ExportPresenceModes.ERROR
  201. : ExportPresenceModes.WARN;
  202. }
  203. /**
  204. * Returns warnings
  205. * @param {ModuleGraph} moduleGraph module graph
  206. * @returns {WebpackError[] | null | undefined} warnings
  207. */
  208. getWarnings(moduleGraph) {
  209. const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph);
  210. if (exportsPresence === ExportPresenceModes.WARN) {
  211. return this._getErrors(moduleGraph);
  212. }
  213. return null;
  214. }
  215. /**
  216. * Returns errors
  217. * @param {ModuleGraph} moduleGraph module graph
  218. * @returns {WebpackError[] | null | undefined} errors
  219. */
  220. getErrors(moduleGraph) {
  221. const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph);
  222. if (exportsPresence === ExportPresenceModes.ERROR) {
  223. return this._getErrors(moduleGraph);
  224. }
  225. return null;
  226. }
  227. /**
  228. * @param {ModuleGraph} moduleGraph module graph
  229. * @returns {WebpackError[] | undefined} errors
  230. */
  231. _getErrors(moduleGraph) {
  232. const ids = this.getIds(moduleGraph);
  233. return this.getLinkingErrors(
  234. moduleGraph,
  235. ids,
  236. `(imported as '${this.name}')`
  237. );
  238. }
  239. /**
  240. * implement this method to allow the occurrence order plugin to count correctly
  241. * @returns {number} count how often the id is used in this dependency
  242. */
  243. getNumberOfIdOccurrences() {
  244. return 0;
  245. }
  246. /**
  247. * @param {ObjectSerializerContext} context context
  248. */
  249. serialize(context) {
  250. const { write } = context;
  251. write(this.ids);
  252. write(this.name);
  253. write(this.range);
  254. write(this.idRanges);
  255. write(this.exportPresenceMode);
  256. write(this.namespaceObjectAsContext);
  257. write(this.call);
  258. write(this.directImport);
  259. write(this.shorthand);
  260. write(this.asiSafe);
  261. write(this.usedByExports);
  262. write(this.referencedPropertiesInDestructuring);
  263. super.serialize(context);
  264. }
  265. /**
  266. * @param {ObjectDeserializerContext} context context
  267. */
  268. deserialize(context) {
  269. const { read } = context;
  270. this.ids = read();
  271. this.name = read();
  272. this.range = read();
  273. this.idRanges = read();
  274. this.exportPresenceMode = read();
  275. this.namespaceObjectAsContext = read();
  276. this.call = read();
  277. this.directImport = read();
  278. this.shorthand = read();
  279. this.asiSafe = read();
  280. this.usedByExports = read();
  281. this.referencedPropertiesInDestructuring = read();
  282. super.deserialize(context);
  283. }
  284. }
  285. makeSerializable(
  286. HarmonyImportSpecifierDependency,
  287. "webpack/lib/dependencies/HarmonyImportSpecifierDependency"
  288. );
  289. HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependencyTemplate extends (
  290. HarmonyImportDependency.Template
  291. ) {
  292. /**
  293. * @param {Dependency} dependency the dependency for which the template should be applied
  294. * @param {ReplaceSource} source the current replace source which can be modified
  295. * @param {DependencyTemplateContext} templateContext the context object
  296. * @returns {void}
  297. */
  298. apply(dependency, source, templateContext) {
  299. const dep = /** @type {HarmonyImportSpecifierDependency} */ (dependency);
  300. const { moduleGraph, runtime } = templateContext;
  301. const connection = moduleGraph.getConnection(dep);
  302. // Skip rendering depending when dependency is conditional
  303. if (connection && !connection.isTargetActive(runtime)) return;
  304. const ids = dep.getIds(moduleGraph);
  305. const {
  306. trimmedRange: [trimmedRangeStart, trimmedRangeEnd],
  307. trimmedIds
  308. } = getTrimmedIdsAndRange(ids, dep.range, dep.idRanges, moduleGraph, dep);
  309. const exportExpr = this._getCodeForIds(
  310. dep,
  311. source,
  312. templateContext,
  313. trimmedIds
  314. );
  315. if (dep.shorthand) {
  316. source.insert(trimmedRangeEnd, `: ${exportExpr}`);
  317. } else {
  318. source.replace(trimmedRangeStart, trimmedRangeEnd - 1, exportExpr);
  319. }
  320. if (dep.referencedPropertiesInDestructuring) {
  321. let prefixedIds = ids;
  322. if (ids[0] === "default") {
  323. const selfModule =
  324. /** @type {Module} */
  325. (moduleGraph.getParentModule(dep));
  326. const importedModule =
  327. /** @type {Module} */
  328. (moduleGraph.getModule(dep));
  329. const exportsType = importedModule.getExportsType(
  330. moduleGraph,
  331. /** @type {BuildMeta} */
  332. (selfModule.buildMeta).strictHarmonyModule
  333. );
  334. if (
  335. (exportsType === "default-only" ||
  336. exportsType === "default-with-named") &&
  337. ids.length >= 1
  338. ) {
  339. prefixedIds = ids.slice(1);
  340. }
  341. }
  342. for (const {
  343. id,
  344. shorthand,
  345. range
  346. } of dep.referencedPropertiesInDestructuring) {
  347. const concatedIds = prefixedIds.concat([id]);
  348. const module = /** @type {Module} */ (moduleGraph.getModule(dep));
  349. const used = moduleGraph
  350. .getExportsInfo(module)
  351. .getUsedName(concatedIds, runtime);
  352. if (!used) return;
  353. const newName = used[used.length - 1];
  354. const name = concatedIds[concatedIds.length - 1];
  355. if (newName === name) continue;
  356. const comment = `${Template.toNormalComment(name)} `;
  357. const key = comment + JSON.stringify(newName);
  358. source.replace(
  359. /** @type {Range} */
  360. (range)[0],
  361. /** @type {Range} */
  362. (range)[1] - 1,
  363. shorthand ? `${key}: ${name}` : `${key}`
  364. );
  365. }
  366. }
  367. }
  368. /**
  369. * @param {HarmonyImportSpecifierDependency} dep dependency
  370. * @param {ReplaceSource} source source
  371. * @param {DependencyTemplateContext} templateContext context
  372. * @param {string[]} ids ids
  373. * @returns {string} generated code
  374. */
  375. _getCodeForIds(dep, source, templateContext, ids) {
  376. const { moduleGraph, module, runtime, concatenationScope } =
  377. templateContext;
  378. const connection = moduleGraph.getConnection(dep);
  379. let exportExpr;
  380. if (
  381. connection &&
  382. concatenationScope &&
  383. concatenationScope.isModuleInScope(connection.module)
  384. ) {
  385. if (ids.length === 0) {
  386. exportExpr = concatenationScope.createModuleReference(
  387. connection.module,
  388. {
  389. asiSafe: dep.asiSafe
  390. }
  391. );
  392. } else if (dep.namespaceObjectAsContext && ids.length === 1) {
  393. exportExpr =
  394. concatenationScope.createModuleReference(connection.module, {
  395. asiSafe: dep.asiSafe
  396. }) + propertyAccess(ids);
  397. } else {
  398. exportExpr = concatenationScope.createModuleReference(
  399. connection.module,
  400. {
  401. ids,
  402. call: dep.call,
  403. directImport: dep.directImport,
  404. asiSafe: dep.asiSafe
  405. }
  406. );
  407. }
  408. } else {
  409. super.apply(dep, source, templateContext);
  410. const { runtimeTemplate, initFragments, runtimeRequirements } =
  411. templateContext;
  412. exportExpr = runtimeTemplate.exportFromImport({
  413. moduleGraph,
  414. module: /** @type {Module} */ (moduleGraph.getModule(dep)),
  415. request: dep.request,
  416. exportName: ids,
  417. originModule: module,
  418. asiSafe: dep.shorthand ? true : dep.asiSafe,
  419. isCall: dep.call,
  420. callContext: !dep.directImport,
  421. defaultInterop: true,
  422. importVar: dep.getImportVar(moduleGraph),
  423. initFragments,
  424. runtime,
  425. runtimeRequirements
  426. });
  427. }
  428. return exportExpr;
  429. }
  430. };
  431. module.exports = HarmonyImportSpecifierDependency;