Dependency.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { JAVASCRIPT_TYPE } = require("./ModuleSourceTypeConstants");
  7. const memoize = require("./util/memoize");
  8. /** @import ChunkGraph from "./ChunkGraph" */
  9. /** @import DependenciesBlock from "./DependenciesBlock" */
  10. /** @import Module, { SourceType } from "./Module" */
  11. /** @import ModuleGraph from "./ModuleGraph" */
  12. /**
  13. * @import ModuleGraphConnection, {
  14. * ConnectionState
  15. * } from "./ModuleGraphConnection"
  16. */
  17. /** @import RuntimeTemplate from "./RuntimeTemplate" */
  18. /** @import WebpackError from "./errors/WebpackError" */
  19. /**
  20. * @import {
  21. * ObjectDeserializerContext,
  22. * ObjectSerializerContext
  23. * } from "./serialization/ObjectMiddleware"
  24. */
  25. /** @import Hash from "./util/Hash" */
  26. /** @import { RuntimeSpec } from "./util/runtime" */
  27. /** @import ModuleDependency from "./dependencies/ModuleDependency" */
  28. /**
  29. * Defines the update hash context type used by this module.
  30. * @typedef {object} UpdateHashContext
  31. * @property {ChunkGraph} chunkGraph
  32. * @property {RuntimeSpec} runtime
  33. * @property {RuntimeTemplate=} runtimeTemplate
  34. */
  35. /**
  36. * Defines the source position type used by this module.
  37. * @typedef {object} SourcePosition
  38. * @property {number} line
  39. * @property {number=} column
  40. */
  41. /**
  42. * Defines the real dependency location type used by this module.
  43. * @typedef {object} RealDependencyLocation
  44. * @property {SourcePosition} start
  45. * @property {SourcePosition=} end
  46. * @property {number=} index
  47. */
  48. /**
  49. * Defines the synthetic dependency location type used by this module.
  50. * @typedef {object} SyntheticDependencyLocation
  51. * @property {string} name
  52. * @property {number=} index
  53. */
  54. /** @typedef {SyntheticDependencyLocation | RealDependencyLocation} DependencyLocation */
  55. /** @typedef {string} ExportInfoName */
  56. /**
  57. * Defines the export spec type used by this module.
  58. * @typedef {object} ExportSpec
  59. * @property {ExportInfoName} name the name of the export
  60. * @property {boolean=} canMangle can the export be renamed (defaults to true)
  61. * @property {boolean=} terminalBinding is the export a terminal binding that should be checked for export star conflicts
  62. * @property {boolean=} isPure calling this export has no observable side effects
  63. * @property {(string | ExportSpec)[]=} exports nested exports
  64. * @property {ModuleGraphConnection=} from when reexported: from which module
  65. * @property {string[] | null=} export when reexported: from which export
  66. * @property {number=} priority when reexported: with which priority
  67. * @property {boolean=} hidden export is not visible, because another export blends over it
  68. * @property {import("./optimize/InlineExports").InlinedValue=} inlined when set: the export binds to a small primitive constant eligible for inlining
  69. */
  70. /** @typedef {Set<string>} ExportsSpecExcludeExports */
  71. /**
  72. * Defines the exports spec type used by this module.
  73. * @typedef {object} ExportsSpec
  74. * @property {(string | ExportSpec)[] | true | null} exports exported names, true for unknown exports or null for no exports
  75. * @property {ExportsSpecExcludeExports=} excludeExports when exports = true, list of unaffected exports
  76. * @property {(Set<string> | null)=} hideExports list of maybe prior exposed, but now hidden exports
  77. * @property {ModuleGraphConnection=} from when reexported: from which module
  78. * @property {number=} priority when reexported: with which priority
  79. * @property {boolean=} canMangle can the export be renamed (defaults to true)
  80. * @property {boolean=} terminalBinding are the exports terminal bindings that should be checked for export star conflicts
  81. * @property {boolean=} isPure calling these exports has no observable side effects
  82. * @property {Module[]=} dependencies module on which the result depends on
  83. */
  84. /**
  85. * Defines the referenced export type used by this module.
  86. * @typedef {object} ReferencedExport
  87. * @property {string[]} name name of the referenced export
  88. * @property {boolean=} canMangle when false, referenced export can not be mangled, defaults to true
  89. * @property {boolean=} canInline when false, the referenced export can not be substituted with an inlined literal at this site, defaults to true
  90. */
  91. /** @typedef {string[][]} RawReferencedExports */
  92. /** @typedef {(string[] | ReferencedExport)[]} ReferencedExports */
  93. /** @typedef {(moduleGraphConnection: ModuleGraphConnection, runtime: RuntimeSpec) => ConnectionState} GetConditionFn */
  94. /**
  95. * Lazy barrel classification of a dependency within a side-effect-free module.
  96. * `LAZY_UNTIL_LOCAL`: locally provided export name (`getLazyName`), requesting it requires no dependency.
  97. * `LAZY_UNTIL_ID`: named re-export (`getLazyName`) deferred until the export name is requested.
  98. * `LAZY_UNTIL_FALLBACK`: star re-export, deferred until an unknown name or all names are requested.
  99. * `LAZY_UNTIL_REQUEST`: deferred together with other dependencies of the same request.
  100. * @typedef {"local" | "id" | "*" | "@"} LazyUntil
  101. */
  102. const LAZY_UNTIL_LOCAL = /** @type {"local"} */ ("local");
  103. const LAZY_UNTIL_ID = /** @type {"id"} */ ("id");
  104. const LAZY_UNTIL_FALLBACK = /** @type {"*"} */ ("*");
  105. const LAZY_UNTIL_REQUEST = /** @type {"@"} */ ("@");
  106. const TRANSITIVE = /** @type {symbol} */ (Symbol("transitive"));
  107. const getIgnoredModule = memoize(() => {
  108. const RawModule = require("./RawModule");
  109. const module = new RawModule("/* (ignored) */", "ignored", "(ignored)");
  110. module.factoryMeta = { sideEffectFree: true };
  111. return module;
  112. });
  113. class Dependency {
  114. constructor() {
  115. /** @type {Module | undefined} */
  116. this._parentModule = undefined;
  117. /** @type {DependenciesBlock | undefined} */
  118. this._parentDependenciesBlock = undefined;
  119. /** @type {number} */
  120. this._parentDependenciesBlockIndex = -1;
  121. // stays on base: also set on ContextDependency, which is not a ModuleDependency
  122. /** @type {boolean | undefined} */
  123. this.optional = false;
  124. /** @type {number} */
  125. this._locSL = 0;
  126. /** @type {number} */
  127. this._locSC = 0;
  128. /** @type {number} */
  129. this._locEL = 0;
  130. /** @type {number} */
  131. this._locEC = 0;
  132. /** @type {undefined | number} */
  133. this._locI = undefined;
  134. /** @type {undefined | string} */
  135. this._locN = undefined;
  136. /** @type {undefined | DependencyLocation} */
  137. this._loc = undefined;
  138. }
  139. /**
  140. * Returns a display name for the type of dependency.
  141. * @returns {string} a display name for the type of dependency
  142. */
  143. get type() {
  144. return "unknown";
  145. }
  146. /**
  147. * Returns a dependency category, typical categories are "commonjs", "amd", "esm".
  148. * @returns {string} a dependency category, typical categories are "commonjs", "amd", "esm"
  149. */
  150. get category() {
  151. return "unknown";
  152. }
  153. /**
  154. * Returns the source type this dependency reads from the module it references:
  155. * `javascript` for anything going through the module wrapper, `asset-url` for a
  156. * bare url embedded into non-javascript output (css, html, a manifest).
  157. * @returns {SourceType} the source type read from the referenced module
  158. */
  159. get referencedSourceType() {
  160. return JAVASCRIPT_TYPE;
  161. }
  162. /**
  163. * Returns location.
  164. * @returns {DependencyLocation} location
  165. */
  166. get loc() {
  167. if (this._loc !== undefined) return this._loc;
  168. /** @type {SyntheticDependencyLocation & RealDependencyLocation} */
  169. const loc = {};
  170. if (this._locSL > 0) {
  171. loc.start = { line: this._locSL, column: this._locSC };
  172. }
  173. if (this._locEL > 0) {
  174. loc.end = { line: this._locEL, column: this._locEC };
  175. }
  176. if (this._locN !== undefined) {
  177. loc.name = this._locN;
  178. }
  179. if (this._locI !== undefined) {
  180. loc.index = this._locI;
  181. }
  182. return (this._loc = loc);
  183. }
  184. set loc(loc) {
  185. if ("start" in loc && typeof loc.start === "object") {
  186. this._locSL = loc.start.line || 0;
  187. this._locSC = loc.start.column || 0;
  188. } else {
  189. this._locSL = 0;
  190. this._locSC = 0;
  191. }
  192. if ("end" in loc && typeof loc.end === "object") {
  193. this._locEL = loc.end.line || 0;
  194. this._locEC = loc.end.column || 0;
  195. } else {
  196. this._locEL = 0;
  197. this._locEC = 0;
  198. }
  199. this._locI = "index" in loc ? loc.index : undefined;
  200. this._locN = "name" in loc ? loc.name : undefined;
  201. // Don't retain the passed object; `get loc` rebuilds it from the numbers
  202. // above on demand, so dependencies whose loc is never read hold 4 numbers
  203. // instead of a SourceLocation + two Position objects.
  204. this._loc = undefined;
  205. }
  206. /**
  207. * Updates loc using the provided start line.
  208. * @param {number} startLine start line
  209. * @param {number} startColumn start column
  210. * @param {number} endLine end line
  211. * @param {number} endColumn end column
  212. */
  213. setLoc(startLine, startColumn, endLine, endColumn) {
  214. this._locSL = startLine;
  215. this._locSC = startColumn;
  216. this._locEL = endLine;
  217. this._locEC = endColumn;
  218. this._locI = undefined;
  219. this._locN = undefined;
  220. this._loc = undefined;
  221. }
  222. /**
  223. * Updates loc from a source location plus an explicit index, without
  224. * materializing the `loc` object (keeps `get loc` lazy). Replaces the
  225. * `dep.loc = Object.create(loc); dep.loc.index = i` pattern, which both
  226. * allocated a copy and stored the index outside the serialized fields.
  227. * @param {DependencyLocation} loc source location (start/end/name read from it)
  228. * @param {number} index dependency index within the statement
  229. */
  230. setLocWithIndex(loc, index) {
  231. this.loc = loc;
  232. this._locI = index;
  233. }
  234. /**
  235. * Compares two dependencies by source location for sorting a module's
  236. * `dependencies`, without materializing the `loc` objects (`get loc` caches
  237. * its result, so comparing through it would retain a location object on every
  238. * sorted dependency). These dependencies always carry a real source position,
  239. * so only start (line, column) and the within-statement index are compared; a
  240. * dependency without an index sorts after one that has an index at the same
  241. * position.
  242. * @param {Dependency} a first dependency
  243. * @param {Dependency} b second dependency
  244. * @returns {-1 | 0 | 1} compare result
  245. */
  246. static compareLocations(a, b) {
  247. if (a._locSL !== b._locSL) return a._locSL < b._locSL ? -1 : 1;
  248. if (a._locSC !== b._locSC) return a._locSC < b._locSC ? -1 : 1;
  249. const ai = a._locI;
  250. const bi = b._locI;
  251. if (ai === bi) return 0;
  252. if (ai === undefined) return 1;
  253. if (bi === undefined) return -1;
  254. return ai < bi ? -1 : 1;
  255. }
  256. /**
  257. * Returns a request context.
  258. * @returns {string | undefined} a request context
  259. */
  260. getContext() {
  261. return undefined;
  262. }
  263. /**
  264. * Returns an identifier to merge equal requests.
  265. * @returns {string | null} an identifier to merge equal requests
  266. */
  267. getResourceIdentifier() {
  268. return null;
  269. }
  270. /**
  271. * Could affect referencing module.
  272. * @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
  273. */
  274. couldAffectReferencingModule() {
  275. return TRANSITIVE;
  276. }
  277. /**
  278. * Returns the export name this dependency requests from its target module (lazy barrel optimization).
  279. * @returns {string | true | null} export name, true for all exports, null for none
  280. */
  281. getForwardId() {
  282. // unknown dependency types conservatively request all exports
  283. return true;
  284. }
  285. /**
  286. * Returns how this dependency may be deferred when its parent module is side-effect-free (lazy barrel optimization).
  287. * @returns {LazyUntil | null} lazy classification, null when it must be processed eagerly
  288. */
  289. getLazyUntil() {
  290. return null;
  291. }
  292. /**
  293. * Returns the export name for a `LAZY_UNTIL_LOCAL`/`LAZY_UNTIL_ID` classification (lazy barrel optimization).
  294. * @returns {string | null} export name, null when not applicable
  295. */
  296. getLazyName() {
  297. return null;
  298. }
  299. /**
  300. * Whether the lazy barrel currently defers creating this dependency's target module (lazy barrel optimization).
  301. * @returns {boolean} true while deferred, so it must not be processed or rendered
  302. */
  303. isLazy() {
  304. return false;
  305. }
  306. /**
  307. * Sets whether the lazy barrel defers creating this dependency's target module (lazy barrel optimization).
  308. * @param {boolean} value true to defer, false to create it now
  309. */
  310. setLazy(value) {}
  311. /**
  312. * Returns the referenced module and export
  313. * @deprecated
  314. * @param {ModuleGraph} moduleGraph module graph
  315. * @returns {never} throws error
  316. */
  317. getReference(moduleGraph) {
  318. throw new Error(
  319. "Dependency.getReference was removed in favor of Dependency.getReferencedExports, ModuleGraph.getModule, ModuleGraph.getConnection(), and ModuleGraphConnection.getActiveState(runtime)"
  320. );
  321. }
  322. /**
  323. * Returns list of exports referenced by this dependency
  324. * @param {ModuleGraph} moduleGraph module graph
  325. * @param {RuntimeSpec} runtime the runtime for which the module is analysed
  326. * @returns {ReferencedExports} referenced exports
  327. */
  328. getReferencedExports(moduleGraph, runtime) {
  329. return Dependency.EXPORTS_OBJECT_REFERENCED;
  330. }
  331. /**
  332. * Returns function to determine if the connection is active.
  333. * @param {ModuleGraph} moduleGraph module graph
  334. * @returns {null | false | GetConditionFn} function to determine if the connection is active
  335. */
  336. getCondition(moduleGraph) {
  337. return null;
  338. }
  339. /**
  340. * Returns the exported names
  341. * @param {ModuleGraph} moduleGraph module graph
  342. * @returns {ExportsSpec | undefined} export names
  343. */
  344. getExports(moduleGraph) {
  345. return undefined;
  346. }
  347. /**
  348. * Returns warnings.
  349. * @param {ModuleGraph} moduleGraph module graph
  350. * @returns {WebpackError[] | null | undefined} warnings
  351. */
  352. getWarnings(moduleGraph) {
  353. return null;
  354. }
  355. /**
  356. * Returns errors.
  357. * @param {ModuleGraph} moduleGraph module graph
  358. * @returns {WebpackError[] | null | undefined} errors
  359. */
  360. getErrors(moduleGraph) {
  361. return null;
  362. }
  363. /**
  364. * Updates the hash with the data contributed by this instance.
  365. * @param {Hash} hash hash to be updated
  366. * @param {UpdateHashContext} context context
  367. * @returns {void}
  368. */
  369. updateHash(hash, context) {}
  370. /**
  371. * implement this method to allow the occurrence order plugin to count correctly
  372. * @returns {number} count how often the id is used in this dependency
  373. */
  374. getNumberOfIdOccurrences() {
  375. return 1;
  376. }
  377. /**
  378. * Gets module evaluation side effects state.
  379. * @param {ModuleGraph} moduleGraph the module graph
  380. * @returns {ConnectionState} how this dependency connects the module to referencing modules
  381. */
  382. getModuleEvaluationSideEffectsState(moduleGraph) {
  383. return true;
  384. }
  385. /**
  386. * Creates an ignored module.
  387. * @param {string} context context directory
  388. * @returns {Module} ignored module
  389. */
  390. createIgnoredModule(context) {
  391. return getIgnoredModule();
  392. }
  393. /**
  394. * Returns true if this dependency can be concatenated
  395. * @param {boolean} concatenateCommonJsModules whether optimization.concatenateModules.commonjs is enabled
  396. * @returns {boolean} true if this dependency can be concatenated
  397. */
  398. canConcatenate(concatenateCommonJsModules) {
  399. return false;
  400. }
  401. /**
  402. * Serializes this instance into the provided serializer context.
  403. * @param {ObjectSerializerContext} context context
  404. */
  405. serialize({ write }) {
  406. write(this.optional);
  407. write(this._locSL);
  408. write(this._locSC);
  409. write(this._locEL);
  410. write(this._locEC);
  411. write(this._locI);
  412. write(this._locN);
  413. }
  414. /**
  415. * Restores this instance from the provided deserializer context.
  416. * @param {ObjectDeserializerContext} context context
  417. */
  418. deserialize({ read }) {
  419. this.optional = read();
  420. this._locSL = read();
  421. this._locSC = read();
  422. this._locEL = read();
  423. this._locEC = read();
  424. this._locI = read();
  425. this._locN = read();
  426. }
  427. }
  428. /** @type {RawReferencedExports} */
  429. Dependency.NO_EXPORTS_REFERENCED = [];
  430. /** @type {RawReferencedExports} */
  431. Dependency.EXPORTS_OBJECT_REFERENCED = [[]];
  432. // Like EXPORTS_OBJECT_REFERENCED, but the reference can be rendered as a
  433. // decoupled namespace object, so the module's exports stay mangleable.
  434. // Same shape as EXPORTS_OBJECT_REFERENCED; only distinguished by identity.
  435. /** @type {RawReferencedExports} */
  436. Dependency.EXPORTS_OBJECT_REFERENCED_MANGLEABLE = [[]];
  437. // TODO remove in webpack 6
  438. Object.defineProperty(Dependency.prototype, "module", {
  439. /**
  440. * Returns throws.
  441. * @deprecated
  442. * @returns {EXPECTED_ANY} throws
  443. */
  444. get() {
  445. throw new Error(
  446. "module property was removed from Dependency (use compilation.moduleGraph.getModule(dependency) instead)"
  447. );
  448. },
  449. /**
  450. * Updates module.
  451. * @deprecated
  452. * @returns {never} throws
  453. */
  454. set() {
  455. throw new Error(
  456. "module property was removed from Dependency (use compilation.moduleGraph.updateModule(dependency, module) instead)"
  457. );
  458. }
  459. });
  460. /**
  461. * Returns true if the dependency is a low priority dependency.
  462. * @param {Dependency} dependency dep
  463. * @returns {boolean} true if the dependency is a low priority dependency
  464. */
  465. Dependency.isLowPriorityDependency = (dependency) =>
  466. /** @type {ModuleDependency} */ (dependency).sourceOrder === Infinity;
  467. // TODO in webpack 6, call canConcatenate() directly on the dependency instance instead of using this static method.
  468. /**
  469. * Returns true if the dependency can be concatenated (scope hoisting).
  470. * @param {Dependency} dependency dep
  471. * @param {boolean} concatenateCommonJsModules whether optimization.concatenateModules.commonjs is enabled
  472. * @returns {boolean} true if this dependency supports concatenation
  473. */
  474. Dependency.canConcatenate = (dependency, concatenateCommonJsModules) => {
  475. if (typeof dependency.canConcatenate === "function") {
  476. return dependency.canConcatenate(concatenateCommonJsModules);
  477. }
  478. return false;
  479. };
  480. // TODO remove in webpack 6
  481. Object.defineProperty(Dependency.prototype, "disconnect", {
  482. /**
  483. * Returns throws.
  484. * @deprecated
  485. * @returns {EXPECTED_ANY} throws
  486. */
  487. get() {
  488. throw new Error(
  489. "disconnect was removed from Dependency (Dependency no longer carries graph specific information)"
  490. );
  491. }
  492. });
  493. Dependency.TRANSITIVE = TRANSITIVE;
  494. Dependency.LAZY_UNTIL_LOCAL = LAZY_UNTIL_LOCAL;
  495. Dependency.LAZY_UNTIL_ID = LAZY_UNTIL_ID;
  496. Dependency.LAZY_UNTIL_FALLBACK = LAZY_UNTIL_FALLBACK;
  497. Dependency.LAZY_UNTIL_REQUEST = LAZY_UNTIL_REQUEST;
  498. module.exports = Dependency;