/
utils.js
1193 lines (1079 loc) Β· 30.5 KB
/
utils.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
// @flow strict-local
import type {
Asset,
BuildEvent,
BuildSuccessEvent,
BundleGraph,
Dependency,
FilePath,
InitialParcelOptions,
PackagedBundle,
} from '@parcel/types';
import type {FileSystem} from '@parcel/fs';
import type WorkerFarm from '@parcel/workers';
import invariant from 'assert';
import util from 'util';
import Parcel, {createWorkerFarm} from '@parcel/core';
import assert from 'assert';
import vm from 'vm';
import v8 from 'v8';
import {NodeFS, MemoryFS, OverlayFS, ncp as _ncp} from '@parcel/fs';
import path from 'path';
import url from 'url';
import WebSocket from 'ws';
import nullthrows from 'nullthrows';
import {parser as postHtmlParse} from 'posthtml-parser';
import postHtml from 'posthtml';
import EventEmitter from 'events';
import http from 'http';
import https from 'https';
import {makeDeferredWithPromise, normalizeSeparators} from '@parcel/utils';
import _chalk from 'chalk';
import resolve from 'resolve';
export const workerFarm = (createWorkerFarm(): WorkerFarm);
export const inputFS: NodeFS = new NodeFS();
export let outputFS: MemoryFS = new MemoryFS(workerFarm);
export let overlayFS: OverlayFS = new OverlayFS(outputFS, inputFS);
beforeEach(() => {
outputFS = new MemoryFS(workerFarm);
overlayFS = new OverlayFS(outputFS, inputFS);
});
// Recursively copies a directory from the inputFS to the outputFS
export async function ncp(source: FilePath, destination: FilePath) {
await _ncp(inputFS, source, outputFS, destination);
}
// Mocha is currently run with exit: true because of this issue preventing us
// from properly ending the workerfarm after the test run:
// https://github.com/nodejs/node/pull/28788
//
// TODO: Remove exit: true in .mocharc.json and instead add the following in this file:
// // Spin down the worker farm to stop it from preventing the main process from exiting
// await workerFarm.end();
// when https://github.com/nodejs/node/pull/28788 is resolved.
const chalk = new _chalk.Instance();
const warning = chalk.keyword('orange');
/* eslint-disable no-console */
// $FlowFixMe[cannot-write]
console.warn = (...args) => {
// eslint-disable-next-line no-console
console.error(warning(...args));
};
/* eslint-enable no-console */
type ExternalModules = {|
[name: string]: (vm$Context) => {[string]: mixed},
|};
export function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
export function normalizeFilePath(filePath: string): FilePath {
return normalizeSeparators(filePath);
}
export const distDir: string = path.resolve(
__dirname,
'..',
'..',
'integration-tests',
'dist',
);
export async function removeDistDirectory() {
await outputFS.rimraf(distDir);
}
export function symlinkPrivilegeWarning() {
// eslint-disable-next-line no-console
console.warn(
`-----------------------------------
Skipping symbolic link test(s) because you don't have the privilege.
Run tests with Administrator privilege.
If you don't know how, check here: https://bit.ly/2UmWsbD
-----------------------------------`,
);
}
export function getParcelOptions(
entries: FilePath | Array<FilePath>,
opts?: $Shape<InitialParcelOptions>,
): InitialParcelOptions {
return mergeParcelOptions(
{
entries,
shouldDisableCache: true,
logLevel: 'none',
defaultConfig: path.join(
__dirname,
process.env.PARCEL_TEST_EXPERIMENTAL_BUNDLER == null
? '.parcelrc-no-reporters'
: '.parcelrc-experimental-bundler',
),
inputFS,
outputFS,
workerFarm,
shouldContentHash: true,
defaultTargetOptions: {
distDir,
engines: {
browsers: ['last 1 Chrome version'],
node: '8',
},
},
},
opts,
);
}
export function bundler(
entries: FilePath | Array<FilePath>,
opts?: $Shape<InitialParcelOptions>,
): Parcel {
return new Parcel(getParcelOptions(entries, opts));
}
export function findAsset(
bundleGraph: BundleGraph<PackagedBundle>,
assetFileName: string,
): ?Asset {
return bundleGraph.traverseBundles((bundle, context, actions) => {
let asset = bundle.traverseAssets((asset, context, actions) => {
if (path.basename(asset.filePath) === assetFileName) {
actions.stop();
return asset;
}
});
if (asset) {
actions.stop();
return asset;
}
});
}
export function findDependency(
bundleGraph: BundleGraph<PackagedBundle>,
assetFileName: string,
specifier: string,
): Dependency {
let asset = nullthrows(
findAsset(bundleGraph, assetFileName),
`Couldn't find asset ${assetFileName}`,
);
let dependency = bundleGraph
.getDependencies(asset)
.find(d => d.specifier === specifier);
invariant(
dependency != null,
`Couldn't find dependency ${assetFileName} -> ${specifier}`,
);
return dependency;
}
export function mergeParcelOptions(
optsOne: InitialParcelOptions,
optsTwo?: InitialParcelOptions | null,
): InitialParcelOptions {
if (!optsTwo) {
return optsOne;
}
return {
...optsOne,
...optsTwo,
// $FlowFixMe
defaultTargetOptions: {
...optsOne?.defaultTargetOptions,
// $FlowFixMe
...optsTwo?.defaultTargetOptions,
},
};
}
export function assertDependencyWasExcluded(
bundleGraph: BundleGraph<PackagedBundle>,
assetFileName: string,
specifier: string,
): void {
let dep = findDependency(bundleGraph, assetFileName, specifier);
invariant(
bundleGraph.isDependencySkipped(dep),
util.inspect(dep) + " wasn't deferred",
);
}
export async function bundle(
entries: FilePath | Array<FilePath>,
opts?: InitialParcelOptions,
): Promise<BundleGraph<PackagedBundle>> {
return (await bundler(entries, opts).run()).bundleGraph;
}
export function getNextBuild(b: Parcel): Promise<BuildEvent> {
return new Promise((resolve, reject) => {
let subscriptionPromise = b
.watch((err, buildEvent) => {
if (err) {
reject(err);
return;
}
subscriptionPromise
.then(subscription => {
// If the watch callback was reached, subscription must have been successful
invariant(subscription != null);
return subscription.unsubscribe();
})
.then(() => {
// If the build promise hasn't been rejected, buildEvent must exist
invariant(buildEvent != null);
resolve(buildEvent);
})
.catch(reject);
})
.catch(reject);
});
}
export async function getNextBuildSuccess(
b: Parcel,
): Promise<BuildSuccessEvent> {
let evt = await getNextBuild(b);
invariant(evt.type === 'buildSuccess');
return evt;
}
export function shallowEqual(
a: $Shape<{|+[string]: mixed|}>,
b: $Shape<{|+[string]: mixed|}>,
): boolean {
if (Object.keys(a).length !== Object.keys(b).length) {
return false;
}
for (let [key, value] of Object.entries(a)) {
if (!b.hasOwnProperty(key) || b[key] !== value) {
return false;
}
}
return true;
}
type RunOpts = {require?: boolean, strict?: boolean, ...};
export async function runBundles(
bundleGraph: BundleGraph<PackagedBundle>,
parent: PackagedBundle,
bundles: Array<[string, PackagedBundle]>,
globals: mixed,
opts: RunOpts = {},
externalModules?: ExternalModules,
): Promise<mixed> {
let entryAsset = nullthrows(
bundles
.map(([, b]) => b.getMainEntry() || b.getEntryAssets()[0])
.filter(Boolean)[0],
);
let env = entryAsset.env;
let target = env.context;
let outputFormat = env.outputFormat;
let ctx, promises;
switch (target) {
case 'browser': {
let prepared = prepareBrowserContext(parent, globals);
ctx = prepared.ctx;
promises = prepared.promises;
break;
}
case 'node':
case 'electron-main':
nodeCache.clear();
ctx = prepareNodeContext(
outputFormat === 'commonjs' && parent.filePath,
globals,
);
break;
case 'electron-renderer': {
nodeCache.clear();
let prepared = prepareBrowserContext(parent, globals);
prepareNodeContext(
outputFormat === 'commonjs' && parent.filePath,
globals,
prepared.ctx,
);
ctx = prepared.ctx;
promises = prepared.promises;
break;
}
case 'web-worker':
case 'service-worker': {
let prepared = prepareWorkerContext(parent.filePath, globals);
ctx = prepared.ctx;
promises = prepared.promises;
break;
}
case 'worklet': {
ctx = Object.assign({}, globals);
break;
}
default:
throw new Error('Unknown target ' + target);
}
// A utility to prevent optimizers from removing side-effect-free code needed for testing
// $FlowFixMe[prop-missing]
ctx.sideEffectNoop = () => {};
vm.createContext(ctx);
let esmOutput;
if (outputFormat === 'esmodule') {
let res = await runESM(
bundles[0][1].target.distDir,
bundles.map(([code, bundle]) => [code, bundle.filePath]),
ctx,
overlayFS,
externalModules,
true,
);
esmOutput = bundles.length === 1 ? res[0] : res;
} else {
invariant(
externalModules == null,
'externalModules are only supported with ESM',
);
for (let [code, b] of bundles) {
// require, parcelRequire was set up in prepare*Context
new vm.Script((opts.strict ? '"use strict";\n' : '') + code, {
filename:
b.bundleBehavior === 'inline'
? b.name
: normalizeSeparators(path.relative(b.target.distDir, b.filePath)),
async importModuleDynamically(specifier) {
let filePath = path.resolve(path.dirname(parent.filePath), specifier);
let code = await overlayFS.readFile(filePath, 'utf8');
let modules = await runESM(
b.target.distDir,
[[code, filePath]],
ctx,
overlayFS,
externalModules,
true,
);
return modules[0];
},
}).runInContext(ctx);
}
}
if (promises) {
// await any ongoing dynamic imports during the run
await Promise.all(promises);
}
if (opts.require !== false) {
switch (outputFormat) {
case 'global':
if (env.shouldScopeHoist) {
return typeof ctx.output !== 'undefined' ? ctx.output : undefined;
} else {
for (let key in ctx) {
if (key.startsWith('parcelRequire')) {
// $FlowFixMe[incompatible-use]
return ctx[key](bundleGraph.getAssetPublicId(entryAsset));
}
}
}
return;
case 'commonjs':
invariant(typeof ctx.module === 'object' && ctx.module != null);
return ctx.module.exports;
case 'esmodule':
return esmOutput;
default:
throw new Error(
'Unable to run bundle with outputFormat ' + env.outputFormat,
);
}
}
return ctx;
}
export async function runBundle(
bundleGraph: BundleGraph<PackagedBundle>,
bundle: PackagedBundle,
globals: mixed,
opts: RunOpts = {},
externalModules?: ExternalModules,
): Promise<mixed> {
if (bundle.type === 'html') {
let code = await overlayFS.readFile(nullthrows(bundle.filePath), 'utf8');
let ast = postHtmlParse(code, {
lowerCaseAttributeNames: true,
});
let bundles = bundleGraph.getBundles({includeInline: true});
let scripts = [];
postHtml().walk.call(ast, node => {
if (node.attrs?.nomodule != null) {
return node;
}
if (node.tag === 'script' && node.attrs?.src) {
let src = url.parse(nullthrows(node.attrs).src);
if (src.hostname == null) {
let p = path.join(distDir, nullthrows(src.pathname));
let b = nullthrows(bundles.find(b => b.filePath === p));
scripts.push([overlayFS.readFileSync(b.filePath, 'utf8'), b]);
}
} else if (node.tag === 'script' && node.content && !node.attrs?.src) {
let content = node.content.join('');
let inline = bundles.filter(
b => b.bundleBehavior === 'inline' && b.type === 'js',
);
scripts.push([content, inline[0]]);
}
return node;
});
return runBundles(
bundleGraph,
bundle,
scripts,
globals,
opts,
externalModules,
);
} else {
return runBundles(
bundleGraph,
bundle,
[[overlayFS.readFileSync(bundle.filePath, 'utf8'), bundle]],
globals,
opts,
externalModules,
);
}
}
export function run(
bundleGraph: BundleGraph<PackagedBundle>,
globals: mixed,
opts: RunOpts = {},
externalModules?: ExternalModules,
// $FlowFixMe[unclear-type]
): Promise<any> {
let bundle = nullthrows(
bundleGraph.getBundles().find(b => b.type === 'js' || b.type === 'html'),
);
return runBundle(bundleGraph, bundle, globals, opts, externalModules);
}
export function assertBundles(
bundleGraph: BundleGraph<PackagedBundle>,
expectedBundles: Array<{|
name?: string | RegExp,
type?: string,
assets: Array<string>,
|}>,
) {
let actualBundles = [];
const byAlphabet = (a, b) => (a.toLowerCase() < b.toLowerCase() ? -1 : 1);
bundleGraph.traverseBundles(bundle => {
let assets = [];
bundle.traverseAssets(asset => {
if (/@swc[/\\]helpers/.test(asset.filePath)) {
// Skip all helpers for now, as they add friction and churn to assertions.
// A longer term solution might have an explicit opt-in to this behavior, or
// if we enable symbol propagation unconditionally, the set of helpers
// should be more minimal.
return;
}
if (/runtime-[a-z0-9]{16}\.js/.test(asset.filePath)) {
// Skip runtime assets, which have hashed filenames for source maps.
return;
}
const name = path.basename(asset.filePath);
assets.push(name);
});
assets.sort(byAlphabet);
actualBundles.push({
name:
bundle.bundleBehavior === 'inline'
? bundle.name
: path.basename(bundle.filePath),
type: bundle.type,
assets,
});
});
for (let bundle of expectedBundles) {
if (!Array.isArray(bundle.assets)) {
throw new Error(
'Expected bundle must include an array of expected assets',
);
}
bundle.assets.sort(byAlphabet);
}
const byName = (a, b) => {
if (typeof a.name === 'string' && typeof b.name === 'string') {
return a.name.localeCompare(b.name);
}
return 0;
};
const byAssets = (a, b) =>
a.assets.join(',').localeCompare(b.assets.join(','));
expectedBundles.sort(byName).sort(byAssets);
actualBundles.sort(byName).sort(byAssets);
assert.equal(
actualBundles.length,
expectedBundles.length,
'expected number of bundles mismatched',
);
let i = 0;
for (let bundle of expectedBundles) {
let actualBundle = actualBundles[i++];
let name = bundle.name;
let actualName = actualBundle.name;
if (name != null && actualName != null) {
if (typeof name === 'string') {
assert.equal(
actualName,
name,
`Bundle name "${actualName}", does not match expected name "${name}"`,
);
} else if (name instanceof RegExp) {
assert(
actualName.match(name),
`${actualName} does not match regexp ${name.toString()}`,
);
} else {
// $FlowFixMe[incompatible-call]
assert.fail('Expected bundle name has invalid type');
}
}
if (bundle.type != null) {
assert.equal(actualBundle.type, bundle.type);
}
if (bundle.assets) {
assert.deepEqual(actualBundle.assets, bundle.assets);
}
}
}
export function normaliseNewlines(text: string): string {
return text.replace(/(\r\n|\n|\r)/g, '\n');
}
function prepareBrowserContext(
bundle: PackagedBundle,
globals: mixed,
): {|
ctx: vm$Context,
promises: Array<Promise<mixed>>,
|} {
// for testing dynamic imports
const fakeElement = {
remove() {},
};
const head = {
children: [],
appendChild(el) {
head.children.push(el);
if (el.tag === 'script') {
let {deferred, promise} = makeDeferredWithPromise();
promises.push(promise);
setTimeout(function () {
let pathname = url.parse(el.src).pathname;
let file = path.join(bundle.target.distDir, pathname);
new vm.Script(
// '"use strict";\n' +
overlayFS.readFileSync(file, 'utf8'),
{
filename: pathname.slice(1),
},
).runInContext(ctx);
el.onload();
deferred.resolve();
}, 0);
} else if (typeof el.onload === 'function') {
el.onload();
}
},
};
let promises = [];
const fakeDocument = {
head,
createElement(tag) {
return {tag};
},
getElementsByTagName() {
return [head];
},
createEvent() {
// For Vue
return {timeStamp: Date.now()};
},
getElementById(id) {
if (id !== '__parcel__error__overlay__') return fakeElement;
},
body: {
appendChild() {
return null;
},
},
currentScript: null,
};
var exports = {};
function PatchedError(message) {
const patchedError = new Error(message);
const stackStart = patchedError.stack.indexOf('at new Error');
const stackEnd = patchedError.stack.includes('at Script.runInContext')
? patchedError.stack.indexOf('at Script.runInContext')
: patchedError.stack.indexOf('at runNextTicks');
const stack = patchedError.stack.slice(stackStart, stackEnd).split('\n');
stack.shift();
stack.pop();
for (let [i, line] of stack.entries()) {
stack[i] = line.replace(
/( ?.* )\(?(.*)\)?$/,
(_, prefix, path) =>
prefix +
(path.endsWith(')')
? `(http://localhost/${path.slice(0, path.length - 1)})`
: `http://localhost/${path}`),
);
}
patchedError.stack =
patchedError.stack.slice(0, stackStart).replace(/ +$/, '') +
stack.join('\n');
return patchedError;
}
PatchedError.prototype = Object.create(Error.prototype);
Object.defineProperty(PatchedError, 'name', {
writable: true,
value: 'Error',
});
PatchedError.prototype.constructor = PatchedError;
var ctx = Object.assign(
{
Error: PatchedError,
exports,
module: {exports},
document: fakeDocument,
WebSocket,
console: {...console, clear: () => {}},
location: {
hostname: 'localhost',
origin: 'http://localhost',
protocol: 'http',
},
navigator: {
userAgent: '',
},
fetch(url) {
return Promise.resolve({
async arrayBuffer() {
let readFilePromise = overlayFS.readFile(
path.join(path.dirname(bundle.target.distDir), url),
);
promises.push(readFilePromise);
return new Uint8Array(await readFilePromise).buffer;
},
text() {
let readFilePromise = overlayFS.readFile(
path.join(path.dirname(bundle.target.distDir), url),
'utf8',
);
promises.push(readFilePromise);
return readFilePromise;
},
});
},
atob(str) {
return Buffer.from(str, 'base64').toString('binary');
},
btoa(str) {
return Buffer.from(str, 'binary').toString('base64');
},
URL,
Worker: createWorkerClass(bundle.filePath),
addEventListener() {},
removeEventListener() {},
},
globals,
);
ctx.window = ctx.self = ctx;
return {ctx, promises};
}
function createWorkerClass(filePath: FilePath) {
return class Worker extends EventEmitter {
constructor(url) {
super();
this._run(url);
}
async _run(url) {
let u = new URL(url);
let filename = path.join(path.dirname(filePath), u.pathname);
let {ctx, promises} = prepareWorkerContext(filename, {
postMessage: msg => {
this.emit('message', msg);
},
});
let code = await overlayFS.readFile(filename, 'utf8');
vm.createContext(ctx);
new vm.Script(code, {
filename: 'http://localhost/' + path.basename(filename),
}).runInContext(ctx);
if (promises) {
await Promise.all(promises);
}
}
addEventListener(evt, callback) {
super.on(evt, callback);
}
removeEventListener(evt, callback) {
super.removeListener(evt, callback);
}
};
}
function prepareWorkerContext(
filePath: FilePath,
globals: mixed,
): {|
ctx: vm$Context,
promises: Array<Promise<mixed>>,
|} {
let promises = [];
var exports = {};
var ctx = Object.assign(
{
exports,
module: {exports},
WebSocket,
console,
location: {hostname: 'localhost', origin: 'http://localhost'},
importScripts(...urls) {
for (let u of urls) {
new vm.Script(
overlayFS.readFileSync(
path.join(path.dirname(filePath), url.parse(u).pathname),
'utf8',
),
{
filename: path.basename(url.parse(u).pathname),
},
).runInContext(ctx);
}
},
fetch(url) {
return Promise.resolve({
async arrayBuffer() {
let readFilePromise = overlayFS.readFile(
path.join(path.dirname(filePath), url),
);
promises.push(readFilePromise);
return new Uint8Array(await readFilePromise).buffer;
},
text() {
let readFilePromise = overlayFS.readFile(
path.join(path.dirname(filePath), url),
'utf8',
);
promises.push(readFilePromise);
return readFilePromise;
},
});
},
atob(str) {
return Buffer.from(str, 'base64').toString('binary');
},
btoa(str) {
return Buffer.from(str, 'binary').toString('base64');
},
URL,
Worker: createWorkerClass(filePath),
},
globals,
);
ctx.window = ctx.self = ctx;
return {ctx, promises};
}
const nodeCache = new Map();
// no filepath = ESM
// $FlowFixMe
function prepareNodeContext(filePath, globals, ctx: any = {}) {
let exports = {};
let req =
filePath &&
(specifier => {
// $FlowFixMe[prop-missing]
let res = resolve.sync(specifier, {
basedir: path.dirname(filePath),
preserveSymlinks: true,
extensions: ['.js', '.json'],
readFileSync: (...args) => {
return overlayFS.readFileSync(...args);
},
isFile: file => {
try {
var stat = overlayFS.statSync(file);
} catch (err) {
return false;
}
return stat.isFile();
},
isDirectory: file => {
try {
var stat = overlayFS.statSync(file);
} catch (err) {
return false;
}
return stat.isDirectory();
},
});
// Shim FS module using overlayFS
if (res === 'fs') {
return {
readFile: async (file, encoding, cb) => {
let res = await overlayFS.readFile(file, encoding);
cb(null, res);
},
readFileSync: (file, encoding) => {
return overlayFS.readFileSync(file, encoding);
},
};
}
if (res === specifier) {
// $FlowFixMe[unsupported-syntax]
return require(specifier);
}
let cached = nodeCache.get(res);
if (cached) {
return cached.module.exports;
}
let g = {
...globals,
};
for (let key in ctx) {
if (
key !== 'module' &&
key !== 'exports' &&
key !== '__filename' &&
key !== '__dirname' &&
key !== 'require'
) {
g[key] = ctx[key];
}
}
let childCtx = prepareNodeContext(res, g);
nodeCache.set(res, childCtx);
vm.createContext(childCtx);
new vm.Script(
//'"use strict";\n' +
overlayFS.readFileSync(res, 'utf8'),
{
filename: path.basename(res),
},
).runInContext(childCtx);
return childCtx.module.exports;
});
if (filePath) {
ctx.module = {exports, require: req};
ctx.exports = exports;
ctx.__filename = filePath;
ctx.__dirname = path.dirname(filePath);
ctx.require = req;
}
ctx.console = console;
ctx.process = process;
ctx.setTimeout = setTimeout;
ctx.setImmediate = setImmediate;
ctx.global = ctx;
ctx.URL = URL;
Object.assign(ctx, globals);
return ctx;
}
let instanceId = 0;
export async function runESM(
baseDir: FilePath,
entries: Array<[string, string]>,
context: vm$Context,
fs: FileSystem,
externalModules: ExternalModules = {},
requireExtensions: boolean = false,
): Promise<Array<{|[string]: mixed|}>> {
let id = instanceId++;
let cache = new Map();
function load(specifier, referrer, code = null) {
if (path.isAbsolute(specifier) || specifier.startsWith('.')) {
let extname = path.extname(specifier);
if (extname && extname !== '.js' && extname !== '.mjs') {
throw new Error(
'Unknown file extension in ' +
specifier +
' from ' +
referrer.identifier,
);
}
let filename = path.resolve(
baseDir,
path.dirname(referrer.identifier),
!extname && !requireExtensions ? specifier + '.js' : specifier,
);
let m = cache.get(filename);
if (m) {
return m;
}
let source = code ?? fs.readFileSync(filename, 'utf8');
// $FlowFixMe Experimental
m = new vm.SourceTextModule(source, {
identifier: `${normalizeSeparators(
path.relative(baseDir, filename),
)}?id=${id}`,
importModuleDynamically: (specifier, referrer) =>
entry(specifier, referrer),
context,
initializeImportMeta(meta) {
meta.url = `http://localhost/${path.basename(filename)}`;
},