-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Parcel.js
452 lines (387 loc) Β· 12.7 KB
/
Parcel.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
// @flow strict-local
import type {
AsyncSubscription,
BuildEvent,
BuildSuccessEvent,
InitialParcelOptions,
PackagedBundle as IPackagedBundle,
} from '@parcel/types';
import type {ParcelOptions} from './types';
// eslint-disable-next-line no-unused-vars
import type {FarmOptions, SharedReference} from '@parcel/workers';
import type {Diagnostic} from '@parcel/diagnostic';
import type {AbortSignal} from 'abortcontroller-polyfill/dist/cjs-ponyfill';
import invariant from 'assert';
import ThrowableDiagnostic, {anyToDiagnostic} from '@parcel/diagnostic';
import {assetFromValue} from './public/Asset';
import {PackagedBundle} from './public/Bundle';
import BundleGraph from './public/BundleGraph';
import WorkerFarm from '@parcel/workers';
import nullthrows from 'nullthrows';
import {BuildAbortError} from './utils';
import {loadParcelConfig} from './requests/ParcelConfigRequest';
import ReporterRunner from './ReporterRunner';
import dumpGraphToGraphViz from './dumpGraphToGraphViz';
import resolveOptions from './resolveOptions';
import {ValueEmitter} from '@parcel/events';
import {registerCoreWithSerializer} from './utils';
import {AbortController} from 'abortcontroller-polyfill/dist/cjs-ponyfill';
import {PromiseQueue} from '@parcel/utils';
import ParcelConfig from './ParcelConfig';
import logger from '@parcel/logger';
import RequestTracker, {
getWatcherOptions,
requestGraphEdgeTypes,
} from './RequestTracker';
import createValidationRequest from './requests/ValidationRequest';
import createParcelBuildRequest from './requests/ParcelBuildRequest';
import {Disposable} from '@parcel/events';
import {init as initSourcemaps} from '@parcel/source-map';
import {init as initHash} from '@parcel/hash';
import {toProjectPath} from './projectPath';
registerCoreWithSerializer();
export const INTERNAL_TRANSFORM: symbol = Symbol('internal_transform');
export const INTERNAL_RESOLVE: symbol = Symbol('internal_resolve');
export default class Parcel {
#requestTracker /*: RequestTracker*/;
#config /*: ParcelConfig*/;
#farm /*: WorkerFarm*/;
#initialized /*: boolean*/ = false;
#disposable /*: Disposable */;
#initialOptions /*: InitialParcelOptions*/;
#reporterRunner /*: ReporterRunner*/;
#resolvedOptions /*: ?ParcelOptions*/ = null;
#optionsRef /*: SharedReference */;
#watchAbortController /*: AbortController*/;
#watchQueue /*: PromiseQueue<?BuildEvent>*/ = new PromiseQueue<?BuildEvent>({
maxConcurrent: 1,
});
#watchEvents /*: ValueEmitter<
| {|
+error: Error,
+buildEvent?: void,
|}
| {|
+buildEvent: BuildEvent,
+error?: void,
|},
> */;
#watcherSubscription /*: ?AsyncSubscription*/;
#watcherCount /*: number*/ = 0;
#requestedAssetIds /*: Set<string>*/ = new Set();
isProfiling /*: boolean */;
constructor(options: InitialParcelOptions) {
this.#initialOptions = options;
}
async _init(): Promise<void> {
if (this.#initialized) {
return;
}
await initSourcemaps;
await initHash;
let resolvedOptions: ParcelOptions = await resolveOptions(
this.#initialOptions,
);
this.#resolvedOptions = resolvedOptions;
let {config} = await loadParcelConfig(resolvedOptions);
this.#config = new ParcelConfig(config, resolvedOptions);
if (this.#initialOptions.workerFarm) {
if (this.#initialOptions.workerFarm.ending) {
throw new Error('Supplied WorkerFarm is ending');
}
this.#farm = this.#initialOptions.workerFarm;
} else {
this.#farm = createWorkerFarm({
shouldPatchConsole: resolvedOptions.shouldPatchConsole,
});
}
await resolvedOptions.cache.ensure();
let {
dispose: disposeOptions,
ref: optionsRef,
} = await this.#farm.createSharedReference(resolvedOptions);
this.#optionsRef = optionsRef;
this.#disposable = new Disposable();
if (this.#initialOptions.workerFarm) {
// If we don't own the farm, dispose of only these references when
// Parcel ends.
this.#disposable.add(disposeOptions);
} else {
// Otherwise, when shutting down, end the entire farm we created.
this.#disposable.add(() => this.#farm.end());
}
this.#watchEvents = new ValueEmitter();
this.#disposable.add(() => this.#watchEvents.dispose());
this.#requestTracker = await RequestTracker.init({
farm: this.#farm,
options: resolvedOptions,
});
this.#reporterRunner = new ReporterRunner({
config: this.#config,
options: resolvedOptions,
workerFarm: this.#farm,
});
this.#disposable.add(this.#reporterRunner);
this.#initialized = true;
}
async run(): Promise<BuildSuccessEvent> {
let startTime = Date.now();
if (!this.#initialized) {
await this._init();
}
let result = await this._build({startTime});
await this._end();
if (result.type === 'buildFailure') {
throw new BuildError(result.diagnostics);
}
return result;
}
async _end(): Promise<void> {
this.#initialized = false;
await Promise.all([
this.#disposable.dispose(),
await this.#requestTracker.writeToCache(),
]);
await this.#farm.callAllWorkers('clearConfigCache', []);
}
async _startNextBuild(): Promise<?BuildEvent> {
this.#watchAbortController = new AbortController();
await this.#farm.callAllWorkers('clearConfigCache', []);
try {
let buildEvent = await this._build({
signal: this.#watchAbortController.signal,
});
this.#watchEvents.emit({
buildEvent,
});
return buildEvent;
} catch (err) {
// Ignore BuildAbortErrors and only emit critical errors.
if (!(err instanceof BuildAbortError)) {
throw err;
}
}
}
async watch(
cb?: (err: ?Error, buildEvent?: BuildEvent) => mixed,
): Promise<AsyncSubscription> {
if (!this.#initialized) {
await this._init();
}
let watchEventsDisposable;
if (cb) {
watchEventsDisposable = this.#watchEvents.addListener(
({error, buildEvent}) => cb(error, buildEvent),
);
}
if (this.#watcherCount === 0) {
this.#watcherSubscription = await this._getWatcherSubscription();
await this.#reporterRunner.report({type: 'watchStart'});
// Kick off a first build, but don't await its results. Its results will
// be provided to the callback.
this.#watchQueue.add(() => this._startNextBuild());
this.#watchQueue.run();
}
this.#watcherCount++;
let unsubscribePromise;
const unsubscribe = async () => {
if (watchEventsDisposable) {
watchEventsDisposable.dispose();
}
this.#watcherCount--;
if (this.#watcherCount === 0) {
await nullthrows(this.#watcherSubscription).unsubscribe();
this.#watcherSubscription = null;
await this.#reporterRunner.report({type: 'watchEnd'});
this.#watchAbortController.abort();
await this.#watchQueue.run();
await this._end();
}
};
return {
unsubscribe() {
if (unsubscribePromise == null) {
unsubscribePromise = unsubscribe();
}
return unsubscribePromise;
},
};
}
async _build({
signal,
startTime = Date.now(),
}: {|
signal?: AbortSignal,
startTime?: number,
|} = {}): Promise<BuildEvent> {
this.#requestTracker.setSignal(signal);
let options = nullthrows(this.#resolvedOptions);
try {
if (options.shouldProfile) {
await this.startProfiling();
}
this.#reporterRunner.report({
type: 'buildStart',
});
let request = createParcelBuildRequest({
optionsRef: this.#optionsRef,
requestedAssetIds: this.#requestedAssetIds,
signal,
});
let {
bundleGraph,
bundleInfo,
changedAssets,
assetRequests,
} = await this.#requestTracker.runRequest(request, {force: true});
this.#requestedAssetIds.clear();
dumpGraphToGraphViz(
// $FlowFixMe
this.#requestTracker.graph,
'RequestGraph',
requestGraphEdgeTypes,
);
let event = {
type: 'buildSuccess',
changedAssets: new Map(
Array.from(changedAssets).map(([id, asset]) => [
id,
assetFromValue(asset, options),
]),
),
bundleGraph: new BundleGraph<IPackagedBundle>(
bundleGraph,
(bundle, bundleGraph, options) =>
PackagedBundle.getWithInfo(
bundle,
bundleGraph,
options,
bundleInfo.get(bundle.id),
),
options,
),
buildTime: Date.now() - startTime,
requestBundle: async bundle => {
let bundleNode = bundleGraph._graph.getNodeByContentKey(bundle.id);
invariant(bundleNode?.type === 'bundle', 'Bundle does not exist');
if (!bundleNode.value.isPlaceholder) {
// Nothing to do.
return {
type: 'buildSuccess',
changedAssets: new Map(),
bundleGraph: event.bundleGraph,
buildTime: 0,
requestBundle: event.requestBundle,
};
}
for (let assetId of bundleNode.value.entryAssetIds) {
this.#requestedAssetIds.add(assetId);
}
if (this.#watchQueue.getNumWaiting() === 0) {
if (this.#watchAbortController) {
this.#watchAbortController.abort();
}
this.#watchQueue.add(() => this._startNextBuild());
}
let results = await this.#watchQueue.run();
let result = results.filter(Boolean).pop();
if (result.type === 'buildFailure') {
throw new BuildError(result.diagnostics);
}
return result;
},
};
await this.#reporterRunner.report(event);
await this.#requestTracker.runRequest(
createValidationRequest({optionsRef: this.#optionsRef, assetRequests}),
{force: assetRequests.length > 0},
);
return event;
} catch (e) {
if (e instanceof BuildAbortError) {
throw e;
}
let diagnostic = anyToDiagnostic(e);
let event = {
type: 'buildFailure',
diagnostics: Array.isArray(diagnostic) ? diagnostic : [diagnostic],
};
await this.#reporterRunner.report(event);
return event;
} finally {
if (this.isProfiling) {
await this.stopProfiling();
}
}
}
async _getWatcherSubscription(): Promise<AsyncSubscription> {
invariant(this.#watcherSubscription == null);
let resolvedOptions = nullthrows(this.#resolvedOptions);
let opts = getWatcherOptions(resolvedOptions);
let sub = await resolvedOptions.inputFS.watch(
resolvedOptions.projectRoot,
(err, events) => {
if (err) {
this.#watchEvents.emit({error: err});
return;
}
let isInvalid = this.#requestTracker.respondToFSEvents(
events.map(e => ({
type: e.type,
path: toProjectPath(resolvedOptions.projectRoot, e.path),
})),
);
if (isInvalid && this.#watchQueue.getNumWaiting() === 0) {
if (this.#watchAbortController) {
this.#watchAbortController.abort();
}
this.#watchQueue.add(() => this._startNextBuild());
this.#watchQueue.run();
}
},
opts,
);
return {unsubscribe: () => sub.unsubscribe()};
}
// This is mainly for integration tests and it not public api!
_getResolvedParcelOptions(): ParcelOptions {
return nullthrows(
this.#resolvedOptions,
'Resolved options is null, please let parcel initialise before accessing this.',
);
}
async startProfiling(): Promise<void> {
if (this.isProfiling) {
throw new Error('Parcel is already profiling');
}
logger.info({origin: '@parcel/core', message: 'Starting profiling...'});
this.isProfiling = true;
await this.#farm.startProfile();
}
stopProfiling(): Promise<void> {
if (!this.isProfiling) {
throw new Error('Parcel is not profiling');
}
logger.info({origin: '@parcel/core', message: 'Stopping profiling...'});
this.isProfiling = false;
return this.#farm.endProfile();
}
takeHeapSnapshot(): Promise<void> {
logger.info({origin: '@parcel/core', message: 'Taking heap snapshot...'});
return this.#farm.takeHeapSnapshot();
}
}
export class BuildError extends ThrowableDiagnostic {
constructor(diagnostic: Array<Diagnostic> | Diagnostic) {
super({diagnostic});
this.name = 'BuildError';
}
}
export function createWorkerFarm(
options: $Shape<FarmOptions> = {},
): WorkerFarm {
return new WorkerFarm({
...options,
workerPath: require.resolve('./worker'),
});
}