ModuleFilenameHelpers.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const NormalModule = require("./NormalModule");
  7. const { DEFAULTS } = require("./config/defaults");
  8. const createHash = require("./util/createHash");
  9. const memoize = require("./util/memoize");
  10. /** @typedef {import("../declarations/WebpackOptions").DevtoolModuleFilenameTemplate} DevtoolModuleFilenameTemplate */
  11. /** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */
  12. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  13. /** @typedef {import("./Module")} Module */
  14. /** @typedef {import("./RequestShortener")} RequestShortener */
  15. /** @typedef {string | RegExp | (string | RegExp)[]} Matcher */
  16. /** @typedef {{ test?: Matcher, include?: Matcher, exclude?: Matcher }} MatchObject */
  17. const ModuleFilenameHelpers = module.exports;
  18. // TODO webpack 6: consider removing these
  19. ModuleFilenameHelpers.ALL_LOADERS_RESOURCE = "[all-loaders][resource]";
  20. ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE =
  21. /\[all-?loaders\]\[resource\]/gi;
  22. ModuleFilenameHelpers.LOADERS_RESOURCE = "[loaders][resource]";
  23. ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE = /\[loaders\]\[resource\]/gi;
  24. ModuleFilenameHelpers.RESOURCE = "[resource]";
  25. ModuleFilenameHelpers.REGEXP_RESOURCE = /\[resource\]/gi;
  26. ModuleFilenameHelpers.ABSOLUTE_RESOURCE_PATH = "[absolute-resource-path]";
  27. // cSpell:words olute
  28. ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH =
  29. /\[abs(olute)?-?resource-?path\]/gi;
  30. ModuleFilenameHelpers.RESOURCE_PATH = "[resource-path]";
  31. ModuleFilenameHelpers.REGEXP_RESOURCE_PATH = /\[resource-?path\]/gi;
  32. ModuleFilenameHelpers.ALL_LOADERS = "[all-loaders]";
  33. ModuleFilenameHelpers.REGEXP_ALL_LOADERS = /\[all-?loaders\]/gi;
  34. ModuleFilenameHelpers.LOADERS = "[loaders]";
  35. ModuleFilenameHelpers.REGEXP_LOADERS = /\[loaders\]/gi;
  36. ModuleFilenameHelpers.QUERY = "[query]";
  37. ModuleFilenameHelpers.REGEXP_QUERY = /\[query\]/gi;
  38. ModuleFilenameHelpers.ID = "[id]";
  39. ModuleFilenameHelpers.REGEXP_ID = /\[id\]/gi;
  40. ModuleFilenameHelpers.HASH = "[hash]";
  41. ModuleFilenameHelpers.REGEXP_HASH = /\[hash\]/gi;
  42. ModuleFilenameHelpers.NAMESPACE = "[namespace]";
  43. ModuleFilenameHelpers.REGEXP_NAMESPACE = /\[namespace\]/gi;
  44. /** @typedef {() => string} ReturnStringCallback */
  45. /**
  46. * Returns a function that returns the part of the string after the token
  47. * @param {ReturnStringCallback} strFn the function to get the string
  48. * @param {string} token the token to search for
  49. * @returns {ReturnStringCallback} a function that returns the part of the string after the token
  50. */
  51. const getAfter = (strFn, token) => () => {
  52. const str = strFn();
  53. const idx = str.indexOf(token);
  54. return idx < 0 ? "" : str.slice(idx);
  55. };
  56. /**
  57. * Returns a function that returns the part of the string before the token
  58. * @param {ReturnStringCallback} strFn the function to get the string
  59. * @param {string} token the token to search for
  60. * @returns {ReturnStringCallback} a function that returns the part of the string before the token
  61. */
  62. const getBefore = (strFn, token) => () => {
  63. const str = strFn();
  64. const idx = str.lastIndexOf(token);
  65. return idx < 0 ? "" : str.slice(0, idx);
  66. };
  67. /**
  68. * Returns a function that returns a hash of the string
  69. * @param {ReturnStringCallback} strFn the function to get the string
  70. * @param {HashFunction=} hashFunction the hash function to use
  71. * @returns {ReturnStringCallback} a function that returns the hash of the string
  72. */
  73. const getHash =
  74. (strFn, hashFunction = DEFAULTS.HASH_FUNCTION) =>
  75. () => {
  76. const hash = createHash(hashFunction);
  77. hash.update(strFn());
  78. const digest = /** @type {string} */ (hash.digest("hex"));
  79. return digest.slice(0, 4);
  80. };
  81. /**
  82. * @template T
  83. * Returns a lazy object. The object is lazy in the sense that the properties are
  84. * only evaluated when they are accessed. This is only obtained by setting a function as the value for each key.
  85. * @param {Record<string, () => T>} obj the object to convert to a lazy access object
  86. * @returns {T} the lazy access object
  87. */
  88. const lazyObject = obj => {
  89. const newObj = /** @type {T} */ ({});
  90. for (const key of Object.keys(obj)) {
  91. const fn = obj[key];
  92. Object.defineProperty(newObj, key, {
  93. get: () => fn(),
  94. set: v => {
  95. Object.defineProperty(newObj, key, {
  96. value: v,
  97. enumerable: true,
  98. writable: true
  99. });
  100. },
  101. enumerable: true,
  102. configurable: true
  103. });
  104. }
  105. return newObj;
  106. };
  107. const SQUARE_BRACKET_TAG_REGEXP = /\[\\*([\w-]+)\\*\]/gi;
  108. /** @typedef {((context: TODO) => string)} ModuleFilenameTemplateFunction */
  109. /** @typedef {string | ModuleFilenameTemplateFunction} ModuleFilenameTemplate */
  110. /**
  111. * @param {Module | string} module the module
  112. * @param {{ namespace?: string, moduleFilenameTemplate?: ModuleFilenameTemplate }} options options
  113. * @param {{ requestShortener: RequestShortener, chunkGraph: ChunkGraph, hashFunction?: HashFunction }} contextInfo context info
  114. * @returns {string} the filename
  115. */
  116. ModuleFilenameHelpers.createFilename = (
  117. // eslint-disable-next-line default-param-last
  118. module = "",
  119. options,
  120. { requestShortener, chunkGraph, hashFunction = DEFAULTS.HASH_FUNCTION }
  121. ) => {
  122. const opts = {
  123. namespace: "",
  124. moduleFilenameTemplate: "",
  125. ...(typeof options === "object"
  126. ? options
  127. : {
  128. moduleFilenameTemplate: options
  129. })
  130. };
  131. /** @type {ReturnStringCallback} */
  132. let absoluteResourcePath;
  133. let hash;
  134. /** @type {ReturnStringCallback} */
  135. let identifier;
  136. /** @type {ReturnStringCallback} */
  137. let moduleId;
  138. /** @type {ReturnStringCallback} */
  139. let shortIdentifier;
  140. if (typeof module === "string") {
  141. shortIdentifier =
  142. /** @type {ReturnStringCallback} */
  143. (memoize(() => requestShortener.shorten(module)));
  144. identifier = shortIdentifier;
  145. moduleId = () => "";
  146. absoluteResourcePath = () =>
  147. /** @type {string} */ (module.split("!").pop());
  148. hash = getHash(identifier, hashFunction);
  149. } else {
  150. shortIdentifier = memoize(() =>
  151. module.readableIdentifier(requestShortener)
  152. );
  153. identifier =
  154. /** @type {ReturnStringCallback} */
  155. (memoize(() => requestShortener.shorten(module.identifier())));
  156. moduleId =
  157. /** @type {ReturnStringCallback} */
  158. (() => chunkGraph.getModuleId(module));
  159. absoluteResourcePath = () =>
  160. module instanceof NormalModule
  161. ? module.resource
  162. : /** @type {string} */ (module.identifier().split("!").pop());
  163. hash = getHash(identifier, hashFunction);
  164. }
  165. const resource =
  166. /** @type {ReturnStringCallback} */
  167. (memoize(() => shortIdentifier().split("!").pop()));
  168. const loaders = getBefore(shortIdentifier, "!");
  169. const allLoaders = getBefore(identifier, "!");
  170. const query = getAfter(resource, "?");
  171. const resourcePath = () => {
  172. const q = query().length;
  173. return q === 0 ? resource() : resource().slice(0, -q);
  174. };
  175. if (typeof opts.moduleFilenameTemplate === "function") {
  176. return opts.moduleFilenameTemplate(
  177. lazyObject({
  178. identifier,
  179. shortIdentifier,
  180. resource,
  181. resourcePath: memoize(resourcePath),
  182. absoluteResourcePath: memoize(absoluteResourcePath),
  183. loaders: memoize(loaders),
  184. allLoaders: memoize(allLoaders),
  185. query: memoize(query),
  186. moduleId: memoize(moduleId),
  187. hash: memoize(hash),
  188. namespace: () => opts.namespace
  189. })
  190. );
  191. }
  192. // TODO webpack 6: consider removing alternatives without dashes
  193. /** @type {Map<string, () => string>} */
  194. const replacements = new Map([
  195. ["identifier", identifier],
  196. ["short-identifier", shortIdentifier],
  197. ["resource", resource],
  198. ["resource-path", resourcePath],
  199. // cSpell:words resourcepath
  200. ["resourcepath", resourcePath],
  201. ["absolute-resource-path", absoluteResourcePath],
  202. ["abs-resource-path", absoluteResourcePath],
  203. // cSpell:words absoluteresource
  204. ["absoluteresource-path", absoluteResourcePath],
  205. // cSpell:words absresource
  206. ["absresource-path", absoluteResourcePath],
  207. // cSpell:words resourcepath
  208. ["absolute-resourcepath", absoluteResourcePath],
  209. // cSpell:words resourcepath
  210. ["abs-resourcepath", absoluteResourcePath],
  211. // cSpell:words absoluteresourcepath
  212. ["absoluteresourcepath", absoluteResourcePath],
  213. // cSpell:words absresourcepath
  214. ["absresourcepath", absoluteResourcePath],
  215. ["all-loaders", allLoaders],
  216. // cSpell:words allloaders
  217. ["allloaders", allLoaders],
  218. ["loaders", loaders],
  219. ["query", query],
  220. ["id", moduleId],
  221. ["hash", hash],
  222. ["namespace", () => opts.namespace]
  223. ]);
  224. // TODO webpack 6: consider removing weird double placeholders
  225. return /** @type {string} */ (opts.moduleFilenameTemplate)
  226. .replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE, "[identifier]")
  227. .replace(
  228. ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE,
  229. "[short-identifier]"
  230. )
  231. .replace(SQUARE_BRACKET_TAG_REGEXP, (match, content) => {
  232. if (content.length + 2 === match.length) {
  233. const replacement = replacements.get(content.toLowerCase());
  234. if (replacement !== undefined) {
  235. return replacement();
  236. }
  237. } else if (match.startsWith("[\\") && match.endsWith("\\]")) {
  238. return `[${match.slice(2, -2)}]`;
  239. }
  240. return match;
  241. });
  242. };
  243. /**
  244. * Replaces duplicate items in an array with new values generated by a callback function.
  245. * The callback function is called with the duplicate item, the index of the duplicate item, and the number of times the item has been replaced.
  246. * The callback function should return the new value for the duplicate item.
  247. * @template T
  248. * @param {T[]} array the array with duplicates to be replaced
  249. * @param {(duplicateItem: T, duplicateItemIndex: number, numberOfTimesReplaced: number) => T} fn callback function to generate new values for the duplicate items
  250. * @param {(firstElement:T, nextElement:T) => -1 | 0 | 1=} comparator optional comparator function to sort the duplicate items
  251. * @returns {T[]} the array with duplicates replaced
  252. * @example
  253. * ```js
  254. * const array = ["a", "b", "c", "a", "b", "a"];
  255. * const result = ModuleFilenameHelpers.replaceDuplicates(array, (item, index, count) => `${item}-${count}`);
  256. * // result: ["a-1", "b-1", "c", "a-2", "b-2", "a-3"]
  257. * ```
  258. */
  259. ModuleFilenameHelpers.replaceDuplicates = (array, fn, comparator) => {
  260. const countMap = Object.create(null);
  261. const posMap = Object.create(null);
  262. for (const [idx, item] of array.entries()) {
  263. countMap[item] = countMap[item] || [];
  264. countMap[item].push(idx);
  265. posMap[item] = 0;
  266. }
  267. if (comparator) {
  268. for (const item of Object.keys(countMap)) {
  269. countMap[item].sort(comparator);
  270. }
  271. }
  272. return array.map((item, i) => {
  273. if (countMap[item].length > 1) {
  274. if (comparator && countMap[item][0] === i) return item;
  275. return fn(item, i, posMap[item]++);
  276. }
  277. return item;
  278. });
  279. };
  280. /**
  281. * Tests if a string matches a RegExp or an array of RegExp.
  282. * @param {string} str string to test
  283. * @param {Matcher} test value which will be used to match against the string
  284. * @returns {boolean} true, when the RegExp matches
  285. * @example
  286. * ```js
  287. * ModuleFilenameHelpers.matchPart("foo.js", "foo"); // true
  288. * ModuleFilenameHelpers.matchPart("foo.js", "foo.js"); // true
  289. * ModuleFilenameHelpers.matchPart("foo.js", "foo."); // false
  290. * ModuleFilenameHelpers.matchPart("foo.js", "foo*"); // false
  291. * ModuleFilenameHelpers.matchPart("foo.js", "foo.*"); // true
  292. * ModuleFilenameHelpers.matchPart("foo.js", /^foo/); // true
  293. * ModuleFilenameHelpers.matchPart("foo.js", [/^foo/, "bar"]); // true
  294. * ModuleFilenameHelpers.matchPart("foo.js", [/^foo/, "bar"]); // true
  295. * ModuleFilenameHelpers.matchPart("foo.js", [/^foo/, /^bar/]); // true
  296. * ModuleFilenameHelpers.matchPart("foo.js", [/^baz/, /^bar/]); // false
  297. * ```
  298. */
  299. const matchPart = (str, test) => {
  300. if (!test) return true;
  301. if (Array.isArray(test)) {
  302. return test.some(test => matchPart(str, test));
  303. }
  304. if (typeof test === "string") {
  305. return str.startsWith(test);
  306. }
  307. return test.test(str);
  308. };
  309. ModuleFilenameHelpers.matchPart = matchPart;
  310. /**
  311. * Tests if a string matches a match object. The match object can have the following properties:
  312. * - `test`: a RegExp or an array of RegExp
  313. * - `include`: a RegExp or an array of RegExp
  314. * - `exclude`: a RegExp or an array of RegExp
  315. *
  316. * The `test` property is tested first, then `include` and then `exclude`.
  317. * @param {MatchObject} obj a match object to test against the string
  318. * @param {string} str string to test against the matching object
  319. * @returns {boolean} true, when the object matches
  320. * @example
  321. * ```js
  322. * ModuleFilenameHelpers.matchObject({ test: "foo.js" }, "foo.js"); // true
  323. * ModuleFilenameHelpers.matchObject({ test: /^foo/ }, "foo.js"); // true
  324. * ModuleFilenameHelpers.matchObject({ test: [/^foo/, "bar"] }, "foo.js"); // true
  325. * ModuleFilenameHelpers.matchObject({ test: [/^foo/, "bar"] }, "baz.js"); // false
  326. * ModuleFilenameHelpers.matchObject({ include: "foo.js" }, "foo.js"); // true
  327. * ModuleFilenameHelpers.matchObject({ include: "foo.js" }, "bar.js"); // false
  328. * ModuleFilenameHelpers.matchObject({ include: /^foo/ }, "foo.js"); // true
  329. * ModuleFilenameHelpers.matchObject({ include: [/^foo/, "bar"] }, "foo.js"); // true
  330. * ModuleFilenameHelpers.matchObject({ include: [/^foo/, "bar"] }, "baz.js"); // false
  331. * ModuleFilenameHelpers.matchObject({ exclude: "foo.js" }, "foo.js"); // false
  332. * ModuleFilenameHelpers.matchObject({ exclude: [/^foo/, "bar"] }, "foo.js"); // false
  333. * ```
  334. */
  335. ModuleFilenameHelpers.matchObject = (obj, str) => {
  336. if (obj.test && !ModuleFilenameHelpers.matchPart(str, obj.test)) {
  337. return false;
  338. }
  339. if (obj.include && !ModuleFilenameHelpers.matchPart(str, obj.include)) {
  340. return false;
  341. }
  342. if (obj.exclude && ModuleFilenameHelpers.matchPart(str, obj.exclude)) {
  343. return false;
  344. }
  345. return true;
  346. };