-
-
Notifications
You must be signed in to change notification settings - Fork 9.5k
Expand file tree
/
Copy pathTemplatedPathPlugin.js
More file actions
570 lines (522 loc) · 16.2 KB
/
Copy pathTemplatedPathPlugin.js
File metadata and controls
570 lines (522 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Jason Anderson @diurnalist
*/
"use strict";
const { basename, extname } = require("path");
const util = require("util");
const Chunk = require("./Chunk");
const Module = require("./Module");
const { parseResource } = require("./util/identifier");
const memoize = require("./util/memoize");
const getMimeTypes = memoize(() => require("./util/mimeTypes"));
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./Compilation").AssetInfo} AssetInfo */
/** @typedef {import("./Compilation").PathData} PathData */
/** @typedef {import("./Compilation").PathDataChunk} PathDataChunk */
/** @typedef {import("./Compilation").PathDataModule} PathDataModule */
/** @typedef {import("./Compiler")} Compiler */
const REGEXP = /\[\\*([\w:]+)\\*\]/g;
/**
* Placeholder kinds present in a template string, cached so the scan is not
* repeated for reused templates (e.g. `output.filename`, `localIdentName`).
* Bounded so dynamic (function-built) paths can't grow it without limit.
* @type {Map<string, Set<string>>}
*/
const presentKindsCache = new Map();
const PRESENT_KINDS_CACHE_MAX = 1000;
/**
* Returns the placeholder kinds (`[kind]` / `[kind:arg]`) a template references,
* matching the replace pass below so guarding replacer construction by it stays
* output-identical.
* @param {string} path template string (already known to contain `[`)
* @returns {Set<string>} placeholder kinds present
*/
const getPresentKinds = (path) => {
const cached = presentKindsCache.get(path);
if (cached !== undefined) return cached;
/** @type {Set<string>} */
const kinds = new Set();
// `RegExp.exec` loop rather than `String.matchAll` (Node.js 12+) so this
// stays compatible with the supported Node.js 10 range.
REGEXP.lastIndex = 0;
/** @type {RegExpExecArray | null} */
let m;
while ((m = REGEXP.exec(path)) !== null) {
const content = /** @type {string} */ (m[1]);
if (content.length + 2 === m[0].length) {
const cm = /^(\w+)(?::\w+)?$/.exec(content);
if (cm) kinds.add(cm[1]);
}
}
if (presentKindsCache.size >= PRESENT_KINDS_CACHE_MAX) {
presentKindsCache.clear();
}
presentKindsCache.set(path, kinds);
return kinds;
};
/** @type {PathData["prepareId"]} */
const prepareId = (id) => {
if (typeof id !== "string") return id;
if (/^"\s\+*.*\+\s*"$/.test(id)) {
const match = /^"\s\+*\s*(.*)\s*\+\s*"$/.exec(id);
return `" + (${
/** @type {string[]} */ (match)[1]
} + "").replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_") + "`;
}
return id.replace(/(^[.-]|[^a-z0-9_-])+/gi, "_");
};
/**
* Defines the replacer function callback.
* @callback ReplacerFunction
* @param {string} match
* @param {string | undefined} arg
* @param {string} input
*/
/**
* Returns hash replacer function.
* @param {ReplacerFunction} replacer replacer
* @param {((arg0: number) => string) | undefined} handler handler
* @param {AssetInfo | undefined} assetInfo asset info
* @param {string} hashName hash name
* @returns {Replacer} hash replacer function
*/
const hashLength = (replacer, handler, assetInfo, hashName) => {
/** @type {Replacer} */
const fn = (match, arg, input) => {
/** @type {string} */
let result;
const length = arg && Number.parseInt(arg, 10);
if (length && handler) {
result = handler(length);
} else {
const hash = replacer(match, arg, input);
result = length ? hash.slice(0, length) : hash;
}
if (assetInfo) {
assetInfo.immutable = true;
if (Array.isArray(assetInfo[hashName])) {
assetInfo[hashName] = [...assetInfo[hashName], result];
} else if (assetInfo[hashName]) {
assetInfo[hashName] = [assetInfo[hashName], result];
} else {
assetInfo[hashName] = result;
}
}
return result;
};
return fn;
};
/** @typedef {(match: string, arg: string | undefined, input: string) => string} Replacer */
/**
* Returns replacer.
* @param {string | number | null | undefined | (() => string | number | null | undefined)} value value
* @param {boolean=} allowEmpty allow empty
* @returns {Replacer} replacer
*/
const replacer = (value, allowEmpty) => {
/** @type {Replacer} */
const fn = (match, arg, input) => {
if (typeof value === "function") {
value = value();
}
if (value === null || value === undefined) {
if (!allowEmpty) {
throw new Error(
`Path variable ${match} not implemented in this context: ${input}`
);
}
return "";
}
return `${value}`;
};
return fn;
};
/** @type {Map<string, (...args: EXPECTED_ANY[]) => EXPECTED_ANY>} */
const deprecationCache = new Map();
const deprecatedFunction = (() => () => {})();
/**
* Returns function with deprecation output.
* @template {(...args: EXPECTED_ANY[]) => EXPECTED_ANY} T
* @param {T} fn function
* @param {string} message message
* @param {string} code code
* @returns {T} function with deprecation output
*/
const deprecated = (fn, message, code) => {
let d = deprecationCache.get(message);
if (d === undefined) {
d = util.deprecate(deprecatedFunction, message, code);
deprecationCache.set(message, d);
}
return /** @type {T} */ (
(...args) => {
d();
return fn(...args);
}
);
};
/**
* Callback used to compute a path from contextual data. The type parameter
* narrows the `pathData` shape when the caller knows it operates in a chunk
* (`PathDataChunk`) or module (`PathDataModule`) context — defaults to the
* fully-optional `PathData` for backward compatibility.
* @template {PathData} [T=PathData]
* @typedef {(pathData: T, assetInfo?: AssetInfo) => string} TemplatePathFn
*/
/**
* Either a raw template string (e.g. `"[name].[contenthash].js"`) or a
* generic `TemplatePathFn`. Method signatures that need to thread a narrowed
* `PathData` shape spell the function side out as `TemplatePathFn<T>`
* directly — `TemplatePath` itself stays a plain alias so local JSDoc
* re-imports keep a single shared identity.
* @typedef {string | TemplatePathFn} TemplatePath
*/
/**
* Returns the interpolated path.
* @template {PathData} [T=PathData]
* @param {string | TemplatePathFn<T>} path the raw path
* @param {T} data context data
* @param {AssetInfo=} assetInfo extra info about the asset (will be written to)
* @returns {string} the interpolated path
*/
const interpolate = (path, data, assetInfo) => {
if (typeof path === "function") {
path = path(data, assetInfo);
}
// Literal paths carry no `[placeholder]`, so the whole replacement table
// and regex pass are pure overhead — building replacers has no side effects
// (those only fire when a replacer is invoked), so the output is identical.
if (!path.includes("[")) {
return path;
}
// Only build replacers for placeholders the template actually uses — most
// templates reference a handful, so building the whole table per call is
// wasted work. Replacer construction has no side effects (those fire only
// when a replacer is invoked, which happens for present kinds), so this is
// output-identical.
const presentKinds = getPresentKinds(path);
const chunkGraph = data.chunkGraph;
/** @type {Map<string, Replacer>} */
const replacements = new Map();
// Filename context
//
// Placeholders
//
// for /some/path/file.js?query#fragment:
// [file] - /some/path/file.js
// [query] - ?query
// [fragment] - #fragment
// [base] - file.js
// [path] - /some/path/
// [name] - file
// [ext] - .js
if (
typeof data.filename === "string" &&
(presentKinds.has("file") ||
presentKinds.has("query") ||
presentKinds.has("fragment") ||
presentKinds.has("path") ||
presentKinds.has("base") ||
presentKinds.has("name") ||
presentKinds.has("ext") ||
presentKinds.has("filebase"))
) {
// check that filename is data uri
const match = data.filename.match(/^data:([^;,]+)/);
if (match) {
const ext = getMimeTypes().extension(match[1]);
const emptyReplacer = replacer("", true);
// "XXXX" used for `updateHash`, so we don't need it here
const contentHash =
data.contentHash && !/X+/.test(data.contentHash)
? data.contentHash
: false;
const baseReplacer = contentHash ? replacer(contentHash) : emptyReplacer;
if (presentKinds.has("file")) replacements.set("file", emptyReplacer);
if (presentKinds.has("query")) replacements.set("query", emptyReplacer);
if (presentKinds.has("fragment")) {
replacements.set("fragment", emptyReplacer);
}
if (presentKinds.has("path")) replacements.set("path", emptyReplacer);
if (presentKinds.has("base")) replacements.set("base", baseReplacer);
if (presentKinds.has("name")) replacements.set("name", baseReplacer);
if (presentKinds.has("ext")) {
replacements.set("ext", replacer(ext ? `.${ext}` : "", true));
}
// Legacy
if (presentKinds.has("filebase")) {
replacements.set(
"filebase",
deprecated(
baseReplacer,
"[filebase] is now [base]",
"DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_FILENAME"
)
);
}
} else {
const { path: file, query, fragment } = parseResource(data.filename);
const ext = extname(file);
const base = basename(file);
const name = base.slice(0, base.length - ext.length);
const path = file.slice(0, file.length - base.length);
if (presentKinds.has("file")) replacements.set("file", replacer(file));
if (presentKinds.has("query")) {
replacements.set("query", replacer(query, true));
}
if (presentKinds.has("fragment")) {
replacements.set("fragment", replacer(fragment, true));
}
if (presentKinds.has("path")) {
replacements.set("path", replacer(path, true));
}
if (presentKinds.has("base")) replacements.set("base", replacer(base));
if (presentKinds.has("name")) replacements.set("name", replacer(name));
if (presentKinds.has("ext")) replacements.set("ext", replacer(ext, true));
// Legacy
if (presentKinds.has("filebase")) {
replacements.set(
"filebase",
deprecated(
replacer(base),
"[filebase] is now [base]",
"DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_FILENAME"
)
);
}
}
}
// Compilation context
//
// Placeholders
//
// [fullhash] - data.hash (3a4b5c6e7f)
//
// Legacy Placeholders
//
// [hash] - data.hash (3a4b5c6e7f)
if (data.hash && (presentKinds.has("fullhash") || presentKinds.has("hash"))) {
const hashReplacer = hashLength(
replacer(data.hash),
data.hashWithLength,
assetInfo,
"fullhash"
);
if (presentKinds.has("fullhash")) {
replacements.set("fullhash", hashReplacer);
}
// Legacy
if (presentKinds.has("hash")) {
replacements.set(
"hash",
deprecated(
hashReplacer,
"[hash] is now [fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details)",
"DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_HASH"
)
);
}
}
// Chunk Context
//
// Placeholders
//
// [id] - chunk.id (0.js)
// [name] - chunk.name (app.js)
// [chunkhash] - chunk.hash (7823t4t4.js)
// [contenthash] - chunk.contentHash[type] (3256u3zg.js)
if (data.chunk) {
const chunk = data.chunk;
const contentHashType = data.contentHashType;
if (presentKinds.has("id")) replacements.set("id", replacer(chunk.id));
if (presentKinds.has("name")) {
replacements.set("name", replacer(chunk.name || chunk.id));
}
if (presentKinds.has("chunkhash")) {
replacements.set(
"chunkhash",
hashLength(
replacer(chunk instanceof Chunk ? chunk.renderedHash : chunk.hash),
"hashWithLength" in chunk ? chunk.hashWithLength : undefined,
assetInfo,
"chunkhash"
)
);
}
if (presentKinds.has("contenthash")) {
replacements.set(
"contenthash",
hashLength(
replacer(
data.contentHash ||
(contentHashType &&
chunk.contentHash &&
chunk.contentHash[contentHashType])
),
data.contentHashWithLength ||
("contentHashWithLength" in chunk && chunk.contentHashWithLength
? chunk.contentHashWithLength[
/** @type {string} */ (contentHashType)
]
: undefined),
assetInfo,
"contenthash"
)
);
}
}
// Module Context
//
// Placeholders
//
// [id] - module.id (2.png)
// [hash] - module.hash (6237543873.png)
//
// Legacy Placeholders
//
// [moduleid] - module.id (2.png)
// [modulehash] - module.hash (6237543873.png)
if (data.module) {
const module = data.module;
const needId = presentKinds.has("id");
const needModuleId = presentKinds.has("moduleid");
const needHash = presentKinds.has("hash");
if (needId || needModuleId) {
const idReplacer = replacer(() =>
(data.prepareId || prepareId)(
module instanceof Module
? /** @type {ModuleId} */
(/** @type {ChunkGraph} */ (chunkGraph).getModuleId(module))
: module.id
)
);
if (needId) replacements.set("id", idReplacer);
// Legacy
if (needModuleId) {
replacements.set(
"moduleid",
deprecated(
idReplacer,
"[moduleid] is now [id]",
"DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_MODULE_ID"
)
);
}
}
// `[hash]` aliases module content hash when present, else module hash.
const wantModuleHash =
presentKinds.has("modulehash") || (needHash && !data.contentHash);
const wantContentHash =
presentKinds.has("contenthash") || (needHash && data.contentHash);
/** @type {Replacer | undefined} */
let moduleHashReplacer;
/** @type {Replacer | undefined} */
let contentHashReplacer;
if (wantModuleHash) {
moduleHashReplacer = hashLength(
replacer(() =>
module instanceof Module
? /** @type {ChunkGraph} */
(chunkGraph).getRenderedModuleHash(module, data.runtime)
: module.hash
),
"hashWithLength" in module ? module.hashWithLength : undefined,
assetInfo,
"modulehash"
);
if (presentKinds.has("modulehash")) {
replacements.set("modulehash", moduleHashReplacer);
}
}
if (wantContentHash) {
contentHashReplacer = hashLength(
replacer(/** @type {string} */ (data.contentHash)),
undefined,
assetInfo,
"contenthash"
);
if (presentKinds.has("contenthash")) {
replacements.set("contenthash", contentHashReplacer);
}
}
if (needHash) {
replacements.set(
"hash",
/** @type {Replacer} */
(data.contentHash ? contentHashReplacer : moduleHashReplacer)
);
}
}
// Other things
//
// Placeholders
//
// [url] - data.url
// [uniqueName] - data.uniqueName (output.uniqueName)
// [uniquename] - alias of [uniqueName]
if (data.url && presentKinds.has("url")) {
replacements.set("url", replacer(data.url));
}
if (
data.uniqueName !== undefined &&
(presentKinds.has("uniqueName") || presentKinds.has("uniquename"))
) {
const uniqueNameReplacer = replacer(data.uniqueName);
if (presentKinds.has("uniqueName")) {
replacements.set("uniqueName", uniqueNameReplacer);
}
if (presentKinds.has("uniquename")) {
replacements.set("uniquename", uniqueNameReplacer);
}
}
if (presentKinds.has("runtime")) {
if (typeof data.runtime === "string") {
replacements.set(
"runtime",
replacer(() =>
(data.prepareId || prepareId)(/** @type {string} */ (data.runtime))
)
);
} else {
replacements.set("runtime", replacer("_"));
}
}
path = path.replace(REGEXP, (match, content) => {
if (content.length + 2 === match.length) {
const contentMatch = /^(\w+)(?::(\w+))?$/.exec(content);
if (!contentMatch) return match;
const [, kind, arg] = contentMatch;
const replacer = replacements.get(kind);
if (replacer !== undefined) {
return replacer(match, arg, /** @type {string} */ (path));
}
} else if (match.startsWith("[\\") && match.endsWith("\\]")) {
return `[${match.slice(2, -2)}]`;
}
return match;
});
return path;
};
const plugin = "TemplatedPathPlugin";
class TemplatedPathPlugin {
/**
* Applies the plugin by registering its hooks on the compiler.
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(plugin, (compilation) => {
compilation.hooks.assetPath.tap(plugin, (path, data, assetInfo) => {
// Default from output options so `[uniqueName]` resolves in every template
if (data.uniqueName === undefined) {
data.uniqueName = compilation.outputOptions.uniqueName;
}
return interpolate(path, data, assetInfo);
});
});
}
}
module.exports = TemplatedPathPlugin;
module.exports.interpolate = interpolate;