/
BundleGraph.js
1732 lines (1544 loc) Β· 53 KB
/
BundleGraph.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 {
GraphVisitor,
FilePath,
Symbol,
TraversalActions,
} from '@parcel/types';
import type {
ContentGraphOpts,
NodeId,
SerializedContentGraph,
} from '@parcel/graph';
import type {
Asset,
AssetNode,
Bundle,
BundleGraphNode,
BundleGroup,
Dependency,
DependencyNode,
InternalSourceLocation,
Target,
} from './types';
import type AssetGraph from './AssetGraph';
import type {ProjectPath} from './projectPath';
import assert from 'assert';
import invariant from 'assert';
import nullthrows from 'nullthrows';
import {ContentGraph, ALL_EDGE_TYPES, mapVisitor} from '@parcel/graph';
import {Hash, hashString} from '@parcel/hash';
import {objectSortedEntriesDeep, getRootDir} from '@parcel/utils';
import {Priority, BundleBehavior, SpecifierType} from './types';
import {getBundleGroupId, getPublicId} from './utils';
import {ISOLATED_ENVS} from './public/Environment';
import {fromProjectPath} from './projectPath';
export const bundleGraphEdgeTypes = {
// A lack of an edge type indicates to follow the edge while traversing
// the bundle's contents, e.g. `bundle.traverse()` during packaging.
null: 1,
// Used for constant-time checks of presence of a dependency or asset in a bundle,
// avoiding bundle traversal in cases like `isAssetInAncestors`
contains: 2,
// Connections between bundles and bundle groups, for quick traversal of the
// bundle hierarchy.
bundle: 3,
// When dependency -> asset: Indicates that the asset a dependency references
// is contained in another bundle.
// When dependency -> bundle: Indicates the bundle is necessary for any bundles
// with the dependency.
// When bundle -> bundle: Indicates the target bundle is necessary for the
// source bundle.
// This type prevents referenced assets from being traversed from dependencies
// along the untyped edge, and enables traversal to referenced bundles that are
// not directly connected to bundle group nodes.
references: 4,
// Signals that the dependency is internally resolvable via the bundle's ancestry,
// and that the bundle connected to the dependency is not necessary for the source bundle.
internal_async: 5,
};
export type BundleGraphEdgeType = $Values<typeof bundleGraphEdgeTypes>;
type InternalSymbolResolution = {|
asset: Asset,
exportSymbol: string,
symbol: ?Symbol | false,
loc: ?InternalSourceLocation,
|};
type InternalExportSymbolResolution = {|
...InternalSymbolResolution,
+exportAs: Symbol | string,
|};
type BundleGraphOpts = {|
graph: ContentGraphOpts<BundleGraphNode, BundleGraphEdgeType>,
bundleContentHashes: Map<string, string>,
assetPublicIds: Set<string>,
publicIdByAssetId: Map<string, string>,
symbolPropagationRan: boolean,
|};
type SerializedBundleGraph = {|
$$raw: true,
graph: SerializedContentGraph<BundleGraphNode, BundleGraphEdgeType>,
bundleContentHashes: Map<string, string>,
assetPublicIds: Set<string>,
publicIdByAssetId: Map<string, string>,
symbolPropagationRan: boolean,
|};
function makeReadOnlySet<T>(set: Set<T>): $ReadOnlySet<T> {
return new Proxy(set, {
get(target, property) {
if (property === 'delete' || property === 'add' || property === 'clear') {
return undefined;
} else {
// $FlowFixMe[incompatible-type]
let value = target[property];
return typeof value === 'function' ? value.bind(target) : value;
}
},
});
}
export default class BundleGraph {
_assetPublicIds: Set<string>;
_publicIdByAssetId: Map<string, string>;
// TODO: These hashes are being invalidated in mutative methods, but this._graph is not a private
// property so it is possible to reach in and mutate the graph without invalidating these hashes.
// It needs to be exposed in BundlerRunner for now based on how applying runtimes works and the
// BundlerRunner takes care of invalidating hashes when runtimes are applied, but this is not ideal.
_bundleContentHashes: Map<string, string>;
_targetEntryRoots: Map<ProjectPath, FilePath> = new Map();
_graph: ContentGraph<BundleGraphNode, BundleGraphEdgeType>;
_symbolPropagationRan /*: boolean*/;
constructor({
graph,
publicIdByAssetId,
assetPublicIds,
bundleContentHashes,
symbolPropagationRan,
}: {|
graph: ContentGraph<BundleGraphNode, BundleGraphEdgeType>,
publicIdByAssetId: Map<string, string>,
assetPublicIds: Set<string>,
bundleContentHashes: Map<string, string>,
symbolPropagationRan: boolean,
|}) {
this._graph = graph;
this._assetPublicIds = assetPublicIds;
this._publicIdByAssetId = publicIdByAssetId;
this._bundleContentHashes = bundleContentHashes;
this._symbolPropagationRan = symbolPropagationRan;
}
static fromAssetGraph(
assetGraph: AssetGraph,
publicIdByAssetId: Map<string, string> = new Map(),
assetPublicIds: Set<string> = new Set(),
): BundleGraph {
let graph = new ContentGraph<BundleGraphNode, BundleGraphEdgeType>();
let assetGroupIds = new Set();
let assetGraphNodeIdToBundleGraphNodeId = new Map<NodeId, NodeId>();
let assetGraphRootNode =
assetGraph.rootNodeId != null
? assetGraph.getNode(assetGraph.rootNodeId)
: null;
invariant(assetGraphRootNode != null && assetGraphRootNode.type === 'root');
for (let [nodeId, node] of assetGraph.nodes) {
if (node.type === 'asset') {
let {id: assetId} = node.value;
// Generate a new, short public id for this asset to use.
// If one already exists, use it.
let publicId = publicIdByAssetId.get(assetId);
if (publicId == null) {
publicId = getPublicId(assetId, existing =>
assetPublicIds.has(existing),
);
publicIdByAssetId.set(assetId, publicId);
assetPublicIds.add(publicId);
}
}
// Don't copy over asset groups into the bundle graph.
if (node.type === 'asset_group') {
assetGroupIds.add(nodeId);
} else {
let bundleGraphNodeId = graph.addNodeByContentKey(node.id, node);
if (node.id === assetGraphRootNode?.id) {
graph.setRootNodeId(bundleGraphNodeId);
}
assetGraphNodeIdToBundleGraphNodeId.set(nodeId, bundleGraphNodeId);
}
}
for (let edge of assetGraph.getAllEdges()) {
let fromIds;
if (assetGroupIds.has(edge.from)) {
fromIds = [
...assetGraph.getNodeIdsConnectedTo(
edge.from,
bundleGraphEdgeTypes.null,
),
];
} else {
fromIds = [edge.from];
}
for (let from of fromIds) {
if (assetGroupIds.has(edge.to)) {
for (let to of assetGraph.getNodeIdsConnectedFrom(
edge.to,
bundleGraphEdgeTypes.null,
)) {
graph.addEdge(
nullthrows(assetGraphNodeIdToBundleGraphNodeId.get(from)),
nullthrows(assetGraphNodeIdToBundleGraphNodeId.get(to)),
);
}
} else {
graph.addEdge(
nullthrows(assetGraphNodeIdToBundleGraphNodeId.get(from)),
nullthrows(assetGraphNodeIdToBundleGraphNodeId.get(edge.to)),
);
}
}
}
return new BundleGraph({
graph,
assetPublicIds,
bundleContentHashes: new Map(),
publicIdByAssetId,
symbolPropagationRan: assetGraph.symbolPropagationRan,
});
}
serialize(): SerializedBundleGraph {
return {
$$raw: true,
graph: this._graph.serialize(),
assetPublicIds: this._assetPublicIds,
bundleContentHashes: this._bundleContentHashes,
publicIdByAssetId: this._publicIdByAssetId,
symbolPropagationRan: this._symbolPropagationRan,
};
}
static deserialize(serialized: BundleGraphOpts): BundleGraph {
return new BundleGraph({
graph: ContentGraph.deserialize(serialized.graph),
assetPublicIds: serialized.assetPublicIds,
bundleContentHashes: serialized.bundleContentHashes,
publicIdByAssetId: serialized.publicIdByAssetId,
symbolPropagationRan: serialized.symbolPropagationRan,
});
}
addAssetGraphToBundle(
asset: Asset,
bundle: Bundle,
shouldSkipDependency: Dependency => boolean = d =>
this.isDependencySkipped(d),
) {
let assetNodeId = this._graph.getNodeIdByContentKey(asset.id);
let bundleNodeId = this._graph.getNodeIdByContentKey(bundle.id);
// The root asset should be reached directly from the bundle in traversal.
// Its children will be traversed from there.
this._graph.addEdge(bundleNodeId, assetNodeId);
this._graph.traverse((nodeId, _, actions) => {
let node = nullthrows(this._graph.getNode(nodeId));
if (node.type === 'bundle_group') {
actions.skipChildren();
return;
}
if (node.type === 'dependency' && shouldSkipDependency(node.value)) {
actions.skipChildren();
return;
}
if (node.type === 'asset' || node.type === 'dependency') {
this._graph.addEdge(
bundleNodeId,
nodeId,
bundleGraphEdgeTypes.contains,
);
}
if (node.type === 'dependency') {
for (let [bundleGroupNodeId, bundleGroupNode] of this._graph
.getNodeIdsConnectedFrom(nodeId)
.map(id => [id, nullthrows(this._graph.getNode(id))])
.filter(([, node]) => node.type === 'bundle_group')) {
invariant(bundleGroupNode.type === 'bundle_group');
this._graph.addEdge(
bundleNodeId,
bundleGroupNodeId,
bundleGraphEdgeTypes.bundle,
);
}
// If the dependency references a target bundle, add a reference edge from
// the source bundle to the dependency for easy traversal.
if (
this._graph
.getNodeIdsConnectedFrom(nodeId, bundleGraphEdgeTypes.references)
.map(id => nullthrows(this._graph.getNode(id)))
.some(node => node.type === 'bundle')
) {
this._graph.addEdge(
bundleNodeId,
nodeId,
bundleGraphEdgeTypes.references,
);
}
}
}, assetNodeId);
this._bundleContentHashes.delete(bundle.id);
}
addEntryToBundle(
asset: Asset,
bundle: Bundle,
shouldSkipDependency?: Dependency => boolean,
) {
this.addAssetGraphToBundle(asset, bundle, shouldSkipDependency);
if (!bundle.entryAssetIds.includes(asset.id)) {
bundle.entryAssetIds.push(asset.id);
}
}
internalizeAsyncDependency(bundle: Bundle, dependency: Dependency) {
if (dependency.priority === Priority.sync) {
throw new Error('Expected an async dependency');
}
this._graph.addEdge(
this._graph.getNodeIdByContentKey(bundle.id),
this._graph.getNodeIdByContentKey(dependency.id),
bundleGraphEdgeTypes.internal_async,
);
this.removeExternalDependency(bundle, dependency);
}
isDependencySkipped(dependency: Dependency): boolean {
let node = this._graph.getNodeByContentKey(dependency.id);
invariant(node && node.type === 'dependency');
return !!node.hasDeferred || node.excluded;
}
getParentBundlesOfBundleGroup(bundleGroup: BundleGroup): Array<Bundle> {
return this._graph
.getNodeIdsConnectedTo(
this._graph.getNodeIdByContentKey(getBundleGroupId(bundleGroup)),
bundleGraphEdgeTypes.bundle,
)
.map(id => nullthrows(this._graph.getNode(id)))
.filter(node => node.type === 'bundle')
.map(node => {
invariant(node.type === 'bundle');
return node.value;
});
}
resolveAsyncDependency(
dependency: Dependency,
bundle: ?Bundle,
): ?(
| {|type: 'bundle_group', value: BundleGroup|}
| {|type: 'asset', value: Asset|}
) {
let depNodeId = this._graph.getNodeIdByContentKey(dependency.id);
let bundleNodeId =
bundle != null ? this._graph.getNodeIdByContentKey(bundle.id) : null;
if (
bundleNodeId != null &&
this._graph.hasEdge(
bundleNodeId,
depNodeId,
bundleGraphEdgeTypes.internal_async,
)
) {
let referencedAssetNodeIds = this._graph.getNodeIdsConnectedFrom(
depNodeId,
bundleGraphEdgeTypes.references,
);
let resolved;
if (referencedAssetNodeIds.length === 0) {
resolved = this.getResolvedAsset(dependency, bundle);
} else if (referencedAssetNodeIds.length === 1) {
let referencedAssetNode = this._graph.getNode(
referencedAssetNodeIds[0],
);
// If a referenced asset already exists, resolve this dependency to it.
invariant(referencedAssetNode?.type === 'asset');
resolved = referencedAssetNode.value;
} else {
throw new Error('Dependencies can only reference one asset');
}
if (resolved == null) {
return;
} else {
return {
type: 'asset',
value: resolved,
};
}
}
let node = this._graph
.getNodeIdsConnectedFrom(this._graph.getNodeIdByContentKey(dependency.id))
.map(id => nullthrows(this._graph.getNode(id)))
.find(node => node.type === 'bundle_group');
if (node == null) {
return;
}
invariant(node.type === 'bundle_group');
return {
type: 'bundle_group',
value: node.value,
};
}
getReferencedBundle(dependency: Dependency, fromBundle: Bundle): ?Bundle {
let dependencyNodeId = this._graph.getNodeIdByContentKey(dependency.id);
// If this dependency is async, there will be a bundle group attached to it.
let node = this._graph
.getNodeIdsConnectedFrom(dependencyNodeId)
.map(id => nullthrows(this._graph.getNode(id)))
.find(node => node.type === 'bundle_group');
if (node != null) {
invariant(node.type === 'bundle_group');
return this.getBundlesInBundleGroup(node.value, {
includeInline: true,
}).find(b => {
let mainEntryId = b.entryAssetIds[b.entryAssetIds.length - 1];
return mainEntryId != null && node.value.entryAssetId === mainEntryId;
});
}
// Otherwise, it may be a reference to another asset in the same bundle group.
// Resolve the dependency to an asset, and look for it in one of the referenced bundles.
let referencedBundles = this.getReferencedBundles(fromBundle, {
includeInline: true,
});
let referenced = this._graph
.getNodeIdsConnectedFrom(
dependencyNodeId,
bundleGraphEdgeTypes.references,
)
.map(id => nullthrows(this._graph.getNode(id)))
.find(node => node.type === 'asset');
if (referenced != null) {
invariant(referenced.type === 'asset');
return referencedBundles.find(b =>
this.bundleHasAsset(b, referenced.value),
);
}
}
removeAssetGraphFromBundle(asset: Asset, bundle: Bundle) {
let bundleNodeId = this._graph.getNodeIdByContentKey(bundle.id);
let assetNodeId = this._graph.getNodeIdByContentKey(asset.id);
// Remove all contains edges from the bundle to the nodes in the asset's
// subgraph.
this._graph.traverse((nodeId, context, actions) => {
let node = nullthrows(this._graph.getNode(nodeId));
if (node.type === 'bundle_group') {
actions.skipChildren();
return;
}
if (node.type !== 'dependency' && node.type !== 'asset') {
return;
}
if (
this._graph.hasEdge(bundleNodeId, nodeId, bundleGraphEdgeTypes.contains)
) {
this._graph.removeEdge(
bundleNodeId,
nodeId,
bundleGraphEdgeTypes.contains,
// Removing this contains edge should not orphan the connected node. This
// is disabled for performance reasons as these edges are removed as part
// of a traversal, and checking for orphans becomes quite expensive in
// aggregate.
false /* removeOrphans */,
);
} else {
actions.skipChildren();
}
if (node.type === 'asset' && this._graph.hasEdge(bundleNodeId, nodeId)) {
// Remove the untyped edge from the bundle to the node (it's an entry)
this._graph.removeEdge(bundleNodeId, nodeId);
let entryIndex = bundle.entryAssetIds.indexOf(node.value.id);
if (entryIndex >= 0) {
// Shared bundles have untyped edges to their asset graphs but don't
// have entry assets. For those that have entry asset ids, remove them.
bundle.entryAssetIds.splice(entryIndex, 1);
}
}
if (node.type === 'dependency') {
this.removeExternalDependency(bundle, node.value);
if (
this._graph.hasEdge(
bundleNodeId,
nodeId,
bundleGraphEdgeTypes.references,
)
) {
this._graph.addEdge(
bundleNodeId,
nodeId,
bundleGraphEdgeTypes.references,
);
}
if (
this._graph.hasEdge(
bundleNodeId,
nodeId,
bundleGraphEdgeTypes.internal_async,
)
) {
this._graph.removeEdge(
bundleNodeId,
nodeId,
bundleGraphEdgeTypes.internal_async,
);
}
}
}, assetNodeId);
// Remove bundle node if it no longer has any entry assets
if (this._graph.getNodeIdsConnectedFrom(bundleNodeId).length === 0) {
this.removeBundle(bundle);
}
this._bundleContentHashes.delete(bundle.id);
}
removeBundle(bundle: Bundle): Set<BundleGroup> {
// Remove bundle node if it no longer has any entry assets
let bundleNodeId = this._graph.getNodeIdByContentKey(bundle.id);
let bundleGroupNodeIds = this._graph.getNodeIdsConnectedTo(
bundleNodeId,
bundleGraphEdgeTypes.bundle,
);
this._graph.removeNode(bundleNodeId);
let removedBundleGroups: Set<BundleGroup> = new Set();
// Remove bundle group node if it no longer has any bundles
for (let bundleGroupNodeId of bundleGroupNodeIds) {
let bundleGroupNode = nullthrows(this._graph.getNode(bundleGroupNodeId));
invariant(bundleGroupNode.type === 'bundle_group');
let bundleGroup = bundleGroupNode.value;
if (
// If the bundle group's entry asset belongs to this bundle, the group
// was created because of this bundle. Remove the group.
bundle.entryAssetIds.includes(bundleGroup.entryAssetId) ||
// If the bundle group is now empty, remove it.
this.getBundlesInBundleGroup(bundleGroup, {includeInline: true})
.length === 0
) {
removedBundleGroups.add(bundleGroup);
this.removeBundleGroup(bundleGroup);
}
}
this._bundleContentHashes.delete(bundle.id);
return removedBundleGroups;
}
removeBundleGroup(bundleGroup: BundleGroup) {
let bundleGroupNode = nullthrows(
this._graph.getNodeByContentKey(getBundleGroupId(bundleGroup)),
);
invariant(bundleGroupNode.type === 'bundle_group');
let bundlesInGroup = this.getBundlesInBundleGroup(bundleGroupNode.value, {
includeInline: true,
});
for (let bundle of bundlesInGroup) {
if (this.getBundleGroupsContainingBundle(bundle).length === 1) {
let removedBundleGroups = this.removeBundle(bundle);
if (removedBundleGroups.has(bundleGroup)) {
// This function can be reentered through removeBundle above. In the case this
// bundle group has already been removed, stop.
return;
}
}
}
// This function can be reentered through removeBundle above. In this case,
// the node may already been removed.
if (this._graph.hasContentKey(bundleGroupNode.id)) {
this._graph.removeNode(
this._graph.getNodeIdByContentKey(bundleGroupNode.id),
);
}
assert(
bundlesInGroup.every(
bundle => this.getBundleGroupsContainingBundle(bundle).length > 0,
),
);
}
removeExternalDependency(bundle: Bundle, dependency: Dependency) {
let bundleNodeId = this._graph.getNodeIdByContentKey(bundle.id);
for (let bundleGroupNode of this._graph
.getNodeIdsConnectedFrom(this._graph.getNodeIdByContentKey(dependency.id))
.map(id => nullthrows(this._graph.getNode(id)))
.filter(node => node.type === 'bundle_group')) {
let bundleGroupNodeId = this._graph.getNodeIdByContentKey(
bundleGroupNode.id,
);
if (
!this._graph.hasEdge(
bundleNodeId,
bundleGroupNodeId,
bundleGraphEdgeTypes.bundle,
)
) {
continue;
}
let inboundDependencies = this._graph
.getNodeIdsConnectedTo(bundleGroupNodeId)
.map(id => nullthrows(this._graph.getNode(id)))
.filter(node => node.type === 'dependency')
.map(node => {
invariant(node.type === 'dependency');
return node.value;
});
// If every inbound dependency to this bundle group does not belong to this bundle,
// or the dependency is internal to the bundle, then the connection between
// this bundle and the group is safe to remove.
if (
inboundDependencies.every(
dependency =>
!this.bundleHasDependency(bundle, dependency) ||
this._graph.hasEdge(
bundleNodeId,
this._graph.getNodeIdByContentKey(dependency.id),
bundleGraphEdgeTypes.internal_async,
),
)
) {
this._graph.removeEdge(
bundleNodeId,
bundleGroupNodeId,
bundleGraphEdgeTypes.bundle,
);
}
}
}
createAssetReference(
dependency: Dependency,
asset: Asset,
bundle: Bundle,
): void {
let dependencyId = this._graph.getNodeIdByContentKey(dependency.id);
let assetId = this._graph.getNodeIdByContentKey(asset.id);
let bundleId = this._graph.getNodeIdByContentKey(bundle.id);
this._graph.addEdge(dependencyId, assetId, bundleGraphEdgeTypes.references);
this._graph.addEdge(
dependencyId,
bundleId,
bundleGraphEdgeTypes.references,
);
if (this._graph.hasEdge(dependencyId, assetId)) {
this._graph.removeEdge(dependencyId, assetId);
}
}
createBundleReference(from: Bundle, to: Bundle): void {
this._graph.addEdge(
this._graph.getNodeIdByContentKey(from.id),
this._graph.getNodeIdByContentKey(to.id),
bundleGraphEdgeTypes.references,
);
}
getBundlesWithAsset(asset: Asset): Array<Bundle> {
return this._graph
.getNodeIdsConnectedTo(
this._graph.getNodeIdByContentKey(asset.id),
bundleGraphEdgeTypes.contains,
)
.map(id => nullthrows(this._graph.getNode(id)))
.filter(node => node.type === 'bundle')
.map(node => {
invariant(node.type === 'bundle');
return node.value;
});
}
getBundlesWithDependency(dependency: Dependency): Array<Bundle> {
return this._graph
.getNodeIdsConnectedTo(
nullthrows(this._graph.getNodeIdByContentKey(dependency.id)),
bundleGraphEdgeTypes.contains,
)
.map(id => nullthrows(this._graph.getNode(id)))
.filter(node => node.type === 'bundle')
.map(node => {
invariant(node.type === 'bundle');
return node.value;
});
}
getDependencyAssets(dependency: Dependency): Array<Asset> {
return this._graph
.getNodeIdsConnectedFrom(this._graph.getNodeIdByContentKey(dependency.id))
.map(id => nullthrows(this._graph.getNode(id)))
.filter(node => node.type === 'asset')
.map(node => {
invariant(node.type === 'asset');
return node.value;
});
}
getResolvedAsset(dep: Dependency, bundle: ?Bundle): ?Asset {
let assets = this.getDependencyAssets(dep);
let firstAsset = assets[0];
let resolved =
// If no bundle is specified, use the first concrete asset.
bundle == null
? firstAsset
: // Otherwise, find the first asset that belongs to this bundle.
assets.find(asset => this.bundleHasAsset(bundle, asset)) ||
firstAsset;
// If a resolution still hasn't been found, return the first referenced asset.
if (resolved == null) {
this._graph.traverse(
(nodeId, _, traversal) => {
let node = nullthrows(this._graph.getNode(nodeId));
if (node.type === 'asset') {
resolved = node.value;
traversal.stop();
} else if (node.id !== dep.id) {
traversal.skipChildren();
}
},
this._graph.getNodeIdByContentKey(dep.id),
bundleGraphEdgeTypes.references,
);
}
return resolved;
}
getDependencies(asset: Asset): Array<Dependency> {
let nodeId = this._graph.getNodeIdByContentKey(asset.id);
return this._graph.getNodeIdsConnectedFrom(nodeId).map(id => {
let node = nullthrows(this._graph.getNode(id));
invariant(node.type === 'dependency');
return node.value;
});
}
traverseAssets<TContext>(
bundle: Bundle,
visit: GraphVisitor<Asset, TContext>,
): ?TContext {
return this.traverseBundle(
bundle,
mapVisitor(node => (node.type === 'asset' ? node.value : null), visit),
);
}
isAssetReferenced(bundle: Bundle, asset: Asset): boolean {
let assetNodeId = nullthrows(this._graph.getNodeIdByContentKey(asset.id));
if (
this._graph
.getNodeIdsConnectedTo(assetNodeId, bundleGraphEdgeTypes.references)
.map(id => this._graph.getNode(id))
.some(
node =>
node?.type === 'dependency' &&
node.value.priority === Priority.lazy &&
node.value.specifierType !== SpecifierType.url,
)
) {
// If this asset is referenced by any async dependency, it's referenced.
return true;
}
let dependencies = this._graph
.getNodeIdsConnectedTo(assetNodeId)
.map(id => nullthrows(this._graph.getNode(id)))
.filter(node => node.type === 'dependency')
.map(node => {
invariant(node.type === 'dependency');
return node.value;
});
const bundleHasReference = (bundle: Bundle) => {
return (
!this.bundleHasAsset(bundle, asset) &&
dependencies.some(dependency =>
this.bundleHasDependency(bundle, dependency),
)
);
};
let visitedBundles: Set<Bundle> = new Set();
let siblingBundles = new Set(
this.getBundleGroupsContainingBundle(bundle).flatMap(bundleGroup =>
this.getBundlesInBundleGroup(bundleGroup, {includeInline: true}),
),
);
// Check if any of this bundle's descendants, referencers, bundles referenced
// by referencers, or descendants of its referencers use the asset without
// an explicit reference edge. This can happen if e.g. the asset has been
// deduplicated.
return [...siblingBundles].some(referencer => {
let isReferenced = false;
this.traverseBundles((descendant, _, actions) => {
if (descendant.id === bundle.id) {
return;
}
if (visitedBundles.has(descendant)) {
actions.skipChildren();
return;
}
visitedBundles.add(descendant);
if (
descendant.type !== bundle.type ||
descendant.env.context !== bundle.env.context
) {
actions.skipChildren();
return;
}
if (bundleHasReference(descendant)) {
isReferenced = true;
actions.stop();
return;
}
}, referencer);
return isReferenced;
});
}
hasParentBundleOfType(bundle: Bundle, type: string): boolean {
let parents = this.getParentBundles(bundle);
return parents.length > 0 && parents.every(parent => parent.type === type);
}
getParentBundles(bundle: Bundle): Array<Bundle> {
let parentBundles: Set<Bundle> = new Set();
for (let bundleGroup of this.getBundleGroupsContainingBundle(bundle)) {
for (let parentBundle of this.getParentBundlesOfBundleGroup(
bundleGroup,
)) {
parentBundles.add(parentBundle);
}
}
return [...parentBundles];
}
isAssetReachableFromBundle(asset: Asset, bundle: Bundle): boolean {
// If a bundle's environment is isolated, it can't access assets present
// in any ancestor bundles. Don't consider any assets reachable.
if (
ISOLATED_ENVS.has(bundle.env.context) ||
!bundle.isSplittable ||
bundle.bundleBehavior === BundleBehavior.isolated ||
bundle.bundleBehavior === BundleBehavior.inline
) {
return false;
}
// For an asset to be reachable from a bundle, it must either exist in a sibling bundle,
// or in an ancestor bundle group reachable from all parent bundles.
let bundleGroups = this.getBundleGroupsContainingBundle(bundle);
return bundleGroups.every(bundleGroup => {
// If the asset is in any sibling bundles of the original bundle, it is reachable.
let bundles = this.getBundlesInBundleGroup(bundleGroup);
if (
bundles.some(
b =>
b.id !== bundle.id &&
b.bundleBehavior !== BundleBehavior.isolated &&
b.bundleBehavior !== BundleBehavior.inline &&
this.bundleHasAsset(b, asset),
)
) {
return true;
}
// Get a list of parent bundle nodes pointing to the bundle group
let parentBundleNodes = this._graph.getNodeIdsConnectedTo(
this._graph.getNodeIdByContentKey(getBundleGroupId(bundleGroup)),
bundleGraphEdgeTypes.bundle,
);
// Check that every parent bundle has a bundle group in its ancestry that contains the asset.
return parentBundleNodes.every(bundleNodeId => {
let bundleNode = nullthrows(this._graph.getNode(bundleNodeId));
if (
bundleNode.type !== 'bundle' ||
bundleNode.value.bundleBehavior === BundleBehavior.isolated ||
bundleNode.value.bundleBehavior === BundleBehavior.inline
) {
return false;
}
let isReachable = true;
this._graph.traverseAncestors(
bundleNodeId,
(nodeId, ctx, actions) => {
let node = nullthrows(this._graph.getNode(nodeId));
// If we've reached the root or a context change without
// finding this asset in the ancestry, it is not reachable.
if (
node.type === 'root' ||
(node.type === 'bundle' &&
(node.value.id === bundle.id ||
node.value.env.context !== bundle.env.context))
) {
isReachable = false;
actions.stop();
return;
}
if (node.type === 'bundle_group') {
let childBundles = this.getBundlesInBundleGroup(node.value);
if (
childBundles.some(
b =>
b.id !== bundle.id &&
b.bundleBehavior !== BundleBehavior.isolated &&
b.bundleBehavior !== BundleBehavior.inline &&
this.bundleHasAsset(b, asset),
)
) {
actions.skipChildren();
return;
}
}
},
[bundleGraphEdgeTypes.references, bundleGraphEdgeTypes.bundle],
);
return isReachable;
});
});
}
traverseBundle<TContext>(
bundle: Bundle,
visit: GraphVisitor<AssetNode | DependencyNode, TContext>,
): ?TContext {
let entries = true;
let bundleNodeId = this._graph.getNodeIdByContentKey(bundle.id);
// A modified DFS traversal which traverses entry assets in the same order
// as their ids appear in `bundle.entryAssetIds`.
return this._graph.dfs({
visit: mapVisitor((nodeId, actions) => {
let node = nullthrows(this._graph.getNode(nodeId));
if (nodeId === bundleNodeId) {
return;
}
if (node.type === 'dependency' || node.type === 'asset') {
if (
this._graph.hasEdge(
bundleNodeId,
nodeId,
bundleGraphEdgeTypes.contains,
)
) {
return node;
}
}
actions.skipChildren();