/
BundleGraphRequest.js
469 lines (417 loc) Β· 13.6 KB
/
BundleGraphRequest.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
// @flow strict-local
import type {Async, Bundle as IBundle, Namer} from '@parcel/types';
import type {SharedReference} from '@parcel/workers';
import type ParcelConfig, {LoadedPlugin} from '../ParcelConfig';
import type {StaticRunOpts, RunAPI} from '../RequestTracker';
import type {
Asset,
AssetGroup,
Bundle as InternalBundle,
Config,
DevDepRequest,
ParcelOptions,
} from '../types';
import type {ConfigAndCachePath} from './ParcelConfigRequest';
import type {AbortSignal} from 'abortcontroller-polyfill/dist/cjs-ponyfill';
import invariant from 'assert';
import assert from 'assert';
import nullthrows from 'nullthrows';
import {PluginLogger} from '@parcel/logger';
import ThrowableDiagnostic, {errorToDiagnostic} from '@parcel/diagnostic';
import AssetGraph from '../AssetGraph';
import BundleGraph from '../public/BundleGraph';
import InternalBundleGraph, {bundleGraphEdgeTypes} from '../BundleGraph';
import MutableBundleGraph from '../public/MutableBundleGraph';
import {Bundle, NamedBundle} from '../public/Bundle';
import {report} from '../ReporterRunner';
import dumpGraphToGraphViz from '../dumpGraphToGraphViz';
import {unique} from '@parcel/utils';
import {hashString} from '@parcel/hash';
import PluginOptions from '../public/PluginOptions';
import applyRuntimes from '../applyRuntimes';
import {PARCEL_VERSION, OPTION_CHANGE} from '../constants';
import {assertSignalNotAborted, optionsProxy} from '../utils';
import createParcelConfigRequest, {
getCachedParcelConfig,
} from './ParcelConfigRequest';
import {
createDevDependency,
getDevDepRequests,
invalidateDevDeps,
runDevDepRequest,
} from './DevDepRequest';
import {createConfig} from '../InternalConfig';
import {
loadPluginConfig,
runConfigRequest,
type PluginWithLoadConfig,
} from './ConfigRequest';
import {
joinProjectPath,
fromProjectPathRelative,
toProjectPathUnsafe,
} from '../projectPath';
import createAssetGraphRequest from './AssetGraphRequest';
type BundleGraphRequestInput = {|
requestedAssetIds: Set<string>,
signal?: AbortSignal,
optionsRef: SharedReference,
|};
type BundleGraphRequestResult = {|
bundleGraph: InternalBundleGraph,
|};
type RunInput = {|
input: BundleGraphRequestInput,
...StaticRunOpts,
|};
type BundleGraphResult = {|
bundleGraph: InternalBundleGraph,
changedAssets: Map<string, Asset>,
assetRequests: Array<AssetGroup>,
|};
type BundleGraphRequest = {|
id: string,
+type: 'bundle_graph_request',
run: RunInput => Async<BundleGraphResult>,
input: BundleGraphRequestInput,
|};
export default function createBundleGraphRequest(
input: BundleGraphRequestInput,
): BundleGraphRequest {
return {
type: 'bundle_graph_request',
id: 'BundleGraph',
run: async input => {
let {options, api, invalidateReason} = input;
let {optionsRef, requestedAssetIds, signal} = input.input;
let request = createAssetGraphRequest({
name: 'Main',
entries: options.entries,
optionsRef,
shouldBuildLazily: options.shouldBuildLazily,
requestedAssetIds,
});
let {assetGraph, changedAssets, assetRequests} = await api.runRequest(
request,
{
force: options.shouldBuildLazily && requestedAssetIds.size > 0,
},
);
assertSignalNotAborted(signal);
// If any subrequests are invalid (e.g. dev dep requests or config requests),
// bail on incremental bundling. We also need to invalidate for option changes,
// which are hoisted to direct invalidations on the bundle graph request.
let subRequestsInvalid =
Boolean(invalidateReason & OPTION_CHANGE) ||
input.api
.getSubRequests()
.some(req => !input.api.canSkipSubrequest(req.id));
if (subRequestsInvalid) {
assetGraph.safeToIncrementallyBundle = false;
}
let configResult = nullthrows(
await input.api.runRequest<null, ConfigAndCachePath>(
createParcelConfigRequest(),
),
);
assertSignalNotAborted(signal);
let parcelConfig = getCachedParcelConfig(configResult, input.options);
let {devDeps, invalidDevDeps} = await getDevDepRequests(input.api);
invalidateDevDeps(invalidDevDeps, input.options, parcelConfig);
let builder = new BundlerRunner(input, parcelConfig, devDeps);
let res: BundleGraphResult = await builder.bundle({
graph: assetGraph,
changedAssets: changedAssets,
assetRequests,
});
for (let [id, asset] of changedAssets) {
res.changedAssets.set(id, asset);
}
dumpGraphToGraphViz(
// $FlowFixMe Added in Flow 0.121.0 upgrade in #4381 (Windows only)
res.bundleGraph._graph,
'BundleGraph',
bundleGraphEdgeTypes,
);
return res;
},
input,
};
}
class BundlerRunner {
options: ParcelOptions;
optionsRef: SharedReference;
config: ParcelConfig;
pluginOptions: PluginOptions;
api: RunAPI;
previousDevDeps: Map<string, string>;
devDepRequests: Map<string, DevDepRequest>;
configs: Map<string, Config>;
cacheKey: string;
constructor(
{input, api, options}: RunInput,
config: ParcelConfig,
previousDevDeps: Map<string, string>,
) {
this.options = options;
this.api = api;
this.optionsRef = input.optionsRef;
this.config = config;
this.previousDevDeps = previousDevDeps;
this.devDepRequests = new Map();
this.configs = new Map();
this.pluginOptions = new PluginOptions(
optionsProxy(this.options, api.invalidateOnOptionChange),
);
this.cacheKey = hashString(
`${PARCEL_VERSION}:BundleGraph:${JSON.stringify(options.entries) ?? ''}${
options.mode
}`,
);
}
async loadConfigs() {
// Load all configs up front so we can use them in the cache key
let bundler = await this.config.getBundler();
await this.loadConfig(bundler);
let namers = await this.config.getNamers();
for (let namer of namers) {
await this.loadConfig(namer);
}
let runtimes = await this.config.getRuntimes();
for (let runtime of runtimes) {
await this.loadConfig(runtime);
}
}
async loadConfig<T: PluginWithLoadConfig>(plugin: LoadedPlugin<T>) {
let config = createConfig({
plugin: plugin.name,
searchPath: toProjectPathUnsafe('index'),
});
await loadPluginConfig(plugin, config, this.options);
await runConfigRequest(this.api, config);
for (let devDep of config.devDeps) {
let devDepRequest = await createDevDependency(
devDep,
this.previousDevDeps,
this.options,
);
await this.runDevDepRequest(devDepRequest);
}
this.configs.set(plugin.name, config);
}
async runDevDepRequest(devDepRequest: DevDepRequest) {
let {specifier, resolveFrom} = devDepRequest;
let key = `${specifier}:${fromProjectPathRelative(resolveFrom)}`;
this.devDepRequests.set(key, devDepRequest);
await runDevDepRequest(this.api, devDepRequest);
}
async bundle({
graph,
changedAssets,
assetRequests,
}: {|
graph: AssetGraph,
changedAssets: Map<string, Asset>,
assetRequests: Array<AssetGroup>,
|}): Promise<BundleGraphResult> {
report({
type: 'buildProgress',
phase: 'bundling',
});
await this.loadConfigs();
let plugin = await this.config.getBundler();
let {plugin: bundler, name, resolveFrom} = plugin;
// if a previous asset graph hash is passed in, check if the bundle graph is also available
let previousBundleGraphResult: ?BundleGraphRequestResult;
if (graph.safeToIncrementallyBundle) {
try {
previousBundleGraphResult = await this.api.getPreviousResult();
} catch {
// if the bundle graph had an error or was removed, don't fail the build
}
}
if (previousBundleGraphResult == null) {
graph.safeToIncrementallyBundle = false;
}
let internalBundleGraph;
let logger = new PluginLogger({origin: name});
try {
if (previousBundleGraphResult) {
internalBundleGraph = previousBundleGraphResult.bundleGraph;
for (let changedAsset of changedAssets.values()) {
internalBundleGraph.updateAsset(changedAsset);
}
} else {
internalBundleGraph = InternalBundleGraph.fromAssetGraph(graph);
invariant(internalBundleGraph != null); // ensures the graph was created
await dumpGraphToGraphViz(
// $FlowFixMe
internalBundleGraph._graph,
'before_bundle',
bundleGraphEdgeTypes,
);
let mutableBundleGraph = new MutableBundleGraph(
internalBundleGraph,
this.options,
);
// this the normal bundle workflow (bundle, optimizing, run-times, naming)
await bundler.bundle({
bundleGraph: mutableBundleGraph,
config: this.configs.get(plugin.name)?.result,
options: this.pluginOptions,
logger,
});
if (this.pluginOptions.mode === 'production') {
try {
await bundler.optimize({
bundleGraph: mutableBundleGraph,
config: this.configs.get(plugin.name)?.result,
options: this.pluginOptions,
logger,
});
} catch (e) {
throw new ThrowableDiagnostic({
diagnostic: errorToDiagnostic(e, {
origin: plugin.name,
}),
});
} finally {
await dumpGraphToGraphViz(
// $FlowFixMe[incompatible-call]
internalBundleGraph._graph,
'after_optimize',
);
}
}
// Add dev dependency for the bundler. This must be done AFTER running it due to
// the potential for lazy require() that aren't executed until the request runs.
let devDepRequest = await createDevDependency(
{
specifier: name,
resolveFrom,
},
this.previousDevDeps,
this.options,
);
await this.runDevDepRequest(devDepRequest);
}
} catch (e) {
throw new ThrowableDiagnostic({
diagnostic: errorToDiagnostic(e, {
origin: name,
}),
});
} finally {
invariant(internalBundleGraph != null); // ensures the graph was created
await dumpGraphToGraphViz(
// $FlowFixMe[incompatible-call]
internalBundleGraph._graph,
'after_bundle',
bundleGraphEdgeTypes,
);
}
let changedRuntimes = new Map();
if (!previousBundleGraphResult) {
await this.nameBundles(internalBundleGraph);
changedRuntimes = await applyRuntimes({
bundleGraph: internalBundleGraph,
api: this.api,
config: this.config,
options: this.options,
optionsRef: this.optionsRef,
pluginOptions: this.pluginOptions,
previousDevDeps: this.previousDevDeps,
devDepRequests: this.devDepRequests,
configs: this.configs,
});
// Pre-compute the hashes for each bundle so they are only computed once and shared between workers.
internalBundleGraph.getBundleGraphHash();
}
await dumpGraphToGraphViz(
// $FlowFixMe
internalBundleGraph._graph,
'after_runtimes',
bundleGraphEdgeTypes,
);
this.api.storeResult(
{
bundleGraph: internalBundleGraph,
changedAssets: new Map(),
assetRequests: [],
},
this.cacheKey,
);
return {
bundleGraph: internalBundleGraph,
changedAssets: changedRuntimes,
assetRequests,
};
}
async nameBundles(bundleGraph: InternalBundleGraph): Promise<void> {
let namers = await this.config.getNamers();
// inline bundles must still be named so the PackagerRunner
// can match them to the correct packager/optimizer plugins.
let bundles = bundleGraph.getBundles({includeInline: true});
await Promise.all(
bundles.map(bundle => this.nameBundle(namers, bundle, bundleGraph)),
);
// Add dev deps for namers, AFTER running them to account for lazy require().
for (let namer of namers) {
let devDepRequest = await createDevDependency(
{
specifier: namer.name,
resolveFrom: namer.resolveFrom,
},
this.previousDevDeps,
this.options,
);
await this.runDevDepRequest(devDepRequest);
}
let bundleNames = bundles.map(b =>
joinProjectPath(b.target.distDir, nullthrows(b.name)),
);
assert.deepEqual(
bundleNames,
unique(bundleNames),
'Bundles must have unique names',
);
}
async nameBundle(
namers: Array<LoadedPlugin<Namer<mixed>>>,
internalBundle: InternalBundle,
internalBundleGraph: InternalBundleGraph,
): Promise<void> {
let bundle = Bundle.get(internalBundle, internalBundleGraph, this.options);
let bundleGraph = new BundleGraph<IBundle>(
internalBundleGraph,
NamedBundle.get.bind(NamedBundle),
this.options,
);
for (let namer of namers) {
try {
let name = await namer.plugin.name({
bundle,
bundleGraph,
config: this.configs.get(namer.name)?.result,
options: this.pluginOptions,
logger: new PluginLogger({origin: namer.name}),
});
if (name != null) {
internalBundle.name = name;
let {hashReference} = internalBundle;
internalBundle.displayName = name.includes(hashReference)
? name.replace(hashReference, '[hash]')
: name;
return;
}
} catch (e) {
throw new ThrowableDiagnostic({
diagnostic: errorToDiagnostic(e, {
origin: namer.name,
}),
});
}
}
throw new Error('Unable to name bundle');
}
}