TemplatedPathPlugin.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Jason Anderson @diurnalist
  4. */
  5. "use strict";
  6. const { basename, extname } = require("path");
  7. const util = require("util");
  8. const Chunk = require("./Chunk");
  9. const Module = require("./Module");
  10. const { parseResource } = require("./util/identifier");
  11. const memoize = require("./util/memoize");
  12. const getMimeTypes = memoize(() => require("./util/mimeTypes"));
  13. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  14. /** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
  15. /** @typedef {import("./Compilation").AssetInfo} AssetInfo */
  16. /** @typedef {import("./Compilation").PathData} PathData */
  17. /** @typedef {import("./Compiler")} Compiler */
  18. const REGEXP = /\[\\*([\w:]+)\\*\]/g;
  19. /** @type {PathData["prepareId"]} */
  20. const prepareId = (id) => {
  21. if (typeof id !== "string") return id;
  22. if (/^"\s\+*.*\+\s*"$/.test(id)) {
  23. const match = /^"\s\+*\s*(.*)\s*\+\s*"$/.exec(id);
  24. return `" + (${
  25. /** @type {string[]} */ (match)[1]
  26. } + "").replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_") + "`;
  27. }
  28. return id.replace(/(^[.-]|[^a-z0-9_-])+/gi, "_");
  29. };
  30. /**
  31. * Defines the replacer function callback.
  32. * @callback ReplacerFunction
  33. * @param {string} match
  34. * @param {string | undefined} arg
  35. * @param {string} input
  36. */
  37. /**
  38. * Returns hash replacer function.
  39. * @param {ReplacerFunction} replacer replacer
  40. * @param {((arg0: number) => string) | undefined} handler handler
  41. * @param {AssetInfo | undefined} assetInfo asset info
  42. * @param {string} hashName hash name
  43. * @returns {Replacer} hash replacer function
  44. */
  45. const hashLength = (replacer, handler, assetInfo, hashName) => {
  46. /** @type {Replacer} */
  47. const fn = (match, arg, input) => {
  48. /** @type {string} */
  49. let result;
  50. const length = arg && Number.parseInt(arg, 10);
  51. if (length && handler) {
  52. result = handler(length);
  53. } else {
  54. const hash = replacer(match, arg, input);
  55. result = length ? hash.slice(0, length) : hash;
  56. }
  57. if (assetInfo) {
  58. assetInfo.immutable = true;
  59. if (Array.isArray(assetInfo[hashName])) {
  60. assetInfo[hashName] = [...assetInfo[hashName], result];
  61. } else if (assetInfo[hashName]) {
  62. assetInfo[hashName] = [assetInfo[hashName], result];
  63. } else {
  64. assetInfo[hashName] = result;
  65. }
  66. }
  67. return result;
  68. };
  69. return fn;
  70. };
  71. /** @typedef {(match: string, arg: string | undefined, input: string) => string} Replacer */
  72. /**
  73. * Returns replacer.
  74. * @param {string | number | null | undefined | (() => string | number | null | undefined)} value value
  75. * @param {boolean=} allowEmpty allow empty
  76. * @returns {Replacer} replacer
  77. */
  78. const replacer = (value, allowEmpty) => {
  79. /** @type {Replacer} */
  80. const fn = (match, arg, input) => {
  81. if (typeof value === "function") {
  82. value = value();
  83. }
  84. if (value === null || value === undefined) {
  85. if (!allowEmpty) {
  86. throw new Error(
  87. `Path variable ${match} not implemented in this context: ${input}`
  88. );
  89. }
  90. return "";
  91. }
  92. return `${value}`;
  93. };
  94. return fn;
  95. };
  96. /** @type {Map<string, (...args: EXPECTED_ANY[]) => EXPECTED_ANY>} */
  97. const deprecationCache = new Map();
  98. const deprecatedFunction = (() => () => {})();
  99. /**
  100. * Returns function with deprecation output.
  101. * @template {(...args: EXPECTED_ANY[]) => EXPECTED_ANY} T
  102. * @param {T} fn function
  103. * @param {string} message message
  104. * @param {string} code code
  105. * @returns {T} function with deprecation output
  106. */
  107. const deprecated = (fn, message, code) => {
  108. let d = deprecationCache.get(message);
  109. if (d === undefined) {
  110. d = util.deprecate(deprecatedFunction, message, code);
  111. deprecationCache.set(message, d);
  112. }
  113. return /** @type {T} */ (
  114. (...args) => {
  115. d();
  116. return fn(...args);
  117. }
  118. );
  119. };
  120. /** @typedef {(pathData: PathData, assetInfo?: AssetInfo) => string} TemplatePathFn */
  121. /** @typedef {string | TemplatePathFn} TemplatePath */
  122. /**
  123. * Returns the interpolated path.
  124. * @param {TemplatePath} path the raw path
  125. * @param {PathData} data context data
  126. * @param {AssetInfo=} assetInfo extra info about the asset (will be written to)
  127. * @returns {string} the interpolated path
  128. */
  129. const interpolate = (path, data, assetInfo) => {
  130. const chunkGraph = data.chunkGraph;
  131. /** @type {Map<string, Replacer>} */
  132. const replacements = new Map();
  133. // Filename context
  134. //
  135. // Placeholders
  136. //
  137. // for /some/path/file.js?query#fragment:
  138. // [file] - /some/path/file.js
  139. // [query] - ?query
  140. // [fragment] - #fragment
  141. // [base] - file.js
  142. // [path] - /some/path/
  143. // [name] - file
  144. // [ext] - .js
  145. if (typeof data.filename === "string") {
  146. // check that filename is data uri
  147. const match = data.filename.match(/^data:([^;,]+)/);
  148. if (match) {
  149. const ext = getMimeTypes().extension(match[1]);
  150. const emptyReplacer = replacer("", true);
  151. // "XXXX" used for `updateHash`, so we don't need it here
  152. const contentHash =
  153. data.contentHash && !/X+/.test(data.contentHash)
  154. ? data.contentHash
  155. : false;
  156. const baseReplacer = contentHash ? replacer(contentHash) : emptyReplacer;
  157. replacements.set("file", emptyReplacer);
  158. replacements.set("query", emptyReplacer);
  159. replacements.set("fragment", emptyReplacer);
  160. replacements.set("path", emptyReplacer);
  161. replacements.set("base", baseReplacer);
  162. replacements.set("name", baseReplacer);
  163. replacements.set("ext", replacer(ext ? `.${ext}` : "", true));
  164. // Legacy
  165. replacements.set(
  166. "filebase",
  167. deprecated(
  168. baseReplacer,
  169. "[filebase] is now [base]",
  170. "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_FILENAME"
  171. )
  172. );
  173. } else {
  174. const { path: file, query, fragment } = parseResource(data.filename);
  175. const ext = extname(file);
  176. const base = basename(file);
  177. const name = base.slice(0, base.length - ext.length);
  178. const path = file.slice(0, file.length - base.length);
  179. replacements.set("file", replacer(file));
  180. replacements.set("query", replacer(query, true));
  181. replacements.set("fragment", replacer(fragment, true));
  182. replacements.set("path", replacer(path, true));
  183. replacements.set("base", replacer(base));
  184. replacements.set("name", replacer(name));
  185. replacements.set("ext", replacer(ext, true));
  186. // Legacy
  187. replacements.set(
  188. "filebase",
  189. deprecated(
  190. replacer(base),
  191. "[filebase] is now [base]",
  192. "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_FILENAME"
  193. )
  194. );
  195. }
  196. }
  197. // Compilation context
  198. //
  199. // Placeholders
  200. //
  201. // [fullhash] - data.hash (3a4b5c6e7f)
  202. //
  203. // Legacy Placeholders
  204. //
  205. // [hash] - data.hash (3a4b5c6e7f)
  206. if (data.hash) {
  207. const hashReplacer = hashLength(
  208. replacer(data.hash),
  209. data.hashWithLength,
  210. assetInfo,
  211. "fullhash"
  212. );
  213. replacements.set("fullhash", hashReplacer);
  214. // Legacy
  215. replacements.set(
  216. "hash",
  217. deprecated(
  218. hashReplacer,
  219. "[hash] is now [fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details)",
  220. "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_HASH"
  221. )
  222. );
  223. }
  224. // Chunk Context
  225. //
  226. // Placeholders
  227. //
  228. // [id] - chunk.id (0.js)
  229. // [name] - chunk.name (app.js)
  230. // [chunkhash] - chunk.hash (7823t4t4.js)
  231. // [contenthash] - chunk.contentHash[type] (3256u3zg.js)
  232. if (data.chunk) {
  233. const chunk = data.chunk;
  234. const contentHashType = data.contentHashType;
  235. const idReplacer = replacer(chunk.id);
  236. const nameReplacer = replacer(chunk.name || chunk.id);
  237. const chunkhashReplacer = hashLength(
  238. replacer(chunk instanceof Chunk ? chunk.renderedHash : chunk.hash),
  239. "hashWithLength" in chunk ? chunk.hashWithLength : undefined,
  240. assetInfo,
  241. "chunkhash"
  242. );
  243. const contenthashReplacer = hashLength(
  244. replacer(
  245. data.contentHash ||
  246. (contentHashType &&
  247. chunk.contentHash &&
  248. chunk.contentHash[contentHashType])
  249. ),
  250. data.contentHashWithLength ||
  251. ("contentHashWithLength" in chunk && chunk.contentHashWithLength
  252. ? chunk.contentHashWithLength[/** @type {string} */ (contentHashType)]
  253. : undefined),
  254. assetInfo,
  255. "contenthash"
  256. );
  257. replacements.set("id", idReplacer);
  258. replacements.set("name", nameReplacer);
  259. replacements.set("chunkhash", chunkhashReplacer);
  260. replacements.set("contenthash", contenthashReplacer);
  261. }
  262. // Module Context
  263. //
  264. // Placeholders
  265. //
  266. // [id] - module.id (2.png)
  267. // [hash] - module.hash (6237543873.png)
  268. //
  269. // Legacy Placeholders
  270. //
  271. // [moduleid] - module.id (2.png)
  272. // [modulehash] - module.hash (6237543873.png)
  273. if (data.module) {
  274. const module = data.module;
  275. const idReplacer = replacer(() =>
  276. (data.prepareId || prepareId)(
  277. module instanceof Module
  278. ? /** @type {ModuleId} */
  279. (/** @type {ChunkGraph} */ (chunkGraph).getModuleId(module))
  280. : module.id
  281. )
  282. );
  283. const moduleHashReplacer = hashLength(
  284. replacer(() =>
  285. module instanceof Module
  286. ? /** @type {ChunkGraph} */
  287. (chunkGraph).getRenderedModuleHash(module, data.runtime)
  288. : module.hash
  289. ),
  290. "hashWithLength" in module ? module.hashWithLength : undefined,
  291. assetInfo,
  292. "modulehash"
  293. );
  294. const contentHashReplacer = hashLength(
  295. replacer(/** @type {string} */ (data.contentHash)),
  296. undefined,
  297. assetInfo,
  298. "contenthash"
  299. );
  300. replacements.set("id", idReplacer);
  301. replacements.set("modulehash", moduleHashReplacer);
  302. replacements.set("contenthash", contentHashReplacer);
  303. replacements.set(
  304. "hash",
  305. data.contentHash ? contentHashReplacer : moduleHashReplacer
  306. );
  307. // Legacy
  308. replacements.set(
  309. "moduleid",
  310. deprecated(
  311. idReplacer,
  312. "[moduleid] is now [id]",
  313. "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_MODULE_ID"
  314. )
  315. );
  316. }
  317. // Other things
  318. if (data.url) {
  319. replacements.set("url", replacer(data.url));
  320. }
  321. if (typeof data.runtime === "string") {
  322. replacements.set(
  323. "runtime",
  324. replacer(() =>
  325. (data.prepareId || prepareId)(/** @type {string} */ (data.runtime))
  326. )
  327. );
  328. } else {
  329. replacements.set("runtime", replacer("_"));
  330. }
  331. if (typeof path === "function") {
  332. path = path(data, assetInfo);
  333. }
  334. path = path.replace(REGEXP, (match, content) => {
  335. if (content.length + 2 === match.length) {
  336. const contentMatch = /^(\w+)(?::(\w+))?$/.exec(content);
  337. if (!contentMatch) return match;
  338. const [, kind, arg] = contentMatch;
  339. const replacer = replacements.get(kind);
  340. if (replacer !== undefined) {
  341. return replacer(match, arg, /** @type {string} */ (path));
  342. }
  343. } else if (match.startsWith("[\\") && match.endsWith("\\]")) {
  344. return `[${match.slice(2, -2)}]`;
  345. }
  346. return match;
  347. });
  348. return path;
  349. };
  350. const plugin = "TemplatedPathPlugin";
  351. class TemplatedPathPlugin {
  352. /**
  353. * Applies the plugin by registering its hooks on the compiler.
  354. * @param {Compiler} compiler the compiler instance
  355. * @returns {void}
  356. */
  357. apply(compiler) {
  358. compiler.hooks.compilation.tap(plugin, (compilation) => {
  359. compilation.hooks.assetPath.tap(plugin, interpolate);
  360. });
  361. }
  362. }
  363. module.exports = TemplatedPathPlugin;
  364. module.exports.interpolate = interpolate;