-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
AssetGraphRequest.js
532 lines (480 loc) Β· 17.5 KB
/
AssetGraphRequest.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
// @flow strict-local
import type {NodeId} from '@parcel/graph';
import type {Async} from '@parcel/types';
import type {SharedReference} from '@parcel/workers';
import type {
Asset,
AssetGroup,
AssetRequestInput,
Dependency,
Entry,
ParcelOptions,
Target,
} from '../types';
import type {StaticRunOpts, RunAPI} from '../RequestTracker';
import type {EntryResult} from './EntryRequest';
import type {PathRequestInput} from './PathRequest';
import type {Diagnostic} from '@parcel/diagnostic';
import invariant from 'assert';
import nullthrows from 'nullthrows';
import {PromiseQueue, setEqual} from '@parcel/utils';
import {hashString} from '@parcel/rust';
import ThrowableDiagnostic from '@parcel/diagnostic';
import {Priority} from '../types';
import AssetGraph from '../AssetGraph';
import {PARCEL_VERSION} from '../constants';
import createEntryRequest from './EntryRequest';
import createTargetRequest from './TargetRequest';
import createAssetRequest from './AssetRequest';
import createPathRequest from './PathRequest';
import {type ProjectPath, fromProjectPathRelative} from '../projectPath';
import dumpGraphToGraphViz from '../dumpGraphToGraphViz';
import {propagateSymbols} from '../SymbolPropagation';
type AssetGraphRequestInput = {|
entries?: Array<ProjectPath>,
assetGroups?: Array<AssetGroup>,
optionsRef: SharedReference,
name: string,
shouldBuildLazily?: boolean,
lazyIncludes?: RegExp[],
lazyExcludes?: RegExp[],
requestedAssetIds?: Set<string>,
|};
type AssetGraphRequestResult = {|
assetGraph: AssetGraph,
/** Assets added/modified since the last successful build. */
changedAssets: Map<string, Asset>,
/** Assets added/modified since the last symbol propagation invocation. */
changedAssetsPropagation: Set<string>,
assetGroupsWithRemovedParents: ?Set<NodeId>,
previousSymbolPropagationErrors: ?Map<NodeId, Array<Diagnostic>>,
assetRequests: Array<AssetGroup>,
|};
type RunInput = {|
input: AssetGraphRequestInput,
...StaticRunOpts<AssetGraphRequestResult>,
|};
type AssetGraphRequest = {|
id: string,
+type: 'asset_graph_request',
run: RunInput => Async<AssetGraphRequestResult>,
input: AssetGraphRequestInput,
|};
export default function createAssetGraphRequest(
input: AssetGraphRequestInput,
): AssetGraphRequest {
return {
type: 'asset_graph_request',
id: input.name,
run: async input => {
let prevResult =
await input.api.getPreviousResult<AssetGraphRequestResult>();
let builder = new AssetGraphBuilder(input, prevResult);
let assetGraphRequest = await await builder.build();
// early break for incremental bundling if production or flag is off;
if (
!input.options.shouldBundleIncrementally ||
input.options.mode === 'production'
) {
assetGraphRequest.assetGraph.safeToIncrementallyBundle = false;
}
return assetGraphRequest;
},
input,
};
}
const typesWithRequests = new Set([
'entry_specifier',
'entry_file',
'dependency',
'asset_group',
]);
export class AssetGraphBuilder {
assetGraph: AssetGraph;
assetRequests: Array<AssetGroup> = [];
queue: PromiseQueue<mixed>;
changedAssets: Map<string, Asset>;
changedAssetsPropagation: Set<string>;
optionsRef: SharedReference;
options: ParcelOptions;
api: RunAPI<AssetGraphRequestResult>;
name: string;
cacheKey: string;
shouldBuildLazily: boolean;
lazyIncludes: RegExp[];
lazyExcludes: RegExp[];
requestedAssetIds: Set<string>;
isSingleChangeRebuild: boolean;
assetGroupsWithRemovedParents: Set<NodeId>;
previousSymbolPropagationErrors: Map<NodeId, Array<Diagnostic>>;
constructor(
{input, api, options}: RunInput,
prevResult: ?AssetGraphRequestResult,
) {
let {
entries,
assetGroups,
optionsRef,
name,
requestedAssetIds,
shouldBuildLazily,
lazyIncludes,
lazyExcludes,
} = input;
let assetGraph = prevResult?.assetGraph ?? new AssetGraph();
assetGraph.safeToIncrementallyBundle = true;
assetGraph.setRootConnections({
entries,
assetGroups,
});
this.assetGroupsWithRemovedParents =
prevResult?.assetGroupsWithRemovedParents ?? new Set();
this.previousSymbolPropagationErrors =
prevResult?.previousSymbolPropagationErrors ?? new Map();
this.changedAssets = prevResult?.changedAssets ?? new Map();
this.changedAssetsPropagation =
prevResult?.changedAssetsPropagation ?? new Set();
this.assetGraph = assetGraph;
this.optionsRef = optionsRef;
this.options = options;
this.api = api;
this.name = name;
this.requestedAssetIds = requestedAssetIds ?? new Set();
this.shouldBuildLazily = shouldBuildLazily ?? false;
this.lazyIncludes = lazyIncludes ?? [];
this.lazyExcludes = lazyExcludes ?? [];
this.cacheKey = hashString(
`${PARCEL_VERSION}${name}${JSON.stringify(entries) ?? ''}${options.mode}`,
);
this.isSingleChangeRebuild =
api.getInvalidSubRequests().filter(req => req.type === 'asset_request')
.length === 1;
this.queue = new PromiseQueue();
assetGraph.onNodeRemoved = nodeId => {
this.assetGroupsWithRemovedParents.delete(nodeId);
// This needs to mark all connected nodes that doesn't become orphaned
// due to replaceNodesConnectedTo to make sure that the symbols of
// nodes from which at least one parent was removed are updated.
let node = nullthrows(assetGraph.getNode(nodeId));
if (assetGraph.isOrphanedNode(nodeId) && node.type === 'dependency') {
let children = assetGraph.getNodeIdsConnectedFrom(nodeId);
for (let child of children) {
let childNode = nullthrows(assetGraph.getNode(child));
invariant(
childNode.type === 'asset_group' || childNode.type === 'asset',
);
childNode.usedSymbolsDownDirty = true;
this.assetGroupsWithRemovedParents.add(child);
}
}
};
}
async build(): Promise<AssetGraphRequestResult> {
let errors = [];
let rootNodeId = nullthrows(
this.assetGraph.rootNodeId,
'A root node is required to traverse',
);
let visited = new Set([rootNodeId]);
const visit = (nodeId: NodeId) => {
if (errors.length > 0) {
return;
}
if (this.shouldSkipRequest(nodeId)) {
visitChildren(nodeId);
} else {
// ? do we need to visit children inside of the promise that is queued?
this.queueCorrespondingRequest(nodeId, errors).then(() =>
visitChildren(nodeId),
);
}
};
const visitChildren = (nodeId: NodeId) => {
for (let childNodeId of this.assetGraph.getNodeIdsConnectedFrom(nodeId)) {
let child = nullthrows(this.assetGraph.getNode(childNodeId));
if (
(!visited.has(childNodeId) || child.hasDeferred) &&
this.shouldVisitChild(nodeId, childNodeId)
) {
visited.add(childNodeId);
visit(childNodeId);
}
}
};
visit(rootNodeId);
await this.queue.run();
if (errors.length) {
this.api.storeResult(
{
assetGraph: this.assetGraph,
changedAssets: this.changedAssets,
changedAssetsPropagation: this.changedAssetsPropagation,
assetGroupsWithRemovedParents: this.assetGroupsWithRemovedParents,
previousSymbolPropagationErrors: undefined,
assetRequests: [],
},
this.cacheKey,
);
// TODO: eventually support multiple errors since requests could reject in parallel
throw errors[0];
}
if (this.assetGraph.nodes.length > 1) {
await dumpGraphToGraphViz(
this.assetGraph,
'AssetGraph_' + this.name + '_before_prop',
);
try {
let errors = propagateSymbols({
options: this.options,
assetGraph: this.assetGraph,
changedAssetsPropagation: this.changedAssetsPropagation,
assetGroupsWithRemovedParents: this.assetGroupsWithRemovedParents,
previousErrors: this.previousSymbolPropagationErrors,
});
this.changedAssetsPropagation.clear();
if (errors.size > 0) {
this.api.storeResult(
{
assetGraph: this.assetGraph,
changedAssets: this.changedAssets,
changedAssetsPropagation: this.changedAssetsPropagation,
assetGroupsWithRemovedParents: this.assetGroupsWithRemovedParents,
previousSymbolPropagationErrors: errors,
assetRequests: [],
},
this.cacheKey,
);
// Just throw the first error. Since errors can bubble (e.g. reexporting a reexported symbol also fails),
// determining which failing export is the root cause is nontrivial (because of circular dependencies).
throw new ThrowableDiagnostic({
diagnostic: [...errors.values()][0],
});
}
} catch (e) {
await dumpGraphToGraphViz(
this.assetGraph,
'AssetGraph_' + this.name + '_failed',
);
throw e;
}
}
await dumpGraphToGraphViz(this.assetGraph, 'AssetGraph_' + this.name);
this.api.storeResult(
{
assetGraph: this.assetGraph,
changedAssets: new Map(),
changedAssetsPropagation: this.changedAssetsPropagation,
assetGroupsWithRemovedParents: undefined,
previousSymbolPropagationErrors: undefined,
assetRequests: [],
},
this.cacheKey,
);
return {
assetGraph: this.assetGraph,
changedAssets: this.changedAssets,
changedAssetsPropagation: this.changedAssetsPropagation,
assetGroupsWithRemovedParents: undefined,
previousSymbolPropagationErrors: undefined,
assetRequests: this.assetRequests,
};
}
shouldVisitChild(nodeId: NodeId, childNodeId: NodeId): boolean {
if (this.shouldBuildLazily) {
let node = nullthrows(this.assetGraph.getNode(nodeId));
let childNode = nullthrows(this.assetGraph.getNode(childNodeId));
if (node.type === 'asset' && childNode.type === 'dependency') {
// This logic will set `node.requested` to `true` if the node is in the list of requested asset ids
// (i.e. this is an entry of a (probably) placeholder bundle that wasn't previously requested)
//
// Otherwise, if this node either is explicitly not requested, or has had it's requested attribute deleted,
// it will determine whether this node is an "async child" - that is, is it a (probably)
// dynamic import(). If so, it will explicitly have it's `node.requested` set to `false`
//
// If it's not requested, but it's not an async child then it's `node.requested` is deleted (undefined)
// by default with lazy compilation all nodes are lazy
let isNodeLazy = true;
// For conditional lazy building - if this node matches the `lazyInclude` globs that means we want
// only those nodes to be treated as lazy - that means if this node does _NOT_ match that glob, then we
// also consider it not lazy (so it gets marked as requested).
const relativePath = fromProjectPathRelative(node.value.filePath);
if (this.lazyIncludes.length > 0) {
isNodeLazy = this.lazyIncludes.some(lazyIncludeRegex =>
relativePath.match(lazyIncludeRegex),
);
}
// Excludes override includes, so a node is _not_ lazy if it is included in the exclude list.
if (this.lazyExcludes.length > 0 && isNodeLazy) {
isNodeLazy = !this.lazyExcludes.some(lazyExcludeRegex =>
relativePath.match(lazyExcludeRegex),
);
}
if (this.requestedAssetIds.has(node.value.id) || !isNodeLazy) {
node.requested = true;
} else if (!node.requested) {
let isAsyncChild = this.assetGraph
.getIncomingDependencies(node.value)
.every(dep => dep.isEntry || dep.priority !== Priority.sync);
if (isAsyncChild) {
node.requested = !isNodeLazy;
} else {
delete node.requested;
}
}
let previouslyDeferred = childNode.deferred;
childNode.deferred = node.requested === false;
// The child dependency node we're now evaluating should not be deferred if it's parent
// is explicitly not requested (requested = false, but not requested = undefined)
//
// if we weren't previously deferred but we are now, then this dependency node's parents should also
// be marked as deferred
//
// if we were previously deferred but we not longer are, then then all parents should no longer be
// deferred either
if (!previouslyDeferred && childNode.deferred) {
this.assetGraph.markParentsWithHasDeferred(childNodeId);
} else if (previouslyDeferred && !childNode.deferred) {
this.assetGraph.unmarkParentsWithHasDeferred(childNodeId);
}
// We `shouldVisitChild` if the childNode is not deferred
return !childNode.deferred;
}
}
return this.assetGraph.shouldVisitChild(nodeId, childNodeId);
}
shouldSkipRequest(nodeId: NodeId): boolean {
let node = nullthrows(this.assetGraph.getNode(nodeId));
return (
node.complete === true ||
!typesWithRequests.has(node.type) ||
(node.correspondingRequest != null &&
this.api.canSkipSubrequest(node.correspondingRequest))
);
}
queueCorrespondingRequest(
nodeId: NodeId,
errors: Array<Error>,
): Promise<mixed> {
let promise;
let node = nullthrows(this.assetGraph.getNode(nodeId));
switch (node.type) {
case 'entry_specifier':
promise = this.runEntryRequest(node.value);
break;
case 'entry_file':
promise = this.runTargetRequest(node.value);
break;
case 'dependency':
promise = this.runPathRequest(node.value);
break;
case 'asset_group':
promise = this.runAssetRequest(node.value);
break;
default:
throw new Error(
`Can not queue corresponding request of node with type ${node.type}`,
);
}
return this.queue.add(() =>
promise.then(null, error => errors.push(error)),
);
}
async runEntryRequest(input: ProjectPath) {
let prevEntries = this.assetGraph.safeToIncrementallyBundle
? this.assetGraph
.getEntryAssets()
.map(asset => asset.id)
.sort()
: [];
let request = createEntryRequest(input);
let result = await this.api.runRequest<ProjectPath, EntryResult>(request, {
force: true,
});
this.assetGraph.resolveEntry(request.input, result.entries, request.id);
if (this.assetGraph.safeToIncrementallyBundle) {
let currentEntries = this.assetGraph
.getEntryAssets()
.map(asset => asset.id)
.sort();
let didEntriesChange =
prevEntries.length !== currentEntries.length ||
prevEntries.every(
(entryId, index) => entryId === currentEntries[index],
);
if (didEntriesChange) {
this.assetGraph.safeToIncrementallyBundle = false;
}
}
}
async runTargetRequest(input: Entry) {
let request = createTargetRequest(input);
let targets = await this.api.runRequest<Entry, Array<Target>>(request, {
force: true,
});
this.assetGraph.resolveTargets(request.input, targets, request.id);
}
async runPathRequest(input: Dependency) {
let request = createPathRequest({dependency: input, name: this.name});
let result = await this.api.runRequest<PathRequestInput, ?AssetGroup>(
request,
{force: true},
);
this.assetGraph.resolveDependency(input, result, request.id);
}
async runAssetRequest(input: AssetGroup) {
this.assetRequests.push(input);
let request = createAssetRequest({
...input,
name: this.name,
optionsRef: this.optionsRef,
isSingleChangeRebuild: this.isSingleChangeRebuild,
});
let assets = await this.api.runRequest<AssetRequestInput, Array<Asset>>(
request,
{force: true},
);
if (assets != null) {
for (let asset of assets) {
if (this.assetGraph.safeToIncrementallyBundle) {
let otherAsset = this.assetGraph.getNodeByContentKey(asset.id);
if (otherAsset != null) {
invariant(otherAsset.type === 'asset');
if (!this._areDependenciesEqualForAssets(asset, otherAsset.value)) {
this.assetGraph.safeToIncrementallyBundle = false;
}
} else {
// adding a new entry or dependency
this.assetGraph.safeToIncrementallyBundle = false;
}
}
this.changedAssets.set(asset.id, asset);
this.changedAssetsPropagation.add(asset.id);
}
this.assetGraph.resolveAssetGroup(input, assets, request.id);
} else {
this.assetGraph.safeToIncrementallyBundle = false;
}
this.isSingleChangeRebuild = false;
}
/**
* Used for incremental bundling of modified assets
*/
_areDependenciesEqualForAssets(asset: Asset, otherAsset: Asset): boolean {
let assetDependencies = Array.from(asset?.dependencies.keys()).sort();
let otherAssetDependencies = Array.from(
otherAsset?.dependencies.keys(),
).sort();
if (assetDependencies.length !== otherAssetDependencies.length) {
return false;
}
return assetDependencies.every((key, index) => {
if (key !== otherAssetDependencies[index]) {
return false;
}
return setEqual(
new Set(asset?.dependencies.get(key)?.symbols?.keys()),
new Set(otherAsset?.dependencies.get(key)?.symbols?.keys()),
);
});
}
}