-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
utils.js
526 lines (466 loc) Β· 12.8 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
// @flow
import type {
Bundle,
BuildEvent,
BundleGraph,
FilePath,
InitialParcelOptions,
} from '@parcel/types';
import invariant from 'assert';
import Parcel, {createWorkerFarm} from '@parcel/core';
import defaultConfigContents from '@parcel/config-default';
import assert from 'assert';
import vm from 'vm';
import {NodeFS, MemoryFS, OverlayFS, ncp as _ncp} from '@parcel/fs';
import path from 'path';
import WebSocket from 'ws';
import nullthrows from 'nullthrows';
import {makeDeferredWithPromise} from '@parcel/utils';
import _chalk from 'chalk';
import resolve from 'resolve';
import {NodePackageManager} from '@parcel/package-manager';
const workerFarm = createWorkerFarm();
export const inputFS = new NodeFS();
export let outputFS = new MemoryFS(workerFarm);
export let 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.
export const defaultConfig = {
...defaultConfigContents,
filePath: require.resolve('@parcel/config-default'),
reporters: [],
};
const chalk = new _chalk.constructor({enabled: true});
const warning = chalk.keyword('orange');
/* eslint-disable no-console */
// $FlowFixMe
console.warn = (...args) => {
// eslint-disable-next-line no-console
console.error(warning(...args));
};
/* eslint-enable no-console */
export function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
export function normalizeFilePath(filePath: string) {
return filePath.replace(/[\\/]+/g, '/');
}
export const distDir = 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 bundler(
entries: FilePath | Array<FilePath>,
opts?: InitialParcelOptions,
) {
return new Parcel({
entries,
disableCache: true,
logLevel: 'none',
defaultConfig,
inputFS,
outputFS,
workerFarm,
packageManager: new NodePackageManager(inputFS),
defaultEngines: {
browsers: ['last 1 Chrome version'],
node: '8',
},
...opts,
});
}
export async function bundle(
entries: FilePath | Array<FilePath>,
opts?: InitialParcelOptions,
): Promise<BundleGraph> {
return nullthrows(await bundler(entries, opts).run());
}
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);
});
}
type RunOpts = {require?: boolean, ...};
export async function runBundle(
bundle: Bundle,
globals: mixed,
opts: RunOpts = {},
): Promise<mixed> {
let entryAsset = nullthrows(bundle.getMainEntry());
let target = entryAsset.env.context;
let ctx, promises;
switch (target) {
case 'browser': {
let prepared = prepareBrowserContext(
nullthrows(bundle.filePath),
globals,
);
ctx = prepared.ctx;
promises = prepared.promises;
break;
}
case 'node':
case 'electron-main':
ctx = prepareNodeContext(nullthrows(bundle.filePath), globals);
break;
case 'electron-renderer': {
let browser = prepareBrowserContext(nullthrows(bundle.filePath), globals);
ctx = {
...browser.ctx,
...prepareNodeContext(nullthrows(bundle.filePath), globals),
};
promises = browser.promises;
break;
}
default:
throw new Error('Unknown target ' + target);
}
vm.createContext(ctx);
vm.runInContext(
await overlayFS.readFile(nullthrows(bundle.filePath), 'utf8'),
ctx,
);
if (promises) {
// await any ongoing dynamic imports during the run
await Promise.all(promises);
}
if (opts.require !== false) {
switch (bundle.env.outputFormat) {
case 'global':
if (bundle.env.scopeHoist) {
return typeof ctx.output !== 'undefined' ? ctx.output : undefined;
} else if (ctx.parcelRequire) {
// $FlowFixMe
return ctx.parcelRequire(entryAsset.id);
}
return;
case 'commonjs':
invariant(typeof ctx.module === 'object' && ctx.module != null);
return ctx.module.exports;
default:
throw new Error(
'Unable to run bundle with outputFormat ' + bundle.env.outputFormat,
);
}
}
return ctx;
}
export function run(
bundleGraph: BundleGraph,
globals: mixed,
opts: RunOpts = {},
): Promise<mixed> {
let bundles = bundleGraph.getBundles();
let bundle = nullthrows(bundles.find(b => b.type === 'js'));
return runBundle(bundle, globals, opts);
}
export function assertBundles(
bundleGraph: BundleGraph,
expectedBundles: Array<{|
name?: string | RegExp,
type?: string,
assets: Array<string>,
includedFiles?: {
[key: string]: Array<string>,
...,
},
|}>,
) {
let actualBundles = [];
const byAlphabet = (a, b) => (a.toLowerCase() < b.toLowerCase() ? -1 : 1);
bundleGraph.traverseBundles(bundle => {
let assets = [];
const includedFiles = {};
bundle.traverseAssets(asset => {
const name = path.basename(asset.filePath);
assets.push(name);
includedFiles[name] = asset
.getIncludedFiles()
.map(({filePath}) => path.basename(filePath))
.sort(byAlphabet);
});
assets.sort(byAlphabet);
actualBundles.push({
name: path.basename(nullthrows(bundle.filePath)),
type: bundle.type,
assets,
includedFiles,
});
});
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[0].localeCompare(b.assets[0]);
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;
if (name) {
if (typeof name === 'string') {
assert.equal(actualBundle.name, name);
} else if (name instanceof RegExp) {
assert(
actualBundle.name.match(name),
`${actualBundle.name} does not match regexp ${name.toString()}`,
);
} else {
// $FlowFixMe
assert.fail();
}
}
if (bundle.type) {
assert.equal(actualBundle.type, bundle.type);
}
if (bundle.assets) {
assert.deepEqual(actualBundle.assets, bundle.assets);
}
if (bundle.includedFiles) {
for (let asset of actualBundle.assets) {
const files = bundle.includedFiles[asset];
if (!files) {
continue;
}
assert.deepEqual(
actualBundle.includedFiles[asset],
files.sort(byAlphabet),
);
}
}
}
}
export function normaliseNewlines(text: string): string {
return text.replace(/(\r\n|\n|\r)/g, '\n');
}
function prepareBrowserContext(
filePath: FilePath,
globals: mixed,
): {|ctx: vm$Context, promises: Array<Promise<mixed>>|} {
// for testing dynamic imports
const fakeElement = {
remove() {},
};
let promises = [];
const fakeDocument = {
createElement(tag) {
return {tag};
},
getElementsByTagName() {
return [
{
appendChild(el) {
let {deferred, promise} = makeDeferredWithPromise();
promises.push(promise);
setTimeout(function() {
if (el.tag === 'script') {
vm.runInContext(
overlayFS.readFileSync(
path.join(path.dirname(filePath), el.src),
'utf8',
),
ctx,
);
}
el.onload();
deferred.resolve();
}, 0);
},
},
];
},
getElementById() {
return fakeElement;
},
body: {
appendChild() {
return null;
},
},
};
var exports = {};
var ctx = Object.assign(
{
exports,
module: {exports},
document: fakeDocument,
WebSocket,
console,
location: {hostname: 'localhost'},
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');
},
},
globals,
);
ctx.window = ctx;
return {ctx, promises};
}
const nodeCache = {};
function prepareNodeContext(filePath, globals) {
let exports = {};
let req = specifier => {
// $FlowFixMe
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) {
return require(specifier);
}
if (nodeCache[res]) {
return nodeCache[res].module.exports;
}
let ctx = prepareNodeContext(res, globals);
nodeCache[res] = ctx;
vm.createContext(ctx);
vm.runInContext(overlayFS.readFileSync(res, 'utf8'), ctx);
return ctx.module.exports;
};
var ctx = Object.assign(
{
module: {exports, require: req},
exports,
__filename: filePath,
__dirname: path.dirname(filePath),
require: req,
console,
process: process,
setTimeout: setTimeout,
setImmediate: setImmediate,
},
globals,
);
ctx.global = ctx;
return ctx;
}
export function shallowEqual(
a: $Shape<{|+[string]: mixed|}>,
b: $Shape<{|+[string]: mixed|}>,
) {
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;
}