TemplatedPathPlugin.js 10 KB

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