1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | const errors = require('./errors');
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | const escapeRegExp = (string) => {
|
26 | return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
27 | };
|
28 |
|
29 | module.exports = (modifyURLPrefix) => {
|
30 | if (!modifyURLPrefix ||
|
31 | typeof modifyURLPrefix !== 'object' ||
|
32 | Array.isArray(modifyURLPrefix)) {
|
33 | throw new Error(errors['modify-url-prefix-bad-prefixes']);
|
34 | }
|
35 |
|
36 |
|
37 |
|
38 | if (Object.keys(modifyURLPrefix).length === 0) {
|
39 | return (entry) => entry;
|
40 | }
|
41 |
|
42 | Object.keys(modifyURLPrefix).forEach((key) => {
|
43 | if (typeof modifyURLPrefix[key] !== 'string') {
|
44 | throw new Error(errors['modify-url-prefix-bad-prefixes']);
|
45 | }
|
46 | });
|
47 |
|
48 |
|
49 | const safeModifyURLPrefixes = Object.keys(modifyURLPrefix).map(escapeRegExp);
|
50 |
|
51 | const prefixMatchesStrings = safeModifyURLPrefixes.join('|');
|
52 |
|
53 |
|
54 | const modifyRegex = new RegExp(`^(${prefixMatchesStrings})`);
|
55 |
|
56 | return (originalManifest) => {
|
57 | const manifest = originalManifest.map((entry) => {
|
58 | if (typeof entry.url !== 'string') {
|
59 | throw new Error(errors['manifest-entry-bad-url']);
|
60 | }
|
61 |
|
62 | entry.url = entry.url.replace(modifyRegex, (match) => {
|
63 | return modifyURLPrefix[match];
|
64 | });
|
65 |
|
66 | return entry;
|
67 | });
|
68 |
|
69 | return {manifest};
|
70 | };
|
71 | };
|