forked from parcel-bundler/parcel
/
WebExtensionTransformer.js
401 lines (393 loc) Β· 11.6 KB
/
WebExtensionTransformer.js
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
// @flow
import type {MutableAsset} from '@parcel/types';
import {Transformer} from '@parcel/plugin';
import path from 'path';
import jsm from 'json-source-map';
import parseCSP from 'content-security-policy-parser';
import {validateSchema} from '@parcel/utils';
import ThrowableDiagnostic, {
getJSONSourceLocation,
md,
} from '@parcel/diagnostic';
import {glob} from '@parcel/utils';
import {MV3Schema, MV2Schema, VersionSchema} from './schema';
const DEP_LOCS = [
['icons'],
['browser_action', 'default_icon'],
['browser_action', 'default_popup'],
['page_action', 'default_icon'],
['page_action', 'default_popup'],
['action', 'default_icon'],
['action', 'default_popup'],
['background', 'scripts'],
['chrome_url_overrides'],
['devtools_page'],
['options_ui', 'page'],
['sidebar_action', 'default_icon'],
['sidebar_action', 'default_panel'],
['storage', 'managed_schema'],
['theme', 'images', 'theme_frame'],
['theme', 'images', 'additional_backgrounds'],
['user_scripts', 'api_script'],
];
async function collectDependencies(
asset: MutableAsset,
program: any,
ptrs: {[key: string]: any, ...},
hot: boolean,
) {
const fs = asset.fs;
const filePath = asset.filePath;
const assetDir = path.dirname(filePath);
const isMV2 = program.manifest_version == 2;
delete program.$schema;
if (program.default_locale) {
const locales = path.join(assetDir, '_locales');
let err = !(await fs.exists(locales))
? 'key'
: !(await fs.exists(
path.join(locales, program.default_locale, 'messages.json'),
))
? 'value'
: null;
if (err) {
throw new ThrowableDiagnostic({
diagnostic: [
{
message: 'Invalid Web Extension manifest',
origin: '@parcel/transformer-webextension',
codeFrames: [
{
filePath,
codeHighlights: [
{
...getJSONSourceLocation(ptrs['/default_locale'], err),
message: md`Localization ${
err == 'value'
? 'file for ' + program.default_locale
: 'directory'
} does not exist: ${path.relative(
assetDir,
path.join(locales, program.default_locale),
)}`,
},
],
},
],
},
],
});
}
for (const locale of await fs.readdir(locales)) {
if (await fs.exists(path.join(locales, locale, 'messages.json'))) {
asset.addURLDependency(`_locales/${locale}/messages.json`, {
needsStableName: true,
pipeline: 'raw',
});
}
}
}
let needRuntimeBG = false;
if (program.content_scripts) {
for (let i = 0; i < program.content_scripts.length; ++i) {
const sc = program.content_scripts[i];
for (const k of ['css', 'js']) {
const assets = sc[k] || [];
for (let j = 0; j < assets.length; ++j) {
assets[j] = asset.addURLDependency(assets[j], {
// This causes the packager to re-run when these assets update
priority: 'parallel',
bundleBehavior: 'isolated',
loc: {
filePath,
...getJSONSourceLocation(
ptrs[`/content_scripts/${i}/${k}/${j}`],
'value',
),
},
});
}
}
if (hot && sc.js && sc.js.length) {
needRuntimeBG = true;
sc.js.push(
asset.addURLDependency('./runtime/autoreload.js', {
resolveFrom: __filename,
}),
);
}
}
}
if (program.dictionaries) {
for (const dict in program.dictionaries) {
const sourceLoc = getJSONSourceLocation(
ptrs[`/dictionaries/${dict}`],
'value',
);
const loc = {
filePath,
...sourceLoc,
};
const dictFile = program.dictionaries[dict];
if (path.extname(dictFile) != '.dic') {
throw new ThrowableDiagnostic({
diagnostic: [
{
message: 'Invalid Web Extension manifest',
origin: '@parcel/transformer-webextension',
codeFrames: [
{
filePath,
codeHighlights: [
{
...sourceLoc,
message: 'Dictionaries must be .dic files',
},
],
},
],
},
],
});
}
program.dictionaries[dict] = asset.addURLDependency(dictFile, {
needsStableName: true,
loc,
});
asset.addURLDependency(dictFile.slice(0, -4) + '.aff', {
needsStableName: true,
loc,
});
}
}
const browserActionName = isMV2 ? 'browser_action' : 'action';
if (program[browserActionName]?.theme_icons) {
for (let i = 0; i < program[browserActionName].theme_icons.length; ++i) {
const themeIcon = program[browserActionName].theme_icons[i];
for (const k of ['light', 'dark']) {
const loc = getJSONSourceLocation(
ptrs[`/${browserActionName}/theme_icons/${i}/${k}`],
'value',
);
themeIcon[k] = asset.addURLDependency(themeIcon[k], {
loc: {
...loc,
filePath,
},
});
}
}
}
if (program.web_accessible_resources) {
let war = [];
for (let i = 0; i < program.web_accessible_resources.length; ++i) {
// TODO: this doesn't support Parcel resolution
const currentEntry = program.web_accessible_resources[i];
const files = isMV2 ? [currentEntry] : currentEntry.resources;
for (let j = 0; j < files.length; ++j) {
const globFiles = (
await glob(path.join(assetDir, files[j]), fs, {})
).map(fp =>
asset.addURLDependency(path.relative(assetDir, fp), {
priority: 'parallel',
bundleBehavior: 'isolated',
needsStableName: true,
loc: {
filePath,
...getJSONSourceLocation(
ptrs[
`/web_accessible_resources/${i}${
isMV2 ? '' : `/resources/${j}`
}`
],
),
},
}),
);
if (isMV2) {
war = war.concat(globFiles);
} else {
currentEntry.resources = globFiles;
war.push(currentEntry);
}
}
}
program.web_accessible_resources = war;
}
for (const loc of DEP_LOCS) {
const location = '/' + loc.join('/');
if (!ptrs[location]) continue;
let parent: any = program;
for (let i = 0; i < loc.length - 1; ++i) {
parent = parent[loc[i]];
}
const lastLoc = loc[loc.length - 1];
const obj = parent[lastLoc];
if (typeof obj == 'string')
parent[lastLoc] = asset.addURLDependency(obj, {
priority: 'parallel',
bundleBehavior: 'isolated',
loc: {
filePath,
...getJSONSourceLocation(ptrs[location], 'value'),
},
pipeline: path.extname(obj) == '.json' ? 'raw' : undefined,
});
else {
for (const k of Object.keys(obj)) {
obj[k] = asset.addURLDependency(obj[k], {
priority: 'parallel',
bundleBehavior: 'isolated',
loc: {
filePath,
...getJSONSourceLocation(ptrs[location + '/' + k], 'value'),
},
pipeline: path.extname(obj[k]) == '.json' ? 'raw' : undefined,
});
}
}
}
if (isMV2) {
if (program.background?.page) {
program.background.page = asset.addURLDependency(
program.background.page,
{
priority: 'parallel',
bundleBehavior: 'isolated',
loc: {
filePath,
...getJSONSourceLocation(ptrs['/background/page'], 'value'),
},
},
);
if (needRuntimeBG) {
asset.meta.webextBGInsert = program.background.page;
}
}
if (hot) {
// To enable HMR, we must override the CSP to allow 'unsafe-eval'
program.content_security_policy = cspPatchHMR(
program.content_security_policy,
);
if (needRuntimeBG && !program.background?.page) {
if (!program.background) {
program.background = {};
}
if (!program.background.scripts) {
program.background.scripts = [];
}
if (program.background.scripts.length == 0) {
program.background.scripts.push(
asset.addURLDependency('./runtime/default-bg.js', {
resolveFrom: __filename,
}),
);
}
asset.meta.webextBGInsert = program.background.scripts[0];
}
}
} else {
if (program.background?.service_worker) {
program.background.service_worker = asset.addURLDependency(
program.background.service_worker,
{
priority: 'parallel',
bundleBehavior: 'isolated',
loc: {
filePath,
...getJSONSourceLocation(
ptrs['/background/service_worker'],
'value',
),
},
env: {
context: 'service-worker',
sourceType:
program.background.type == 'module' ? 'module' : 'script',
},
},
);
}
if (needRuntimeBG) {
if (!program.background) {
program.background = {};
}
if (!program.background.service_worker) {
program.background.service_worker = asset.addURLDependency(
'./runtime/default-bg.js',
{
resolveFrom: __filename,
env: {context: 'service-worker'},
},
);
}
asset.meta.webextBGInsert = program.background.service_worker;
}
}
}
function cspPatchHMR(policy: ?string) {
if (policy) {
const csp = parseCSP(policy);
policy = '';
if (!csp['script-src']) {
csp['script-src'] = ["'self' 'unsafe-eval' blob: filesystem:"];
}
if (!csp['script-src'].includes("'unsafe-eval'")) {
csp['script-src'].push("'unsafe-eval'");
}
for (const k in csp) {
policy += `${k} ${csp[k].join(' ')};`;
}
return policy;
} else {
return (
"script-src 'self' 'unsafe-eval' blob: filesystem:;" +
"object-src 'self' blob: filesystem:;"
);
}
}
export default (new Transformer({
async transform({asset, options}) {
// Set environment to browser, since web extensions are always used in
// browsers, and because it avoids delegating extra config to the user
asset.setEnvironment({
context: 'browser',
engines: asset.env.engines,
shouldOptimize: asset.env.shouldOptimize,
sourceMap: {
...asset.env.sourceMap,
inline: true,
inlineSources: true,
},
});
const code = await asset.getCode();
const parsed = jsm.parse(code);
const data: any = parsed.data;
// Not using a unified schema dramatically improves error messages
let schema = VersionSchema;
if (data.manifest_version === 3) {
schema = MV3Schema;
} else if (data.manifest_version === 2) {
schema = MV2Schema;
}
validateSchema.diagnostic(
schema,
{
data: data,
source: code,
filePath: asset.filePath,
},
'@parcel/transformer-webextension',
'Invalid Web Extension manifest',
);
await collectDependencies(
asset,
data,
parsed.pointers,
Boolean(options.hmrOptions),
);
asset.setCode(JSON.stringify(data, null, 2));
asset.meta.webextEntry = true;
return [asset];
},
}): Transformer);