-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
scripts.js
1267 lines (1190 loc) · 38.3 KB
/
scripts.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
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// TODO(ritave): Remove switches on hardcoded build types
const { callbackify } = require('util');
const path = require('path');
const { writeFileSync, readFileSync, unlinkSync } = require('fs');
const EventEmitter = require('events');
const gulp = require('gulp');
const watch = require('gulp-watch');
const Vinyl = require('vinyl');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const log = require('fancy-log');
const browserify = require('browserify');
const watchify = require('watchify');
const babelify = require('babelify');
const envify = require('loose-envify/custom');
const sourcemaps = require('gulp-sourcemaps');
const applySourceMap = require('vinyl-sourcemaps-apply');
const pify = require('pify');
const through = require('through2');
const finished = pify(require('readable-stream').finished);
const labeledStreamSplicer = require('labeled-stream-splicer').obj;
const wrapInStream = require('pumpify').obj;
const { Eta } = require('eta');
const lavapack = require('@lavamoat/lavapack');
const lavamoatBrowserify = require('lavamoat-browserify');
const terser = require('terser');
const bifyModuleGroups = require('bify-module-groups');
const { streamFlatMap } = require('../stream-flat-map');
const { isManifestV3 } = require('../../shared/modules/mv3.utils');
const { setEnvironmentVariables } = require('./set-environment-variables');
const { BUILD_TARGETS } = require('./constants');
const { getConfig } = require('./config');
const {
isDevBuild,
isTestBuild,
getEnvironment,
logError,
wrapAgainstScuttling,
getBuildName,
makeSelfInjecting,
} = require('./utils');
const {
createTask,
composeParallel,
composeSeries,
runInChildProcess,
} = require('./task');
const {
createRemoveFencedCodeTransform,
} = require('./transforms/remove-fenced-code');
// map dist files to bag of needed native APIs against LM scuttling
const scuttlingConfigBase = {
'scripts/sentry-install.js': {
// globals sentry need to function
window: '',
navigator: '',
location: '',
Uint16Array: '',
fetch: '',
String: '',
Math: '',
Object: '',
Symbol: '',
Function: '',
Array: '',
Boolean: '',
Number: '',
Request: '',
Date: '',
JSON: '',
encodeURIComponent: '',
console: '',
crypto: '',
Map: '',
isFinite: '',
// {clear/set}Timeout are "this sensitive"
clearTimeout: 'window',
setTimeout: 'window',
// sentry special props
__SENTRY__: '',
sentryHooks: '',
sentry: '',
appState: '',
extra: '',
stateHooks: '',
nw: '',
// Sentry Auto Session Tracking
document: '',
history: '',
isNaN: '',
parseInt: '',
},
};
const mv3ScuttlingConfig = { ...scuttlingConfigBase };
const standardScuttlingConfig = { ...scuttlingConfigBase };
const noopWriteStream = through.obj((_file, _fileEncoding, callback) =>
callback(),
);
module.exports = createScriptTasks;
/**
* Create tasks for building JavaScript bundles and templates. One
* task is returned for each build target. These build target tasks are
* each composed of smaller tasks.
*
* @param {object} options - Build options.
* @param {boolean} options.applyLavaMoat - Whether the build should use
* LavaMoat at runtime or not.
* @param {string[]} options.browserPlatforms - A list of browser platforms to
* build bundles for.
* @param {string} options.buildType - The current build type (e.g. "main",
* "flask", etc.).
* @param {string[] | null} options.ignoredFiles - A list of files to exclude
* from the current build.
* @param {boolean} options.isLavaMoat - Whether this build script is being run
* using LavaMoat or not.
* @param {object} options.livereload - The "gulp-livereload" server instance.
* @param {boolean} options.policyOnly - Whether to stop the build after
* generating the LavaMoat policy, skipping any writes to disk other than the
* LavaMoat policy itself.
* @param {boolean} options.shouldLintFenceFiles - Whether files with code
* fences should be linted after fences have been removed.
* @param {string} options.version - The current version of the extension.
* @param options.shouldIncludeSnow - Whether the build should use
* Snow at runtime or not.
* @returns {object} A set of tasks, one for each build target.
*/
function createScriptTasks({
shouldIncludeSnow,
applyLavaMoat,
browserPlatforms,
buildType,
ignoredFiles,
isLavaMoat,
livereload,
policyOnly,
shouldLintFenceFiles,
version,
}) {
// high level tasks
return {
// dev tasks (live reload)
dev: createTasksForScriptBundles({
buildTarget: BUILD_TARGETS.DEV,
taskPrefix: 'scripts:core:dev',
}),
// production-like distributable build
dist: createTasksForScriptBundles({
buildTarget: BUILD_TARGETS.DIST,
taskPrefix: 'scripts:core:dist',
}),
// production
prod: createTasksForScriptBundles({
buildTarget: BUILD_TARGETS.PROD,
taskPrefix: 'scripts:core:prod',
}),
// built for CI tests
test: createTasksForScriptBundles({
buildTarget: BUILD_TARGETS.TEST,
taskPrefix: 'scripts:core:test',
}),
// built for CI test debugging
testDev: createTasksForScriptBundles({
buildTarget: BUILD_TARGETS.TEST_DEV,
taskPrefix: 'scripts:core:test-live',
}),
};
/**
* Define tasks for building the JavaScript modules used by the extension.
* This function returns a single task that builds JavaScript modules in
* parallel for a single type of build (e.g. dev, testing, production).
*
* @param {object} options - The build options.
* @param {BUILD_TARGETS} options.buildTarget - The build target that these
* JavaScript modules are intended for.
* @param {string} options.taskPrefix - The prefix to use for the name of
* each defined task.
*/
function createTasksForScriptBundles({ buildTarget, taskPrefix }) {
const standardEntryPoints = ['background', 'ui', 'content-script'];
// In MV3 we will need to build our offscreen entry point bundle and any
// entry points for iframes that we want to lockdown with LavaMoat.
if (isManifestV3) {
standardEntryPoints.push('offscreen');
}
const standardSubtask = createTask(
`${taskPrefix}:standardEntryPoints`,
createFactoredBuild({
shouldIncludeSnow,
applyLavaMoat,
browserPlatforms,
buildTarget,
buildType,
entryFiles: standardEntryPoints.map((label) => {
switch (label) {
case 'content-script':
return './app/vendor/trezor/content-script.js';
case 'offscreen':
return './offscreen/scripts/offscreen.ts';
default:
return `./app/scripts/${label}.js`;
}
}),
ignoredFiles,
policyOnly,
shouldLintFenceFiles,
version,
}),
);
// inpage must be built before contentscript
// because inpage bundle result is included inside contentscript
const contentscriptSubtask = createTask(
`${taskPrefix}:contentscript`,
createContentscriptBundle({ buildTarget }),
);
// this can run whenever
const disableConsoleSubtask = createTask(
`${taskPrefix}:disable-console`,
createDisableConsoleBundle({ buildTarget }),
);
// this can run whenever
const installSentrySubtask = createTask(
`${taskPrefix}:sentry`,
createSentryBundle({ buildTarget }),
);
// task for initiating browser livereload
const initiateLiveReload = async () => {
if (isDevBuild(buildTarget)) {
// trigger live reload when the bundles are updated
// this is not ideal, but overcomes the limitations:
// - run from the main process (not child process tasks)
// - after the first build has completed (thus the timeout)
// - build tasks never "complete" when run with livereload + child process
setTimeout(() => {
watch('./dist/*/*.js', (event) => {
livereload.changed(event.path);
});
}, 75e3);
}
};
// make each bundle run in a separate process
const allSubtasks = [
standardSubtask,
contentscriptSubtask,
disableConsoleSubtask,
installSentrySubtask,
].map((subtask) =>
runInChildProcess(subtask, {
shouldIncludeSnow,
applyLavaMoat,
buildType,
isLavaMoat,
policyOnly,
shouldLintFenceFiles,
}),
);
// make a parent task that runs each task in a child thread
return composeParallel(initiateLiveReload, ...allSubtasks);
}
/**
* Create a bundle for the "disable-console" module.
*
* @param {object} options - The build options.
* @param {BUILD_TARGETS} options.buildTarget - The current build target.
* @returns {Function} A function that creates the bundle.
*/
function createDisableConsoleBundle({ buildTarget }) {
const label = 'disable-console';
return createNormalBundle({
browserPlatforms,
buildTarget,
buildType,
destFilepath: `scripts/${label}.js`,
entryFilepath: `./app/scripts/${label}.js`,
ignoredFiles,
label,
policyOnly,
shouldLintFenceFiles,
version,
applyLavaMoat,
});
}
/**
* Create a bundle for the "sentry-install" module.
*
* @param {object} options - The build options.
* @param {BUILD_TARGETS} options.buildTarget - The current build target.
* @returns {Function} A function that creates the bundle.
*/
function createSentryBundle({ buildTarget }) {
const label = 'sentry-install';
return createNormalBundle({
browserPlatforms,
buildTarget,
buildType,
destFilepath: `scripts/${label}.js`,
entryFilepath: `./app/scripts/${label}.js`,
ignoredFiles,
label,
policyOnly,
shouldLintFenceFiles,
version,
applyLavaMoat,
});
}
/**
* Create bundles for the "contentscript" and "inpage" modules. The inpage
* module is created first because it gets embedded in the contentscript
* module.
*
* @param {object} options - The build options.
* @param {BUILD_TARGETS} options.buildTarget - The current build target.
* @returns {Function} A function that creates the bundles.
*/
function createContentscriptBundle({ buildTarget }) {
const inpage = 'inpage';
const contentscript = 'contentscript';
return composeSeries(
createNormalBundle({
buildTarget,
buildType,
browserPlatforms,
destFilepath: `scripts/${inpage}.js`,
entryFilepath: `./app/scripts/${inpage}.js`,
label: inpage,
ignoredFiles,
policyOnly,
shouldLintFenceFiles,
version,
applyLavaMoat,
}),
() => {
// MV3 injects inpage into the tab's main world, but in MV2 we need
// to do it manually:
if (isManifestV3) {
return;
}
// stringify scripts/inpage.js into itself, and then make it inject itself into the page
browserPlatforms.forEach((browser) => {
makeSelfInjecting(
path.join(__dirname, `../../dist/${browser}/scripts/${inpage}.js`),
);
});
// delete the scripts/inpage.js source map, as it no longer represents
// scripts/inpage.js and so `yarn source-map-explorer` can't handle it.
// It's also not useful anyway, as scripts/inpage.js is injected as a
// `script.textContent`, and not tracked in Sentry or browsers devtools
// anyway.
unlinkSync(
path.join(
__dirname,
`../../dist/sourcemaps/scripts/${inpage}.js.map`,
),
);
},
createNormalBundle({
buildTarget,
buildType,
browserPlatforms,
destFilepath: `scripts/${contentscript}.js`,
entryFilepath: `./app/scripts/${contentscript}.js`,
label: contentscript,
ignoredFiles,
policyOnly,
shouldLintFenceFiles,
version,
applyLavaMoat,
}),
);
}
}
/**
* Create the bundle for the app initialization module used in manifest v3
* builds.
*
* This must be called after the "background" bundles have been created, so
* that the list of all background bundles can be injected into this bundle.
*
* @param {object} options - Build options.
* @param {boolean} options.applyLavaMoat - Whether the build should use
* LavaMoat at runtime or not.
* @param {string[]} options.browserPlatforms - A list of browser platforms to
* build bundles for.
* @param {BUILD_TARGETS} options.buildTarget - The current build target.
* @param {string} options.buildType - The current build type (e.g. "main",
* "flask", etc.).
* @param {string[] | null} options.ignoredFiles - A list of files to exclude
* from the current build.
* @param {string[]} options.jsBundles - A list of JavaScript bundles to be
* injected into this bundle.
* @param {boolean} options.policyOnly - Whether to stop the build after
* generating the LavaMoat policy, skipping any writes to disk other than the
* LavaMoat policy itself.
* @param {boolean} options.shouldLintFenceFiles - Whether files with code
* fences should be linted after fences have been removed.
* @param {string} options.version - The current version of the extension.
* @param options.shouldIncludeSnow - Whether the build should use
* Snow at runtime or not.
* @returns {Function} A function that creates the set of bundles.
*/
async function createManifestV3AppInitializationBundle({
shouldIncludeSnow,
applyLavaMoat,
browserPlatforms,
buildTarget,
buildType,
ignoredFiles,
jsBundles,
policyOnly,
shouldLintFenceFiles,
version,
}) {
const label = 'app-init';
// TODO: remove this filter for firefox once MV3 is supported in it
const mv3BrowserPlatforms = browserPlatforms.filter(
(platform) => platform !== 'firefox',
);
for (const filename of jsBundles) {
if (filename.includes(',')) {
throw new Error(
`Invalid filename "${filename}", not allowed to contain comma.`,
);
}
}
const extraEnvironmentVariables = {
USE_SNOW: shouldIncludeSnow,
APPLY_LAVAMOAT: applyLavaMoat,
FILE_NAMES: jsBundles.join(','),
};
await createNormalBundle({
browserPlatforms: mv3BrowserPlatforms,
buildTarget,
buildType,
destFilepath: 'scripts/app-init.js',
entryFilepath: './app/scripts/app-init.js',
extraEnvironmentVariables,
ignoredFiles,
label,
policyOnly,
shouldLintFenceFiles,
version,
applyLavaMoat,
})();
// Code below is used to set statsMode to true when testing in MV3
// This is used to capture module initialisation stats using lavamoat.
if (isTestBuild(buildTarget)) {
const content = readFileSync(
'./dist/chrome/scripts/runtime-lavamoat.js',
'utf8',
);
const fileOutput = content.replace('statsMode = false', 'statsMode = true');
writeFileSync('./dist/chrome/scripts/runtime-lavamoat.js', fileOutput);
}
console.log(`Bundle end: service worker app-init.js`);
}
/**
* Return a function that creates a set of factored bundles.
*
* For each entry point, a series of one or more bundles is created. These are
* split up roughly by size, to ensure no single bundle exceeds the maximum
* JavaScript file size imposed by Firefox.
*
* Modules that are common between all entry points are bundled separately, as
* a set of one or more "common" bundles.
*
* @param {object} options - Build options.
* @param {boolean} options.applyLavaMoat - Whether the build should use
* LavaMoat at runtime or not.
* @param {string[]} options.browserPlatforms - A list of browser platforms to
* build bundles for.
* @param {BUILD_TARGETS} options.buildTarget - The current build target.
* @param {string} options.buildType - The current build type (e.g. "main",
* "flask", etc.).
* @param {string[]} options.entryFiles - A list of entry point file paths,
* relative to the repository root directory.
* @param {string[] | null} options.ignoredFiles - A list of files to exclude
* from the current build.
* @param {boolean} options.policyOnly - Whether to stop the build after
* generating the LavaMoat policy, skipping any writes to disk other than the
* LavaMoat policy itself.
* @param {boolean} options.shouldLintFenceFiles - Whether files with code
* fences should be linted after fences have been removed.
* @param {string} options.version - The current version of the extension.
* @param options.shouldIncludeSnow - Whether the build should use
* Snow at runtime or not.
* @returns {Function} A function that creates the set of bundles.
*/
function createFactoredBuild({
shouldIncludeSnow,
applyLavaMoat,
browserPlatforms,
buildTarget,
buildType,
entryFiles,
ignoredFiles,
policyOnly,
shouldLintFenceFiles,
version,
}) {
return async function () {
// create bundler setup and apply defaults
const buildConfiguration = createBuildConfiguration();
buildConfiguration.label = 'primary';
const { bundlerOpts, events } = buildConfiguration;
// devMode options
const reloadOnChange = isDevBuild(buildTarget);
const minify = !isDevBuild(buildTarget);
const environment = getEnvironment({ buildTarget });
const config = await getConfig(buildType, environment);
const { variables, activeBuild } = config;
setEnvironmentVariables({
isDevBuild: reloadOnChange,
isTestBuild: isTestBuild(buildTarget),
buildName: getBuildName({
environment,
buildType,
}),
buildType,
environment,
variables,
version,
});
const features = {
active: new Set(activeBuild.features ?? []),
all: new Set(Object.keys(config.buildsYml.features)),
};
setupBundlerDefaults(buildConfiguration, {
buildTarget,
variables,
envVars: buildSafeVariableObject(variables),
ignoredFiles,
policyOnly,
minify,
features,
reloadOnChange,
shouldLintFenceFiles,
});
// set bundle entries
bundlerOpts.entries = [...entryFiles];
// setup lavamoat
// lavamoat will add lavapack but it will be removed by bify-module-groups
// we will re-add it later by installing a lavapack runtime
const lavamoatOpts = {
policy: path.resolve(
__dirname,
`../../lavamoat/browserify/${buildType}/policy.json`,
),
policyDebug: path.resolve(
__dirname,
`../../lavamoat/browserify/${buildType}/policy-debug.json`,
),
policyName: buildType,
policyOverride: path.resolve(
__dirname,
`../../lavamoat/browserify/policy-override.json`,
),
writeAutoPolicy: process.env.WRITE_AUTO_POLICY,
writeAutoPolicyDebug: process.env.WRITE_AUTO_POLICY_DEBUG,
};
Object.assign(bundlerOpts, lavamoatBrowserify.args);
bundlerOpts.plugin.push([lavamoatBrowserify, lavamoatOpts]);
// setup bundle factoring with bify-module-groups plugin
// note: this will remove lavapack, but its ok bc we manually readd it later
Object.assign(bundlerOpts, bifyModuleGroups.plugin.args);
bundlerOpts.plugin = [...bundlerOpts.plugin, [bifyModuleGroups.plugin]];
// instrument pipeline
let sizeGroupMap;
events.on('configurePipeline', ({ pipeline }) => {
// to be populated by the group-by-size transform
sizeGroupMap = new Map();
pipeline.get('groups').unshift(
// factor modules
bifyModuleGroups.groupByFactor({
entryFileToLabel(filepath) {
return path.parse(filepath).name;
},
}),
// cap files at 2 mb
bifyModuleGroups.groupBySize({
sizeLimit: 2e6,
groupingMap: sizeGroupMap,
}),
);
// converts each module group into a single vinyl file containing its bundle
const moduleGroupPackerStream = streamFlatMap((moduleGroup) => {
const filename = `${moduleGroup.label}.js`;
const childStream = wrapInStream(
moduleGroup.stream,
// we manually readd lavapack here bc bify-module-groups removes it
lavapack({ raw: true, hasExports: true, includePrelude: false }),
source(filename),
);
return childStream;
});
pipeline.get('vinyl').unshift(moduleGroupPackerStream, buffer());
// add lavamoat policy loader file to packer output
moduleGroupPackerStream.push(
new Vinyl({
path: 'scripts/policy-load.js',
contents: lavapack.makePolicyLoaderStream(lavamoatOpts),
}),
);
// setup bundle destination
browserPlatforms.forEach((platform) => {
const dest = `./dist/${platform}/`;
const destination = policyOnly ? noopWriteStream : gulp.dest(dest);
pipeline.get('dest').push(destination);
});
});
// wait for bundle completion for postprocessing
events.on('bundleDone', async () => {
// Skip HTML generation if nothing is to be written to disk
if (policyOnly) {
return;
}
const commonSet = sizeGroupMap.get('common');
// create entry points for each file
for (const [groupLabel, groupSet] of sizeGroupMap.entries()) {
// skip "common" group, they are added to all other groups
if (groupSet === commonSet) {
continue;
}
const isTest =
buildTarget === BUILD_TARGETS.TEST ||
buildTarget === BUILD_TARGETS.TEST_DEV;
const scripts = getScriptTags({
groupSet,
commonSet,
shouldIncludeSnow,
applyLavaMoat,
});
switch (groupLabel) {
case 'ui': {
renderHtmlFile({
htmlName: 'loading',
browserPlatforms,
shouldIncludeSnow,
applyLavaMoat,
isMMI: buildType === 'mmi',
scripts,
});
renderHtmlFile({
htmlName: 'popup',
browserPlatforms,
shouldIncludeSnow,
applyLavaMoat,
scripts,
});
renderHtmlFile({
htmlName: 'popup-init',
browserPlatforms,
shouldIncludeSnow,
applyLavaMoat,
scripts,
});
renderHtmlFile({
htmlName: 'notification',
browserPlatforms,
shouldIncludeSnow,
applyLavaMoat,
isMMI: buildType === 'mmi',
isTest,
scripts,
});
renderHtmlFile({
htmlName: 'home',
browserPlatforms,
shouldIncludeSnow,
applyLavaMoat,
isMMI: buildType === 'mmi',
isTest,
scripts,
});
break;
}
case 'background': {
renderHtmlFile({
htmlName: 'background',
groupSet,
commonSet,
browserPlatforms,
shouldIncludeSnow,
applyLavaMoat,
scripts,
});
if (isManifestV3) {
const jsBundles = [
...commonSet.values(),
...groupSet.values(),
].map((label) => `../${label}.js`);
await createManifestV3AppInitializationBundle({
shouldIncludeSnow,
applyLavaMoat,
browserPlatforms,
buildTarget,
buildType,
ignoredFiles,
jsBundles,
policyOnly,
shouldLintFenceFiles,
version,
});
}
break;
}
case 'content-script': {
renderHtmlFile({
htmlName: 'trezor-usb-permissions',
groupSet,
commonSet,
browserPlatforms,
shouldIncludeSnow,
applyLavaMoat: false,
scripts,
});
break;
}
case 'offscreen': {
renderHtmlFile({
htmlName: 'offscreen',
groupSet,
commonSet,
browserPlatforms,
shouldIncludeSnow,
applyLavaMoat,
scripts,
});
break;
}
default: {
throw new Error(
`build/scripts - unknown groupLabel "${groupLabel}"`,
);
}
}
}
});
await createBundle(buildConfiguration, { reloadOnChange });
};
}
/**
* Return a function that creates a single JavaScript bundle.
*
* @param {object} options - Build options.
* @param {string[]} options.browserPlatforms - A list of browser platforms to
* build the bundle for.
* @param {BUILD_TARGETS} options.buildTarget - The current build target.
* @param {string} options.buildType - The current build type (e.g. "main",
* "flask", etc.).
* @param {string} options.destFilepath - The file path the bundle should be
* written to.
* @param {string[]} options.entryFilepath - The entry point file path,
* relative to the repository root directory.
* @param {Record<string, unknown>} options.extraEnvironmentVariables - Extra
* environment variables to inject just into this bundle.
* @param {string[] | null} options.ignoredFiles - A list of files to exclude
* from the current build.
* @param {string} options.label - A label used to describe this bundle in any
* diagnostic messages.
* @param {boolean} options.policyOnly - Whether to stop the build after
* generating the LavaMoat policy, skipping any writes to disk other than the
* LavaMoat policy itself.
* @param {boolean} options.shouldLintFenceFiles - Whether files with code
* fences should be linted after fences have been removed.
* @param {string} options.version - The current version of the extension.
* @param {boolean} options.applyLavaMoat - Whether to apply LavaMoat or not
* @returns {Function} A function that creates the bundle.
*/
function createNormalBundle({
browserPlatforms,
buildTarget,
buildType,
destFilepath,
entryFilepath,
extraEnvironmentVariables,
ignoredFiles,
label,
policyOnly,
shouldLintFenceFiles,
version,
applyLavaMoat,
}) {
return async function () {
// create bundler setup and apply defaults
const buildConfiguration = createBuildConfiguration();
buildConfiguration.label = label;
const { bundlerOpts, events } = buildConfiguration;
// devMode options
const devMode = isDevBuild(buildTarget);
const reloadOnChange = Boolean(devMode);
const minify = Boolean(devMode) === false;
const environment = getEnvironment({ buildTarget });
const config = await getConfig(buildType, environment);
const { activeBuild, variables } = config;
setEnvironmentVariables({
buildName: getBuildName({
environment,
buildType,
}),
isDevBuild: devMode,
isTestBuild: isTestBuild(buildTarget),
buildType,
variables,
environment,
version,
});
Object.entries(extraEnvironmentVariables ?? {}).forEach(([key, value]) =>
variables.set(key, value),
);
const features = {
active: new Set(activeBuild.features ?? []),
all: new Set(Object.keys(config.buildsYml.features)),
};
setupBundlerDefaults(buildConfiguration, {
envVars: buildSafeVariableObject(variables),
ignoredFiles,
policyOnly,
minify,
features,
reloadOnChange,
shouldLintFenceFiles,
applyLavaMoat,
});
// set bundle entries
bundlerOpts.entries = [entryFilepath];
// instrument pipeline
events.on('configurePipeline', ({ pipeline }) => {
// convert bundle stream to gulp vinyl stream
// and ensure file contents are buffered
pipeline.get('vinyl').push(source(destFilepath));
pipeline.get('vinyl').push(buffer());
// setup bundle destination
browserPlatforms.forEach((platform) => {
const dest = `./dist/${platform}/`;
const destination = policyOnly ? noopWriteStream : gulp.dest(dest);
pipeline.get('dest').push(destination);
});
});
await createBundle(buildConfiguration, { reloadOnChange });
};
}
function createBuildConfiguration() {
const label = '(unnamed bundle)';
const events = new EventEmitter();
const bundlerOpts = {
entries: [],
transform: [],
plugin: [],
require: [],
// non-standard bify options
manualExternal: [],
manualIgnore: [],
};
return { bundlerOpts, events, label };
}
function setupBundlerDefaults(
buildConfiguration,
{
buildTarget,
envVars,
ignoredFiles,
policyOnly,
minify,
features,
reloadOnChange,
shouldLintFenceFiles,
applyLavaMoat,
},
) {
const { bundlerOpts } = buildConfiguration;
const extensions = ['.js', '.ts', '.tsx'];
Object.assign(bundlerOpts, {
// Source transforms
transform: [
// // Remove code that should be excluded from builds of the current type
createRemoveFencedCodeTransform(features, shouldLintFenceFiles),
// Transpile top-level code
[
babelify,
// Run TypeScript files through Babel
{
extensions,
},
],
// We are transpelling the firebase package to be compatible with the lavaMoat restrictions
[
babelify,
{
only: [
'./**/node_modules/firebase',
'./**/node_modules/@firebase',
'./**/node_modules/marked',
'./**/node_modules/@solana',
],
global: true,
},
],
],
// Look for TypeScript files when walking the dependency tree
extensions,
// Use entryFilepath for moduleIds, easier to determine origin file
fullPaths: isDevBuild(buildTarget) || isTestBuild(buildTarget),
// For sourcemaps
debug: true,
});
// Ensure react-devtools is only included in dev builds
if (buildTarget !== BUILD_TARGETS.DEV) {
bundlerOpts.manualIgnore.push('react-devtools');
bundlerOpts.manualIgnore.push('remote-redux-devtools');
}
// This dependency uses WASM which we cannot execute in accordance with our CSP
bundlerOpts.manualIgnore.push('@chainsafe/as-sha256');
// Inject environment variables via node-style `process.env`
if (envVars) {
bundlerOpts.transform.push([envify(envVars), { global: true }]);
}
// Ensure that any files that should be ignored are excluded from the build
if (ignoredFiles) {
bundlerOpts.manualExclude = ignoredFiles;
}
// Setup reload on change
if (reloadOnChange) {
setupReloadOnChange(buildConfiguration);
}
if (!policyOnly) {
if (minify) {
setupMinification(buildConfiguration);
}
// Setup source maps
setupSourcemaps(buildConfiguration, { buildTarget });
// Setup wrapping of code against scuttling (before sourcemaps generation)
setupScuttlingWrapping(buildConfiguration, applyLavaMoat);
}
}
function setupReloadOnChange({ bundlerOpts, events }) {
// Add plugin to options
Object.assign(bundlerOpts, {
plugin: [...bundlerOpts.plugin, watchify],
// Required by watchify
cache: {},
packageCache: {},
});
// Instrument pipeline
events.on('configurePipeline', ({ bundleStream }) => {
// Handle build error to avoid breaking build process
// (eg on syntax error)
bundleStream.on('error', (err) => {