TemplatedPathPlugin.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Jason Anderson @diurnalist
  4. */
  5. "use strict";
  6. const mime = require("mime-types");
  7. const { basename, extname } = require("path");
  8. const util = require("util");
  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:]+)\\*\]/gi;
  18. /**
  19. * @param {string | number} id id
  20. * @returns {string | number} result
  21. */
  22. const prepareId = id => {
  23. if (typeof id !== "string") return id;
  24. if (/^"\s\+*.*\+\s*"$/.test(id)) {
  25. const match = /^"\s\+*\s*(.*)\s*\+\s*"$/.exec(id);
  26. return `" + (${
  27. /** @type {string[]} */ (match)[1]
  28. } + "").replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_") + "`;
  29. }
  30. return id.replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_");
  31. };
  32. /**
  33. * @callback ReplacerFunction
  34. * @param {string} match
  35. * @param {string | undefined} arg
  36. * @param {string} input
  37. */
  38. /**
  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. let result;
  49. const length = arg && Number.parseInt(arg, 10);
  50. if (length && handler) {
  51. result = handler(length);
  52. } else {
  53. const hash = replacer(match, arg, input);
  54. result = length ? hash.slice(0, length) : hash;
  55. }
  56. if (assetInfo) {
  57. assetInfo.immutable = true;
  58. if (Array.isArray(assetInfo[hashName])) {
  59. assetInfo[hashName] = [...assetInfo[hashName], result];
  60. } else if (assetInfo[hashName]) {
  61. assetInfo[hashName] = [assetInfo[hashName], result];
  62. } else {
  63. assetInfo[hashName] = result;
  64. }
  65. }
  66. return result;
  67. };
  68. return fn;
  69. };
  70. /** @typedef {(match: string, arg: string | undefined, input: string) => string} Replacer */
  71. /**
  72. * @param {string | number | null | undefined | (() => string | number | null | undefined)} value value
  73. * @param {boolean=} allowEmpty allow empty
  74. * @returns {Replacer} replacer
  75. */
  76. const replacer = (value, allowEmpty) => {
  77. /** @type {Replacer} */
  78. const fn = (match, arg, input) => {
  79. if (typeof value === "function") {
  80. value = value();
  81. }
  82. if (value === null || value === undefined) {
  83. if (!allowEmpty) {
  84. throw new Error(
  85. `Path variable ${match} not implemented in this context: ${input}`
  86. );
  87. }
  88. return "";
  89. }
  90. return `${value}`;
  91. };
  92. return fn;
  93. };
  94. const deprecationCache = new Map();
  95. const deprecatedFunction = (() => () => {})();
  96. /**
  97. * @template {(...args: EXPECTED_ANY[]) => EXPECTED_ANY} T
  98. * @param {T} fn function
  99. * @param {string} message message
  100. * @param {string} code code
  101. * @returns {T} function with deprecation output
  102. */
  103. const deprecated = (fn, message, code) => {
  104. let d = deprecationCache.get(message);
  105. if (d === undefined) {
  106. d = util.deprecate(deprecatedFunction, message, code);
  107. deprecationCache.set(message, d);
  108. }
  109. return /** @type {T} */ (
  110. (...args) => {
  111. d();
  112. return fn(...args);
  113. }
  114. );
  115. };
  116. /** @typedef {string | ((pathData: PathData, assetInfo?: AssetInfo) => string)} 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. 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(() => prepareId(/** @type {string} */ (data.runtime)))
  319. );
  320. } else {
  321. replacements.set("runtime", replacer("_"));
  322. }
  323. if (typeof path === "function") {
  324. path = path(data, assetInfo);
  325. }
  326. path = path.replace(REGEXP, (match, content) => {
  327. if (content.length + 2 === match.length) {
  328. const contentMatch = /^(\w+)(?::(\w+))?$/.exec(content);
  329. if (!contentMatch) return match;
  330. const [, kind, arg] = contentMatch;
  331. const replacer = replacements.get(kind);
  332. if (replacer !== undefined) {
  333. return replacer(match, arg, /** @type {string} */ (path));
  334. }
  335. } else if (match.startsWith("[\\") && match.endsWith("\\]")) {
  336. return `[${match.slice(2, -2)}]`;
  337. }
  338. return match;
  339. });
  340. return path;
  341. };
  342. const plugin = "TemplatedPathPlugin";
  343. class TemplatedPathPlugin {
  344. /**
  345. * Apply the plugin
  346. * @param {Compiler} compiler the compiler instance
  347. * @returns {void}
  348. */
  349. apply(compiler) {
  350. compiler.hooks.compilation.tap(plugin, compilation => {
  351. compilation.hooks.assetPath.tap(plugin, replacePathVariables);
  352. });
  353. }
  354. }
  355. module.exports = TemplatedPathPlugin;