-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathDefaultBundler.js
1866 lines (1699 loc) Β· 65.2 KB
/
DefaultBundler.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 {
Asset,
Bundle as LegacyBundle,
BundleBehavior,
BundleGroup,
Dependency,
Environment,
Config,
MutableBundleGraph,
PluginOptions,
Target,
BuildMode,
PluginLogger,
} from '@parcel/types';
import type {NodeId} from '@parcel/graph';
import type {SchemaEntity} from '@parcel/utils';
import {ContentGraph, Graph, BitSet, ALL_EDGE_TYPES} from '@parcel/graph';
import invariant from 'assert';
import {Bundler} from '@parcel/plugin';
import {validateSchema, DefaultMap, globToRegex} from '@parcel/utils';
import nullthrows from 'nullthrows';
import path from 'path';
import {encodeJSONKeyComponent} from '@parcel/diagnostic';
type Glob = string;
type ManualSharedBundles = Array<{|
name: string,
assets: Array<Glob>,
types?: Array<string>,
root?: string,
split?: number,
|}>;
type BaseBundlerConfig = {|
http?: number,
minBundles?: number,
minBundleSize?: number,
maxParallelRequests?: number,
disableSharedBundles?: boolean,
manualSharedBundles?: ManualSharedBundles,
|};
type BundlerConfig = {|
[mode: BuildMode]: BaseBundlerConfig,
|} & BaseBundlerConfig;
type ResolvedBundlerConfig = {|
minBundles: number,
minBundleSize: number,
maxParallelRequests: number,
projectRoot: string,
disableSharedBundles: boolean,
manualSharedBundles: ManualSharedBundles,
|};
// Default options by http version.
const HTTP_OPTIONS = {
'1': {
minBundles: 1,
manualSharedBundles: [],
minBundleSize: 30000,
maxParallelRequests: 6,
disableSharedBundles: false,
},
'2': {
minBundles: 1,
manualSharedBundles: [],
minBundleSize: 20000,
maxParallelRequests: 25,
disableSharedBundles: false,
},
};
/* BundleRoot - An asset that is the main entry of a Bundle. */
type BundleRoot = Asset;
export type Bundle = {|
uniqueKey: ?string,
assets: Set<Asset>,
internalizedAssets?: BitSet,
bundleBehavior?: ?BundleBehavior,
needsStableName: boolean,
mainEntryAsset: ?Asset,
size: number,
sourceBundles: Set<NodeId>,
target: Target,
env: Environment,
type: string,
manualSharedBundle: ?string, // for naming purposes
|};
const dependencyPriorityEdges = {
sync: 1,
parallel: 2,
lazy: 3,
};
type DependencyBundleGraph = ContentGraph<
| {|
value: Bundle,
type: 'bundle',
|}
| {|
value: Dependency,
type: 'dependency',
|},
number,
>;
// IdealGraph is the structure we will pass to decorate,
// which mutates the assetGraph into the bundleGraph we would
// expect from default bundler
type IdealGraph = {|
assets: Array<Asset>,
dependencyBundleGraph: DependencyBundleGraph,
bundleGraph: Graph<Bundle | 'root'>,
bundleGroupBundleIds: Set<NodeId>,
assetReference: DefaultMap<Asset, Array<[Dependency, Bundle]>>,
manualAssetToBundle: Map<Asset, NodeId>,
|};
/**
*
* The Bundler works by creating an IdealGraph, which contains a BundleGraph that models bundles
* connected to other bundles by what references them, and thus models BundleGroups.
*
* First, we enter `bundle({bundleGraph, config})`. Here, "bundleGraph" is actually just the
* assetGraph turned into a type `MutableBundleGraph`, which will then be mutated in decorate,
* and turned into what we expect the bundleGraph to be as per the old (default) bundler structure
* & what the rest of Parcel expects a BundleGraph to be.
*
* `bundle({bundleGraph, config})` First gets a Mapping of target to entries, In most cases there is
* only one target, and one or more entries. (Targets are pertinent in monorepos or projects where you
* will have two or more distDirs, or output folders.) Then calls create IdealGraph and Decorate per target.
*
*/
export default (new Bundler({
loadConfig({config, options, logger}) {
return loadBundlerConfig(config, options, logger);
},
bundle({bundleGraph, config, logger}) {
let targetMap = getEntryByTarget(bundleGraph); // Organize entries by target output folder/ distDir
let graphs = [];
for (let entries of targetMap.values()) {
// Create separate bundleGraphs per distDir
graphs.push(createIdealGraph(bundleGraph, config, entries, logger));
}
for (let g of graphs) {
decorateLegacyGraph(g, bundleGraph); //mutate original graph
}
},
optimize() {},
}): Bundler);
function decorateLegacyGraph(
idealGraph: IdealGraph,
bundleGraph: MutableBundleGraph,
): void {
let idealBundleToLegacyBundle: Map<Bundle, LegacyBundle> = new Map();
let {
bundleGraph: idealBundleGraph,
dependencyBundleGraph,
bundleGroupBundleIds,
manualAssetToBundle,
} = idealGraph;
let entryBundleToBundleGroup: Map<NodeId, BundleGroup> = new Map();
// Step Create Bundles: Create bundle groups, bundles, and shared bundles and add assets to them
for (let [bundleNodeId, idealBundle] of idealBundleGraph.nodes.entries()) {
if (!idealBundle || idealBundle === 'root') continue;
let entryAsset = idealBundle.mainEntryAsset;
let bundleGroups = [];
let bundleGroup;
let bundle;
if (bundleGroupBundleIds.has(bundleNodeId)) {
invariant(
idealBundle.manualSharedBundle == null,
'Unstable Manual Shared Bundle feature is processing a manualSharedBundle as a BundleGroup',
);
let dependencies = dependencyBundleGraph
.getNodeIdsConnectedTo(
dependencyBundleGraph.getNodeIdByContentKey(String(bundleNodeId)),
ALL_EDGE_TYPES,
)
.map(nodeId => {
let dependency = nullthrows(dependencyBundleGraph.getNode(nodeId));
invariant(dependency.type === 'dependency');
return dependency.value;
});
invariant(
entryAsset != null,
'Processing a bundleGroup with no entry asset',
);
for (let dependency of dependencies) {
bundleGroup = bundleGraph.createBundleGroup(
dependency,
idealBundle.target,
);
bundleGroups.push(bundleGroup);
}
invariant(bundleGroup);
entryBundleToBundleGroup.set(bundleNodeId, bundleGroup);
bundle = nullthrows(
bundleGraph.createBundle({
entryAsset: nullthrows(entryAsset),
needsStableName: idealBundle.needsStableName,
bundleBehavior: idealBundle.bundleBehavior,
target: idealBundle.target,
manualSharedBundle: idealBundle.manualSharedBundle,
}),
);
bundleGraph.addBundleToBundleGroup(bundle, bundleGroup);
} else if (
idealBundle.sourceBundles.size > 0 &&
!idealBundle.mainEntryAsset
) {
let uniqueKey =
idealBundle.uniqueKey != null
? idealBundle.uniqueKey
: [...idealBundle.assets].map(asset => asset.id).join(',');
bundle = nullthrows(
bundleGraph.createBundle({
uniqueKey,
needsStableName: idealBundle.needsStableName,
bundleBehavior: idealBundle.bundleBehavior,
type: idealBundle.type,
target: idealBundle.target,
env: idealBundle.env,
manualSharedBundle: idealBundle.manualSharedBundle,
}),
);
} else if (idealBundle.uniqueKey != null) {
bundle = nullthrows(
bundleGraph.createBundle({
uniqueKey: idealBundle.uniqueKey,
needsStableName: idealBundle.needsStableName,
bundleBehavior: idealBundle.bundleBehavior,
type: idealBundle.type,
target: idealBundle.target,
env: idealBundle.env,
manualSharedBundle: idealBundle.manualSharedBundle,
}),
);
} else {
invariant(entryAsset != null);
bundle = nullthrows(
bundleGraph.createBundle({
entryAsset,
needsStableName: idealBundle.needsStableName,
bundleBehavior: idealBundle.bundleBehavior,
target: idealBundle.target,
manualSharedBundle: idealBundle.manualSharedBundle,
}),
);
}
idealBundleToLegacyBundle.set(idealBundle, bundle);
for (let asset of idealBundle.assets) {
bundleGraph.addAssetToBundle(asset, bundle);
}
}
// Step Internalization: Internalize dependencies for bundles
for (let idealBundle of idealBundleGraph.nodes) {
if (!idealBundle || idealBundle === 'root') continue;
let bundle = nullthrows(idealBundleToLegacyBundle.get(idealBundle));
if (idealBundle.internalizedAssets) {
idealBundle.internalizedAssets.forEach(internalized => {
let incomingDeps = bundleGraph.getIncomingDependencies(
idealGraph.assets[internalized],
);
for (let incomingDep of incomingDeps) {
if (
incomingDep.priority === 'lazy' &&
incomingDep.specifierType !== 'url' &&
bundle.hasDependency(incomingDep)
) {
bundleGraph.internalizeAsyncDependency(bundle, incomingDep);
}
}
});
}
}
// Unstable Manual Shared Bundles
// NOTE: This only works under the assumption that manual shared bundles would have
// always already been loaded before the bundle that requires internalization.
for (let manualSharedAsset of manualAssetToBundle.keys()) {
let incomingDeps = bundleGraph.getIncomingDependencies(manualSharedAsset);
for (let incomingDep of incomingDeps) {
if (
incomingDep.priority === 'lazy' &&
incomingDep.specifierType !== 'url'
) {
let bundles = bundleGraph.getBundlesWithDependency(incomingDep);
for (let bundle of bundles) {
bundleGraph.internalizeAsyncDependency(bundle, incomingDep);
}
}
}
}
// Step Add to BundleGroups: Add bundles to their bundle groups
idealBundleGraph.traverse((nodeId, _, actions) => {
let node = idealBundleGraph.getNode(nodeId);
if (node === 'root') {
return;
}
actions.skipChildren();
let outboundNodeIds = idealBundleGraph.getNodeIdsConnectedFrom(nodeId);
let entryBundle = nullthrows(idealBundleGraph.getNode(nodeId));
invariant(entryBundle !== 'root');
let legacyEntryBundle = nullthrows(
idealBundleToLegacyBundle.get(entryBundle),
);
for (let id of outboundNodeIds) {
let siblingBundle = nullthrows(idealBundleGraph.getNode(id));
invariant(siblingBundle !== 'root');
let legacySiblingBundle = nullthrows(
idealBundleToLegacyBundle.get(siblingBundle),
);
bundleGraph.createBundleReference(legacyEntryBundle, legacySiblingBundle);
}
});
// Step References: Add references to all bundles
for (let [asset, references] of idealGraph.assetReference) {
for (let [dependency, bundle] of references) {
let legacyBundle = nullthrows(idealBundleToLegacyBundle.get(bundle));
bundleGraph.createAssetReference(dependency, asset, legacyBundle);
}
}
for (let {from, to} of idealBundleGraph.getAllEdges()) {
let sourceBundle = nullthrows(idealBundleGraph.getNode(from));
if (sourceBundle === 'root') {
continue;
}
invariant(sourceBundle !== 'root');
let legacySourceBundle = nullthrows(
idealBundleToLegacyBundle.get(sourceBundle),
);
let targetBundle = nullthrows(idealBundleGraph.getNode(to));
if (targetBundle === 'root') {
continue;
}
invariant(targetBundle !== 'root');
let legacyTargetBundle = nullthrows(
idealBundleToLegacyBundle.get(targetBundle),
);
bundleGraph.createBundleReference(legacySourceBundle, legacyTargetBundle);
}
}
function createIdealGraph(
assetGraph: MutableBundleGraph,
config: ResolvedBundlerConfig,
entries: Map<Asset, Dependency>,
logger: PluginLogger,
): IdealGraph {
// Asset to the bundle and group it's an entry of
let bundleRoots: Map<BundleRoot, [NodeId, NodeId]> = new Map();
let bundles: Map<string, NodeId> = new Map();
let dependencyBundleGraph: DependencyBundleGraph = new ContentGraph();
let assetReference: DefaultMap<
Asset,
Array<[Dependency, Bundle]>,
> = new DefaultMap(() => []);
// A Graph of Bundles and a root node (dummy string), which models only Bundles, and connections to their
// referencing Bundle. There are no actual BundleGroup nodes, just bundles that take on that role.
let bundleGraph: Graph<Bundle | 'root'> = new Graph();
let stack: Array<[BundleRoot, NodeId]> = [];
let bundleRootEdgeTypes = {
parallel: 1,
lazy: 2,
};
// Graph that models bundleRoots, with parallel & async deps only to inform reachability
let bundleRootGraph: Graph<
number, // asset index
$Values<typeof bundleRootEdgeTypes>,
> = new Graph();
let assetToBundleRootNodeId = new Map<BundleRoot, number>();
let bundleGroupBundleIds: Set<NodeId> = new Set();
let bundleGraphRootNodeId = nullthrows(bundleGraph.addNode('root'));
bundleGraph.setRootNodeId(bundleGraphRootNodeId);
// Step Create Entry Bundles
for (let [asset, dependency] of entries) {
let bundle = createBundle({
asset,
target: nullthrows(dependency.target),
needsStableName: dependency.isEntry,
});
let nodeId = bundleGraph.addNode(bundle);
bundles.set(asset.id, nodeId);
bundleRoots.set(asset, [nodeId, nodeId]);
bundleGraph.addEdge(bundleGraphRootNodeId, nodeId);
dependencyBundleGraph.addEdge(
dependencyBundleGraph.addNodeByContentKeyIfNeeded(dependency.id, {
value: dependency,
type: 'dependency',
}),
dependencyBundleGraph.addNodeByContentKeyIfNeeded(String(nodeId), {
value: bundle,
type: 'bundle',
}),
dependencyPriorityEdges[dependency.priority],
);
bundleGroupBundleIds.add(nodeId);
}
let assets = [];
let assetToIndex = new Map<Asset, number>();
function makeManualAssetToConfigLookup() {
let manualAssetToConfig = new Map();
let constantModuleToMSB = new DefaultMap(() => []);
if (config.manualSharedBundles.length === 0) {
return {manualAssetToConfig, constantModuleToMSB};
}
let parentsToConfig = new DefaultMap(() => []);
for (let c of config.manualSharedBundles) {
if (c.root != null) {
parentsToConfig.get(path.join(config.projectRoot, c.root)).push(c);
}
}
let numParentsToFind = parentsToConfig.size;
let configToParentAsset = new Map();
assetGraph.traverse((node, _, actions) => {
if (node.type === 'asset' && parentsToConfig.has(node.value.filePath)) {
for (let c of parentsToConfig.get(node.value.filePath)) {
configToParentAsset.set(c, node.value);
}
numParentsToFind--;
if (numParentsToFind === 0) {
// If we've found all parents we can stop traversal
actions.stop();
}
}
});
// Process in reverse order so earlier configs take precedence
for (let c of config.manualSharedBundles.reverse()) {
if (c.root != null && !configToParentAsset.has(c)) {
logger.warn({
origin: '@parcel/bundler-default',
message: `Manual shared bundle "${c.name}" skipped, no root asset found`,
});
continue;
}
let parentAsset = configToParentAsset.get(c);
let assetRegexes = c.assets.map(glob => globToRegex(glob));
assetGraph.traverse((node, _, actions) => {
if (
node.type === 'asset' &&
(!Array.isArray(c.types) || c.types.includes(node.value.type))
) {
let projectRelativePath = path.relative(
config.projectRoot,
node.value.filePath,
);
if (!assetRegexes.some(regex => regex.test(projectRelativePath))) {
return;
}
// We track all matching MSB's for constant modules as they are never duplicated
// and need to be assigned to all matching bundles
if (node.value.meta.isConstantModule === true) {
constantModuleToMSB.get(node.value).push(c);
}
manualAssetToConfig.set(node.value, c);
return;
}
if (
node.type === 'dependency' &&
node.value.priority === 'lazy' &&
parentAsset
) {
// Don't walk past the bundle group assets
actions.skipChildren();
}
}, parentAsset);
}
return {manualAssetToConfig, constantModuleToMSB};
}
//Manual is a map of the user-given name to the bundle node Id that corresponds to ALL the assets that match any glob in that user-specified array
let manualSharedMap: Map<string, NodeId> = new Map();
// May need a map to be able to look up NON- bundle root assets which need special case instructions
// Use this when placing assets into bundles, to avoid duplication
let manualAssetToBundle: Map<Asset, NodeId> = new Map();
let {manualAssetToConfig, constantModuleToMSB} =
makeManualAssetToConfigLookup();
let manualBundleToInternalizedAsset: DefaultMap<
NodeId,
Array<Asset>,
> = new DefaultMap(() => []);
/**
* Step Create Bundles: Traverse the assetGraph (aka MutableBundleGraph) and create bundles
* for asset type changes, parallel, inline, and async or lazy dependencies,
* adding only that asset to each bundle, not its entire subgraph.
*/
assetGraph.traverse(
{
enter(node, context, actions) {
if (node.type === 'asset') {
if (
context?.type === 'dependency' &&
context?.value.isEntry &&
!entries.has(node.value)
) {
// Skip whole subtrees of other targets by skipping those entries
actions.skipChildren();
return node;
}
assetToIndex.set(node.value, assets.length);
assets.push(node.value);
let bundleIdTuple = bundleRoots.get(node.value);
if (bundleIdTuple && bundleIdTuple[0] === bundleIdTuple[1]) {
// Push to the stack (only) when a new bundle is created
stack.push([node.value, bundleIdTuple[0]]);
} else if (bundleIdTuple) {
// Otherwise, push on the last bundle that marks the start of a BundleGroup
stack.push([node.value, stack[stack.length - 1][1]]);
}
} else if (node.type === 'dependency') {
if (context == null) {
return node;
}
let dependency = node.value;
invariant(context?.type === 'asset');
let assets = assetGraph.getDependencyAssets(dependency);
if (assets.length === 0) {
return node;
}
for (let childAsset of assets) {
let bundleId = bundles.get(childAsset.id);
let bundle;
// MSB Step 1: Match glob on filepath and type for any asset
let manualSharedBundleKey;
let manualSharedObject = manualAssetToConfig.get(childAsset);
if (manualSharedObject) {
// MSB Step 2: Generate a key for which to look up this manual bundle with
manualSharedBundleKey =
manualSharedObject.name + ',' + childAsset.type;
}
if (
// MSB Step 3: If a bundle for these globs already exsits, use it
manualSharedBundleKey != null &&
manualSharedMap.has(manualSharedBundleKey)
) {
bundleId = nullthrows(manualSharedMap.get(manualSharedBundleKey));
}
if (
dependency.priority === 'lazy' ||
(dependency.priority !== 'parallel' &&
(dependency.bundleBehavior === 'isolated' ||
childAsset.bundleBehavior === 'isolated')) // An isolated Dependency, or Bundle must contain all assets it needs to load.
) {
if (bundleId == null) {
let firstBundleGroup = nullthrows(
bundleGraph.getNode(stack[0][1]),
);
invariant(firstBundleGroup !== 'root');
bundle = createBundle({
asset: childAsset,
target: firstBundleGroup.target,
needsStableName:
dependency.bundleBehavior === 'inline' ||
childAsset.bundleBehavior === 'inline'
? false
: dependency.isEntry || dependency.needsStableName,
bundleBehavior:
dependency.bundleBehavior ?? childAsset.bundleBehavior,
});
bundleId = bundleGraph.addNode(bundle);
bundles.set(childAsset.id, bundleId);
bundleRoots.set(childAsset, [bundleId, bundleId]);
bundleGroupBundleIds.add(bundleId);
bundleGraph.addEdge(bundleGraphRootNodeId, bundleId);
if (manualSharedObject) {
// MSB Step 4: If this was the first instance of a match, mark mainAsset for internalization
// since MSBs should not have main entry assets
manualBundleToInternalizedAsset
.get(bundleId)
.push(childAsset);
}
} else {
bundle = nullthrows(bundleGraph.getNode(bundleId));
invariant(bundle !== 'root');
if (
// If this dependency requests isolated, but the bundle is not,
// make the bundle isolated for all uses.
dependency.bundleBehavior === 'isolated' &&
bundle.bundleBehavior == null
) {
bundle.bundleBehavior = dependency.bundleBehavior;
}
}
dependencyBundleGraph.addEdge(
dependencyBundleGraph.addNodeByContentKeyIfNeeded(
dependency.id,
{
value: dependency,
type: 'dependency',
},
),
dependencyBundleGraph.addNodeByContentKeyIfNeeded(
String(bundleId),
{
value: bundle,
type: 'bundle',
},
),
dependencyPriorityEdges[dependency.priority],
);
// If this is a sync dependency on a JS asset that won't be replaced with a URL runtime,
// add a reference so the bundle is loaded by the parent. This happens with React Server Components.
if (
dependency.priority === 'sync' &&
childAsset.type === 'js' &&
childAsset?.meta.jsRuntime !== 'url'
) {
assetReference.get(childAsset).push([dependency, bundle]);
}
} else if (
dependency.priority === 'parallel' ||
childAsset.bundleBehavior === 'inline'
) {
// The referencing bundleRoot is the root of a Bundle that first brings in another bundle (essentially the FIRST parent of a bundle, this may or may not be a bundleGroup)
let [referencingBundleRoot, bundleGroupNodeId] = nullthrows(
stack[stack.length - 1],
);
let bundleGroup = nullthrows(
bundleGraph.getNode(bundleGroupNodeId),
);
invariant(bundleGroup !== 'root');
let referencingBundleId = nullthrows(
bundleRoots.get(referencingBundleRoot),
)[0];
let referencingBundle = nullthrows(
bundleGraph.getNode(referencingBundleId),
);
invariant(referencingBundle !== 'root');
if (bundleId == null) {
bundle = createBundle({
// Bundles created from type changes shouldn't have an entry asset.
asset: childAsset,
type: childAsset.type,
env: childAsset.env,
bundleBehavior:
dependency.bundleBehavior ?? childAsset.bundleBehavior,
target: referencingBundle.target,
needsStableName:
childAsset.bundleBehavior === 'inline' ||
dependency.bundleBehavior === 'inline' ||
(dependency.priority === 'parallel' &&
!dependency.needsStableName)
? false
: referencingBundle.needsStableName,
});
bundleId = bundleGraph.addNode(bundle);
} else {
bundle = bundleGraph.getNode(bundleId);
invariant(bundle != null && bundle !== 'root');
if (
// If this dependency requests isolated, but the bundle is not,
// make the bundle isolated for all uses.
dependency.bundleBehavior === 'isolated' &&
bundle.bundleBehavior == null
) {
bundle.bundleBehavior = dependency.bundleBehavior;
}
}
bundles.set(childAsset.id, bundleId);
// A bundle can belong to multiple bundlegroups, all the bundle groups of it's
// ancestors, and all async and entry bundles before it are "bundle groups"
// TODO: We may need to track bundles to all bundleGroups it belongs to in the future.
bundleRoots.set(childAsset, [bundleId, bundleGroupNodeId]);
bundleGraph.addEdge(referencingBundleId, bundleId);
if (bundleId != bundleGroupNodeId) {
dependencyBundleGraph.addEdge(
dependencyBundleGraph.addNodeByContentKeyIfNeeded(
dependency.id,
{
value: dependency,
type: 'dependency',
},
),
dependencyBundleGraph.addNodeByContentKeyIfNeeded(
String(bundleId),
{
value: bundle,
type: 'bundle',
},
),
dependencyPriorityEdges.parallel,
);
}
assetReference.get(childAsset).push([dependency, bundle]);
} else {
bundleId = null;
}
if (manualSharedObject && bundleId != null) {
// MSB Step 5: At this point we've either created or found an existing MSB bundle
// add the asset if it doesn't already have it and set key
invariant(
bundle !== 'root' && bundle != null && bundleId != null,
);
manualAssetToBundle.set(childAsset, bundleId);
if (!bundle.assets.has(childAsset)) {
// Add asset to bundle
bundle.assets.add(childAsset);
bundle.size += childAsset.stats.size;
}
bundles.set(childAsset.id, bundleId);
bundleRoots.set(childAsset, [bundleId, bundleId]);
invariant(manualSharedBundleKey != null);
// Ensure we set key to BundleId so the next glob match uses the appropriate bundle
if (!manualSharedMap.has(manualSharedBundleKey)) {
manualSharedMap.set(manualSharedBundleKey, bundleId);
}
bundle.manualSharedBundle = manualSharedObject.name;
bundle.uniqueKey = manualSharedObject.name + childAsset.type;
}
}
}
return node;
},
exit(node) {
if (stack[stack.length - 1]?.[0] === node.value) {
stack.pop();
}
},
},
null,
{skipUnusedDependencies: true},
);
// Strip MSBs of entries
for (let [
nodeId,
internalizedAssets,
] of manualBundleToInternalizedAsset.entries()) {
let bundle = bundleGraph.getNode(nodeId);
invariant(bundle != null && bundle !== 'root');
if (!bundle.internalizedAssets) {
bundle.internalizedAssets = new BitSet(assets.length);
}
for (let asset of internalizedAssets) {
bundle.internalizedAssets.add(nullthrows(assetToIndex.get(asset)));
}
bundle.mainEntryAsset = null;
bundleGroupBundleIds.delete(nodeId); // manual bundles can now act as shared, non-bundle group, should they be non-bundleRoots as well?
}
/**
* Step Determine Reachability: Determine reachability for every asset from each bundleRoot.
* This is later used to determine which bundles to place each asset in. We build up two
* structures, one traversal each. ReachableRoots to store sync relationships,
* and bundleRootGraph to store the minimal availability through `parallel` and `async` relationships.
* The two graphs, are used to build up ancestorAssets, a structure which holds all availability by
* all means for each asset.
*/
let rootNodeId = bundleRootGraph.addNode(-1);
bundleRootGraph.setRootNodeId(rootNodeId);
for (let [root] of bundleRoots) {
let nodeId = bundleRootGraph.addNode(nullthrows(assetToIndex.get(root)));
assetToBundleRootNodeId.set(root, nodeId);
if (entries.has(root)) {
bundleRootGraph.addEdge(rootNodeId, nodeId);
}
}
// reachableRoots is an array of bit sets for each asset. Each bit set
// indicates which bundle roots are reachable from that asset synchronously.
let reachableRoots = [];
for (let i = 0; i < assets.length; i++) {
reachableRoots.push(new BitSet(bundleRootGraph.nodes.length));
}
// reachableAssets is the inverse mapping of reachableRoots. For each bundle root,
// it contains a bit set that indicates which assets are reachable from it.
let reachableAssets = [];
// ancestorAssets maps bundle roots to the set of all assets available to it at runtime,
// including in earlier parallel bundles. These are intersected through all paths to
// the bundle to ensure that the available assets are always present no matter in which
// order the bundles are loaded.
let ancestorAssets = [];
let inlineConstantDeps = new DefaultMap(() => new Set());
for (let [bundleRootId, assetId] of bundleRootGraph.nodes.entries()) {
let reachable = new BitSet(assets.length);
reachableAssets.push(reachable);
ancestorAssets.push(null);
if (bundleRootId == rootNodeId || assetId == null) continue;
// Add sync relationships to ReachableRoots
let root = assets[assetId];
assetGraph.traverse(
(node, _, actions) => {
if (node.value === root) {
return;
}
if (node.type === 'dependency') {
let dependency = node.value;
if (
dependency.priority !== 'sync' &&
dependencyBundleGraph.hasContentKey(dependency.id)
) {
let assets = assetGraph.getDependencyAssets(dependency);
if (assets.length === 0) {
return;
}
invariant(assets.length === 1);
let bundleRoot = assets[0];
let bundle = nullthrows(
bundleGraph.getNode(nullthrows(bundles.get(bundleRoot.id))),
);
if (
bundle !== 'root' &&
bundle.bundleBehavior == null &&
!bundle.env.isIsolated() &&
bundle.env.context === root.env.context
) {
bundleRootGraph.addEdge(
bundleRootId,
nullthrows(assetToBundleRootNodeId.get(bundleRoot)),
dependency.priority === 'parallel'
? bundleRootEdgeTypes.parallel
: bundleRootEdgeTypes.lazy,
);
}
}
if (dependency.priority !== 'sync') {
actions.skipChildren();
}
return;
}
//asset node type
let asset = node.value;
if (asset.bundleBehavior != null) {
actions.skipChildren();
return;
}
let assetIndex = nullthrows(assetToIndex.get(node.value));
reachable.add(assetIndex);
reachableRoots[assetIndex].add(bundleRootId);
if (asset.meta.isConstantModule === true) {
let parents = assetGraph
.getIncomingDependencies(asset)
.map(dep => nullthrows(assetGraph.getAssetWithDependency(dep)));
for (let parent of parents) {
inlineConstantDeps.get(parent).add(asset);
}
}
return;
},
root,
{skipUnusedDependencies: true},
);
}
for (let entry of entries.keys()) {
// Initialize an empty set of ancestors available to entries
let entryId = nullthrows(assetToBundleRootNodeId.get(entry));
ancestorAssets[entryId] = new BitSet(assets.length);
}
// Step Determine Availability
// Visit nodes in a topological order, visiting parent nodes before child nodes.
// This allows us to construct an understanding of which assets will already be
// loaded and available when a bundle runs, by pushing available assets downwards and
// computing the intersection of assets available through all possible paths to a bundle.
// We call this structure ancestorAssets, a Map that tracks a bundleRoot,
// to all assets available to it (meaning they will exist guaranteed when the bundleRoot is loaded)
// The topological sort ensures all parents are visited before the node we want to process.
for (let nodeId of bundleRootGraph.topoSort(ALL_EDGE_TYPES)) {
if (nodeId === rootNodeId) continue;
const bundleRoot = assets[nullthrows(bundleRootGraph.getNode(nodeId))];
let bundleGroupId = nullthrows(bundleRoots.get(bundleRoot))[1];
// At a BundleRoot, we access it's available assets (via ancestorAssets),
// and add to that all assets within the bundles in that BundleGroup.
// This set is available to all bundles in a particular bundleGroup because
// bundleGroups are just bundles loaded at the same time. However it is
// not true that a bundle's available assets = all assets of all the bundleGroups
// it belongs to. It's the intersection of those sets.
let available;
if (bundleRoot.bundleBehavior === 'isolated') {
available = new BitSet(assets.length);
} else {
available = nullthrows(ancestorAssets[nodeId]).clone();
for (let bundleIdInGroup of [
bundleGroupId,
...bundleGraph.getNodeIdsConnectedFrom(bundleGroupId),
]) {
let bundleInGroup = nullthrows(bundleGraph.getNode(bundleIdInGroup));
invariant(bundleInGroup !== 'root');
if (bundleInGroup.bundleBehavior != null) {
continue;
}
for (let bundleRoot of bundleInGroup.assets) {
// Assets directly connected to current bundleRoot
available.add(nullthrows(assetToIndex.get(bundleRoot)));
available.union(
reachableAssets[
nullthrows(assetToBundleRootNodeId.get(bundleRoot))
],
);
}
}
}
// Now that we have bundleGroup availability, we will propagate that down to all the children
// of this bundleGroup. For a child, we also must maintain parallel availability. If it has
// parallel siblings that come before it, those, too, are available to it. Add those parallel
// available assets to the set of available assets for this child as well.
let children = bundleRootGraph.getNodeIdsConnectedFrom(
nodeId,
ALL_EDGE_TYPES,
);
let parallelAvailability = new BitSet(assets.length);
for (let childId of children) {
let assetId = nullthrows(bundleRootGraph.getNode(childId));
let child = assets[assetId];
let bundleBehavior = getBundleFromBundleRoot(child).bundleBehavior;
if (bundleBehavior != null) {
continue;
}
let isParallel = bundleRootGraph.hasEdge(
nodeId,
childId,
bundleRootEdgeTypes.parallel,
);
// Most of the time, a child will have many parent bundleGroups,
// so the next time we peek at a child from another parent, we will
// intersect the availability built there with the previously computed
// availability. this ensures no matter which bundleGroup loads a particular bundle,
// it will only assume availability of assets it has under any circumstance