@atlaspack/bundler-default 2.14.0 → 2.14.1-canary.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1068 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.createIdealGraph = createIdealGraph;
7
+ exports.idealBundleGraphEdges = void 0;
8
+ function _path() {
9
+ const data = _interopRequireDefault(require("path"));
10
+ _path = function () {
11
+ return data;
12
+ };
13
+ return data;
14
+ }
15
+ function _featureFlags() {
16
+ const data = require("@atlaspack/feature-flags");
17
+ _featureFlags = function () {
18
+ return data;
19
+ };
20
+ return data;
21
+ }
22
+ function _graph() {
23
+ const data = require("@atlaspack/graph");
24
+ _graph = function () {
25
+ return data;
26
+ };
27
+ return data;
28
+ }
29
+ function _utils() {
30
+ const data = require("@atlaspack/utils");
31
+ _utils = function () {
32
+ return data;
33
+ };
34
+ return data;
35
+ }
36
+ function _assert() {
37
+ const data = _interopRequireDefault(require("assert"));
38
+ _assert = function () {
39
+ return data;
40
+ };
41
+ return data;
42
+ }
43
+ function _nullthrows() {
44
+ const data = _interopRequireDefault(require("nullthrows"));
45
+ _nullthrows = function () {
46
+ return data;
47
+ };
48
+ return data;
49
+ }
50
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
51
+ /* BundleRoot - An asset that is the main entry of a Bundle. */
52
+ const dependencyPriorityEdges = {
53
+ sync: 1,
54
+ parallel: 2,
55
+ lazy: 3,
56
+ conditional: 4
57
+ };
58
+ const idealBundleGraphEdges = exports.idealBundleGraphEdges = Object.freeze({
59
+ default: 1,
60
+ conditional: 2
61
+ });
62
+
63
+ // IdealGraph is the structure we will pass to decorate,
64
+ // which mutates the assetGraph into the bundleGraph we would
65
+ // expect from default bundler
66
+
67
+ function createIdealGraph(assetGraph, config, entries, logger) {
68
+ // Asset to the bundle and group it's an entry of
69
+ let bundleRoots = new Map();
70
+ let bundles = new Map();
71
+ let dependencyBundleGraph = new (_graph().ContentGraph)();
72
+ let assetReference = new (_utils().DefaultMap)(() => []);
73
+
74
+ // A Graph of Bundles and a root node (dummy string), which models only Bundles, and connections to their
75
+ // referencing Bundle. There are no actual BundleGroup nodes, just bundles that take on that role.
76
+ let bundleGraph = new (_graph().Graph)();
77
+ let stack = [];
78
+ let bundleRootEdgeTypes = {
79
+ parallel: 1,
80
+ lazy: 2
81
+ };
82
+ // Graph that models bundleRoots, with parallel & async deps only to inform reachability
83
+ let bundleRootGraph = new (_graph().Graph)();
84
+ let assetToBundleRootNodeId = new Map();
85
+ let bundleGroupBundleIds = new Set();
86
+ let bundleGraphRootNodeId = (0, _nullthrows().default)(bundleGraph.addNode('root'));
87
+ bundleGraph.setRootNodeId(bundleGraphRootNodeId);
88
+ // Step Create Entry Bundles
89
+ for (let [asset, dependency] of entries) {
90
+ let bundle = createBundle({
91
+ asset,
92
+ target: (0, _nullthrows().default)(dependency.target),
93
+ needsStableName: dependency.isEntry
94
+ });
95
+ let nodeId = bundleGraph.addNode(bundle);
96
+ bundles.set(asset.id, nodeId);
97
+ bundleRoots.set(asset, [nodeId, nodeId]);
98
+ bundleGraph.addEdge(bundleGraphRootNodeId, nodeId);
99
+ dependencyBundleGraph.addEdge(dependencyBundleGraph.addNodeByContentKeyIfNeeded(dependency.id, {
100
+ value: dependency,
101
+ type: 'dependency'
102
+ }), dependencyBundleGraph.addNodeByContentKeyIfNeeded(String(nodeId), {
103
+ value: bundle,
104
+ type: 'bundle'
105
+ }), dependencyPriorityEdges[dependency.priority]);
106
+ bundleGroupBundleIds.add(nodeId);
107
+ }
108
+ let assets = [];
109
+ let assetToIndex = new Map();
110
+ //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
111
+ let manualSharedMap = new Map();
112
+ // May need a map to be able to look up NON- bundle root assets which need special case instructions
113
+ // Use this when placing assets into bundles, to avoid duplication
114
+ let manualAssetToBundle = new Map();
115
+ let {
116
+ manualAssetToConfig,
117
+ constantModuleToMSB
118
+ } = function makeManualAssetToConfigLookup() {
119
+ let manualAssetToConfig = new Map();
120
+ let constantModuleToMSB = new (_utils().DefaultMap)(() => []);
121
+ if (config.manualSharedBundles.length === 0) {
122
+ return {
123
+ manualAssetToConfig,
124
+ constantModuleToMSB
125
+ };
126
+ }
127
+ let parentsToConfig = new (_utils().DefaultMap)(() => []);
128
+ for (let c of config.manualSharedBundles) {
129
+ if (c.root != null) {
130
+ parentsToConfig.get(_path().default.join(config.projectRoot, c.root)).push(c);
131
+ }
132
+ }
133
+ let numParentsToFind = parentsToConfig.size;
134
+ let configToParentAsset = new Map();
135
+ assetGraph.traverse((node, _, actions) => {
136
+ if (node.type === 'asset' && parentsToConfig.has(node.value.filePath)) {
137
+ for (let c of parentsToConfig.get(node.value.filePath)) {
138
+ configToParentAsset.set(c, node.value);
139
+ }
140
+ numParentsToFind--;
141
+ if (numParentsToFind === 0) {
142
+ // If we've found all parents we can stop traversal
143
+ actions.stop();
144
+ }
145
+ }
146
+ });
147
+
148
+ // Process in reverse order so earlier configs take precedence
149
+ for (let c of config.manualSharedBundles.reverse()) {
150
+ if (c.root != null && !configToParentAsset.has(c)) {
151
+ logger.warn({
152
+ origin: '@atlaspack/bundler-default',
153
+ message: `Manual shared bundle "${c.name}" skipped, no root asset found`
154
+ });
155
+ continue;
156
+ }
157
+ let parentAsset = configToParentAsset.get(c);
158
+ let assetRegexes = c.assets.map(glob => (0, _utils().globToRegex)(glob));
159
+ assetGraph.traverse((node, _, actions) => {
160
+ if (node.type === 'asset' && (!Array.isArray(c.types) || c.types.includes(node.value.type))) {
161
+ let projectRelativePath = _path().default.relative(config.projectRoot, node.value.filePath);
162
+ if (!assetRegexes.some(regex => regex.test(projectRelativePath))) {
163
+ return;
164
+ }
165
+
166
+ // We track all matching MSB's for constant modules as they are never duplicated
167
+ // and need to be assigned to all matching bundles
168
+ if (node.value.meta.isConstantModule === true) {
169
+ constantModuleToMSB.get(node.value).push(c);
170
+ }
171
+ manualAssetToConfig.set(node.value, c);
172
+ return;
173
+ }
174
+ if (node.type === 'dependency' && (node.value.priority === 'lazy' || (0, _featureFlags().getFeatureFlag)('conditionalBundlingApi') && node.value.priority === 'conditional') && parentAsset) {
175
+ // Don't walk past the bundle group assets
176
+ actions.skipChildren();
177
+ }
178
+ }, parentAsset);
179
+ }
180
+ return {
181
+ manualAssetToConfig,
182
+ constantModuleToMSB
183
+ };
184
+ }();
185
+ let manualBundleToInternalizedAsset = new (_utils().DefaultMap)(() => []);
186
+
187
+ /**
188
+ * Step Create Bundles: Traverse the assetGraph (aka MutableBundleGraph) and create bundles
189
+ * for asset type changes, parallel, inline, and async or lazy dependencies,
190
+ * adding only that asset to each bundle, not its entire subgraph.
191
+ */
192
+ assetGraph.traverse({
193
+ enter(node, context, actions) {
194
+ if (node.type === 'asset') {
195
+ if ((context === null || context === void 0 ? void 0 : context.type) === 'dependency' && context !== null && context !== void 0 && context.value.isEntry && !entries.has(node.value)) {
196
+ // Skip whole subtrees of other targets by skipping those entries
197
+ actions.skipChildren();
198
+ return node;
199
+ }
200
+ assetToIndex.set(node.value, assets.length);
201
+ assets.push(node.value);
202
+ let bundleIdTuple = bundleRoots.get(node.value);
203
+ if (bundleIdTuple && bundleIdTuple[0] === bundleIdTuple[1]) {
204
+ // Push to the stack (only) when a new bundle is created
205
+ stack.push([node.value, bundleIdTuple[0]]);
206
+ } else if (bundleIdTuple) {
207
+ // Otherwise, push on the last bundle that marks the start of a BundleGroup
208
+ stack.push([node.value, stack[stack.length - 1][1]]);
209
+ }
210
+ } else if (node.type === 'dependency') {
211
+ if (context == null) {
212
+ return node;
213
+ }
214
+ let dependency = node.value;
215
+ (0, _assert().default)((context === null || context === void 0 ? void 0 : context.type) === 'asset');
216
+ let assets = assetGraph.getDependencyAssets(dependency);
217
+ if (assets.length === 0) {
218
+ return node;
219
+ }
220
+ for (let childAsset of assets) {
221
+ let bundleId = bundles.get(childAsset.id);
222
+ let bundle;
223
+
224
+ // MSB Step 1: Match glob on filepath and type for any asset
225
+ let manualSharedBundleKey;
226
+ let manualSharedObject = manualAssetToConfig.get(childAsset);
227
+ if (manualSharedObject) {
228
+ // MSB Step 2: Generate a key for which to look up this manual bundle with
229
+ manualSharedBundleKey = manualSharedObject.name + ',' + childAsset.type;
230
+ }
231
+ if (
232
+ // MSB Step 3: If a bundle for these globs already exists, use it
233
+ manualSharedBundleKey != null && manualSharedMap.has(manualSharedBundleKey)) {
234
+ bundleId = (0, _nullthrows().default)(manualSharedMap.get(manualSharedBundleKey));
235
+ }
236
+ if (dependency.priority === 'lazy' || (0, _featureFlags().getFeatureFlag)('conditionalBundlingApi') && node.value.priority === 'conditional' || childAsset.bundleBehavior === 'isolated' // An isolated Dependency, or Bundle must contain all assets it needs to load.
237
+ ) {
238
+ if (bundleId == null) {
239
+ let firstBundleGroup = (0, _nullthrows().default)(bundleGraph.getNode(stack[0][1]));
240
+ (0, _assert().default)(firstBundleGroup !== 'root');
241
+ bundle = createBundle({
242
+ asset: childAsset,
243
+ bundleBehavior: dependency.bundleBehavior ?? childAsset.bundleBehavior,
244
+ needsStableName: dependency.bundleBehavior === 'inline' || childAsset.bundleBehavior === 'inline' ? false : dependency.isEntry || dependency.needsStableName,
245
+ target: firstBundleGroup.target
246
+ });
247
+ bundleId = bundleGraph.addNode(bundle);
248
+ bundles.set(childAsset.id, bundleId);
249
+ bundleRoots.set(childAsset, [bundleId, bundleId]);
250
+ bundleGroupBundleIds.add(bundleId);
251
+ bundleGraph.addEdge(bundleGraphRootNodeId, bundleId);
252
+ if (manualSharedObject) {
253
+ // MSB Step 4: If this was the first instance of a match, mark mainAsset for internalization
254
+ // since MSBs should not have main entry assets
255
+ manualBundleToInternalizedAsset.get(bundleId).push(childAsset);
256
+ }
257
+ } else {
258
+ bundle = (0, _nullthrows().default)(bundleGraph.getNode(bundleId));
259
+ (0, _assert().default)(bundle !== 'root');
260
+ if (
261
+ // If this dependency requests isolated, but the bundle is not,
262
+ // make the bundle isolated for all uses.
263
+ dependency.bundleBehavior === 'isolated' && bundle.bundleBehavior == null) {
264
+ bundle.bundleBehavior = dependency.bundleBehavior;
265
+ }
266
+ }
267
+ dependencyBundleGraph.addEdge(dependencyBundleGraph.addNodeByContentKeyIfNeeded(dependency.id, {
268
+ value: dependency,
269
+ type: 'dependency'
270
+ }), dependencyBundleGraph.addNodeByContentKeyIfNeeded(String(bundleId), {
271
+ value: bundle,
272
+ type: 'bundle'
273
+ }), dependencyPriorityEdges[dependency.priority]);
274
+ if ((0, _featureFlags().getFeatureFlag)('conditionalBundlingApi') && dependency.priority === 'conditional') {
275
+ let [referencingBundleRoot, bundleGroupNodeId] = (0, _nullthrows().default)(stack[stack.length - 1]);
276
+ let referencingBundleId = (0, _nullthrows().default)(bundleRoots.get(referencingBundleRoot))[0];
277
+ if (config.loadConditionalBundlesInParallel) {
278
+ // When configured, serve conditional bundles in parallel so we don't get module not found errors
279
+ bundleRoots.set(childAsset, [bundleId, bundleGroupNodeId]);
280
+ bundleGraph.addEdge(referencingBundleId, bundleId);
281
+ }
282
+
283
+ // Add conditional edge to track which bundles request each other
284
+ bundleGraph.addEdge(referencingBundleId, bundleId, idealBundleGraphEdges.conditional);
285
+ }
286
+ } else if (dependency.priority === 'parallel' || childAsset.bundleBehavior === 'inline') {
287
+ // 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)
288
+ let [referencingBundleRoot, bundleGroupNodeId] = (0, _nullthrows().default)(stack[stack.length - 1]);
289
+ let bundleGroup = (0, _nullthrows().default)(bundleGraph.getNode(bundleGroupNodeId));
290
+ (0, _assert().default)(bundleGroup !== 'root');
291
+ let referencingBundleId = (0, _nullthrows().default)(bundleRoots.get(referencingBundleRoot))[0];
292
+ let referencingBundle = (0, _nullthrows().default)(bundleGraph.getNode(referencingBundleId));
293
+ (0, _assert().default)(referencingBundle !== 'root');
294
+ if (bundleId == null) {
295
+ bundle = createBundle({
296
+ // Bundles created from type changes shouldn't have an entry asset.
297
+ asset: childAsset,
298
+ type: childAsset.type,
299
+ env: childAsset.env,
300
+ bundleBehavior: dependency.bundleBehavior ?? childAsset.bundleBehavior,
301
+ target: referencingBundle.target,
302
+ needsStableName: childAsset.bundleBehavior === 'inline' || dependency.bundleBehavior === 'inline' || dependency.priority === 'parallel' && !dependency.needsStableName ? false : referencingBundle.needsStableName
303
+ });
304
+ bundleId = bundleGraph.addNode(bundle);
305
+ } else {
306
+ bundle = bundleGraph.getNode(bundleId);
307
+ (0, _assert().default)(bundle != null && bundle !== 'root');
308
+ if (
309
+ // If this dependency requests isolated, but the bundle is not,
310
+ // make the bundle isolated for all uses.
311
+ dependency.bundleBehavior === 'isolated' && bundle.bundleBehavior == null) {
312
+ bundle.bundleBehavior = dependency.bundleBehavior;
313
+ }
314
+ }
315
+ bundles.set(childAsset.id, bundleId);
316
+
317
+ // A bundle can belong to multiple bundlegroups, all the bundle groups of it's
318
+ // ancestors, and all async and entry bundles before it are "bundle groups"
319
+ // TODO: We may need to track bundles to all bundleGroups it belongs to in the future.
320
+ bundleRoots.set(childAsset, [bundleId, bundleGroupNodeId]);
321
+ bundleGraph.addEdge(referencingBundleId, bundleId);
322
+ if (bundleId != bundleGroupNodeId) {
323
+ dependencyBundleGraph.addEdge(dependencyBundleGraph.addNodeByContentKeyIfNeeded(dependency.id, {
324
+ value: dependency,
325
+ type: 'dependency'
326
+ }), dependencyBundleGraph.addNodeByContentKeyIfNeeded(String(bundleId), {
327
+ value: bundle,
328
+ type: 'bundle'
329
+ }), dependencyPriorityEdges.parallel);
330
+ }
331
+ assetReference.get(childAsset).push([dependency, bundle]);
332
+ } else {
333
+ bundleId = null;
334
+ }
335
+ if (manualSharedObject && bundleId != null) {
336
+ // MSB Step 5: At this point we've either created or found an existing MSB bundle
337
+ // add the asset if it doesn't already have it and set key
338
+
339
+ (0, _assert().default)(bundle !== 'root' && bundle != null && bundleId != null);
340
+ manualAssetToBundle.set(childAsset, bundleId);
341
+ if (!bundle.assets.has(childAsset)) {
342
+ // Add asset to bundle
343
+ bundle.assets.add(childAsset);
344
+ bundle.size += childAsset.stats.size;
345
+ }
346
+ bundles.set(childAsset.id, bundleId);
347
+ bundleRoots.set(childAsset, [bundleId, bundleId]);
348
+ (0, _assert().default)(manualSharedBundleKey != null);
349
+ // Ensure we set key to BundleId so the next glob match uses the appropriate bundle
350
+ if (!manualSharedMap.has(manualSharedBundleKey)) {
351
+ manualSharedMap.set(manualSharedBundleKey, bundleId);
352
+ }
353
+ bundle.manualSharedBundle = manualSharedObject.name;
354
+ bundle.uniqueKey = manualSharedObject.name + childAsset.type;
355
+ }
356
+ }
357
+ }
358
+ return node;
359
+ },
360
+ exit(node) {
361
+ var _stack;
362
+ if (((_stack = stack[stack.length - 1]) === null || _stack === void 0 ? void 0 : _stack[0]) === node.value) {
363
+ stack.pop();
364
+ }
365
+ }
366
+ }, null, {
367
+ skipUnusedDependencies: true
368
+ });
369
+
370
+ // Strip MSBs of entries
371
+ for (let [nodeId, internalizedAssets] of manualBundleToInternalizedAsset.entries()) {
372
+ let bundle = bundleGraph.getNode(nodeId);
373
+ (0, _assert().default)(bundle != null && bundle !== 'root');
374
+ if (!bundle.internalizedAssets) {
375
+ bundle.internalizedAssets = new (_graph().BitSet)(assets.length);
376
+ }
377
+ for (let asset of internalizedAssets) {
378
+ bundle.internalizedAssets.add((0, _nullthrows().default)(assetToIndex.get(asset)));
379
+ }
380
+ bundle.mainEntryAsset = null;
381
+ bundleGroupBundleIds.delete(nodeId); // manual bundles can now act as shared, non-bundle group, should they be non-bundleRoots as well?
382
+ }
383
+
384
+ /**
385
+ * Step Determine Reachability: Determine reachability for every asset from each bundleRoot.
386
+ * This is later used to determine which bundles to place each asset in. We build up two
387
+ * structures, one traversal each. ReachableRoots to store sync relationships,
388
+ * and bundleRootGraph to store the minimal availability through `parallel` and `async` relationships.
389
+ * The two graphs, are used to build up ancestorAssets, a structure which holds all availability by
390
+ * all means for each asset.
391
+ */
392
+ let rootNodeId = bundleRootGraph.addNode(-1);
393
+ bundleRootGraph.setRootNodeId(rootNodeId);
394
+ for (let [root] of bundleRoots) {
395
+ let nodeId = bundleRootGraph.addNode((0, _nullthrows().default)(assetToIndex.get(root)));
396
+ assetToBundleRootNodeId.set(root, nodeId);
397
+ if (entries.has(root)) {
398
+ bundleRootGraph.addEdge(rootNodeId, nodeId);
399
+ }
400
+ }
401
+
402
+ // reachableRoots is an array of bit sets for each asset. Each bit set
403
+ // indicates which bundle roots are reachable from that asset synchronously.
404
+ let reachableRoots = [];
405
+ for (let i = 0; i < assets.length; i++) {
406
+ reachableRoots.push(new (_graph().BitSet)(bundleRootGraph.nodes.length));
407
+ }
408
+
409
+ // reachableAssets is the inverse mapping of reachableRoots. For each bundle root,
410
+ // it contains a bit set that indicates which assets are reachable from it.
411
+ let reachableAssets = [];
412
+
413
+ // ancestorAssets maps bundle roots to the set of all assets available to it at runtime,
414
+ // including in earlier parallel bundles. These are intersected through all paths to
415
+ // the bundle to ensure that the available assets are always present no matter in which
416
+ // order the bundles are loaded.
417
+ let ancestorAssets = [];
418
+ let inlineConstantDeps = new (_utils().DefaultMap)(() => new Set());
419
+ for (let [bundleRootId, assetId] of bundleRootGraph.nodes.entries()) {
420
+ let reachable = new (_graph().BitSet)(assets.length);
421
+ reachableAssets.push(reachable);
422
+ ancestorAssets.push(null);
423
+ if (bundleRootId == rootNodeId || assetId == null) continue;
424
+ // Add sync relationships to ReachableRoots
425
+ let root = assets[assetId];
426
+ assetGraph.traverse((node, _, actions) => {
427
+ if (node.value === root) {
428
+ return;
429
+ }
430
+ if (node.type === 'dependency') {
431
+ let dependency = node.value;
432
+ if (dependency.priority !== 'sync' && dependencyBundleGraph.hasContentKey(dependency.id)) {
433
+ let assets = assetGraph.getDependencyAssets(dependency);
434
+ if (assets.length === 0) {
435
+ return;
436
+ }
437
+ (0, _assert().default)(assets.length === 1);
438
+ let bundleRoot = assets[0];
439
+ let bundle = (0, _nullthrows().default)(bundleGraph.getNode((0, _nullthrows().default)(bundles.get(bundleRoot.id))));
440
+ if (bundle !== 'root' && bundle.bundleBehavior == null && !bundle.env.isIsolated() && bundle.env.context === root.env.context) {
441
+ bundleRootGraph.addEdge(bundleRootId, (0, _nullthrows().default)(assetToBundleRootNodeId.get(bundleRoot)), dependency.priority === 'parallel' || config.loadConditionalBundlesInParallel && dependency.priority === 'conditional' ? bundleRootEdgeTypes.parallel : bundleRootEdgeTypes.lazy);
442
+ }
443
+ }
444
+ if (dependency.priority !== 'sync') {
445
+ actions.skipChildren();
446
+ }
447
+ return;
448
+ }
449
+ //asset node type
450
+ let asset = node.value;
451
+ if (asset.bundleBehavior != null) {
452
+ actions.skipChildren();
453
+ return;
454
+ }
455
+ let assetIndex = (0, _nullthrows().default)(assetToIndex.get(node.value));
456
+ reachable.add(assetIndex);
457
+ reachableRoots[assetIndex].add(bundleRootId);
458
+ if (asset.meta.isConstantModule === true) {
459
+ let parents = assetGraph.getIncomingDependencies(asset).map(dep => (0, _nullthrows().default)(assetGraph.getAssetWithDependency(dep)));
460
+ for (let parent of parents) {
461
+ inlineConstantDeps.get(parent).add(asset);
462
+ }
463
+ }
464
+ return;
465
+ }, root, {
466
+ skipUnusedDependencies: true
467
+ });
468
+ }
469
+ for (let entry of entries.keys()) {
470
+ // Initialize an empty set of ancestors available to entries
471
+ let entryId = (0, _nullthrows().default)(assetToBundleRootNodeId.get(entry));
472
+ ancestorAssets[entryId] = new (_graph().BitSet)(assets.length);
473
+ }
474
+
475
+ // Step Determine Availability
476
+ // Visit nodes in a topological order, visiting parent nodes before child nodes.
477
+
478
+ // This allows us to construct an understanding of which assets will already be
479
+ // loaded and available when a bundle runs, by pushing available assets downwards and
480
+ // computing the intersection of assets available through all possible paths to a bundle.
481
+ // We call this structure ancestorAssets, a Map that tracks a bundleRoot,
482
+ // to all assets available to it (meaning they will exist guaranteed when the bundleRoot is loaded)
483
+ // The topological sort ensures all parents are visited before the node we want to process.
484
+ for (let nodeId of bundleRootGraph.topoSort(_graph().ALL_EDGE_TYPES)) {
485
+ if (nodeId === rootNodeId) continue;
486
+ const bundleRoot = assets[(0, _nullthrows().default)(bundleRootGraph.getNode(nodeId))];
487
+ let bundleGroupId = (0, _nullthrows().default)(bundleRoots.get(bundleRoot))[1];
488
+
489
+ // At a BundleRoot, we access it's available assets (via ancestorAssets),
490
+ // and add to that all assets within the bundles in that BundleGroup.
491
+
492
+ // This set is available to all bundles in a particular bundleGroup because
493
+ // bundleGroups are just bundles loaded at the same time. However it is
494
+ // not true that a bundle's available assets = all assets of all the bundleGroups
495
+ // it belongs to. It's the intersection of those sets.
496
+ let available;
497
+ if (bundleRoot.bundleBehavior === 'isolated') {
498
+ available = new (_graph().BitSet)(assets.length);
499
+ } else {
500
+ available = (0, _nullthrows().default)(ancestorAssets[nodeId]).clone();
501
+ for (let bundleIdInGroup of [bundleGroupId, ...bundleGraph.getNodeIdsConnectedFrom(bundleGroupId)]) {
502
+ let bundleInGroup = (0, _nullthrows().default)(bundleGraph.getNode(bundleIdInGroup));
503
+ (0, _assert().default)(bundleInGroup !== 'root');
504
+ if (bundleInGroup.bundleBehavior != null) {
505
+ continue;
506
+ }
507
+ for (let bundleRoot of bundleInGroup.assets) {
508
+ // Assets directly connected to current bundleRoot
509
+ available.add((0, _nullthrows().default)(assetToIndex.get(bundleRoot)));
510
+ available.union(reachableAssets[(0, _nullthrows().default)(assetToBundleRootNodeId.get(bundleRoot))]);
511
+ }
512
+ }
513
+ }
514
+
515
+ // Now that we have bundleGroup availability, we will propagate that down to all the children
516
+ // of this bundleGroup. For a child, we also must maintain parallel availability. If it has
517
+ // parallel siblings that come before it, those, too, are available to it. Add those parallel
518
+ // available assets to the set of available assets for this child as well.
519
+ let children = bundleRootGraph.getNodeIdsConnectedFrom(nodeId, _graph().ALL_EDGE_TYPES);
520
+ let parallelAvailability = new (_graph().BitSet)(assets.length);
521
+ for (let childId of children) {
522
+ let assetId = (0, _nullthrows().default)(bundleRootGraph.getNode(childId));
523
+ let child = assets[assetId];
524
+ let bundleBehavior = getBundleFromBundleRoot(child).bundleBehavior;
525
+ if (bundleBehavior != null) {
526
+ continue;
527
+ }
528
+ let isParallel = bundleRootGraph.hasEdge(nodeId, childId, bundleRootEdgeTypes.parallel);
529
+
530
+ // Most of the time, a child will have many parent bundleGroups,
531
+ // so the next time we peek at a child from another parent, we will
532
+ // intersect the availability built there with the previously computed
533
+ // availability. this ensures no matter which bundleGroup loads a particular bundle,
534
+ // it will only assume availability of assets it has under any circumstance
535
+ const childAvailableAssets = ancestorAssets[childId];
536
+ let currentChildAvailable = isParallel ? _graph().BitSet.union(parallelAvailability, available) : available;
537
+ if (childAvailableAssets != null) {
538
+ childAvailableAssets.intersect(currentChildAvailable);
539
+ } else {
540
+ ancestorAssets[childId] = currentChildAvailable.clone();
541
+ }
542
+ if (isParallel) {
543
+ parallelAvailability.union(reachableAssets[childId]);
544
+ parallelAvailability.add(assetId); //The next sibling should have older sibling available via parallel
545
+ }
546
+ }
547
+ }
548
+ // Step Internalize async bundles - internalize Async bundles if and only if,
549
+ // the bundle is synchronously available elsewhere.
550
+ // We can query sync assets available via reachableRoots. If the parent has
551
+ // the bundleRoot by reachableRoots AND ancestorAssets, internalize it.
552
+ for (let [id, bundleRootId] of bundleRootGraph.nodes.entries()) {
553
+ if (bundleRootId == null || id === rootNodeId) continue;
554
+ let bundleRoot = assets[bundleRootId];
555
+ if (manualAssetToConfig.has(bundleRoot)) {
556
+ // We internalize for MSBs later, we should never delete MSBs
557
+ continue;
558
+ }
559
+ let parentRoots = bundleRootGraph.getNodeIdsConnectedTo(id, _graph().ALL_EDGE_TYPES);
560
+ let canDelete = getBundleFromBundleRoot(bundleRoot).bundleBehavior !== 'isolated';
561
+ if (parentRoots.length === 0) continue;
562
+ for (let parentId of parentRoots) {
563
+ var _ancestorAssets$paren;
564
+ if (parentId === rootNodeId) {
565
+ // connected to root.
566
+ canDelete = false;
567
+ continue;
568
+ }
569
+ if (reachableAssets[parentId].has(bundleRootId) || (_ancestorAssets$paren = ancestorAssets[parentId]) !== null && _ancestorAssets$paren !== void 0 && _ancestorAssets$paren.has(bundleRootId)) {
570
+ let parentAssetId = (0, _nullthrows().default)(bundleRootGraph.getNode(parentId));
571
+ let parent = assets[parentAssetId];
572
+ let parentBundle = bundleGraph.getNode((0, _nullthrows().default)(bundles.get(parent.id)));
573
+ (0, _assert().default)(parentBundle != null && parentBundle !== 'root');
574
+ if (!parentBundle.internalizedAssets) {
575
+ parentBundle.internalizedAssets = new (_graph().BitSet)(assets.length);
576
+ }
577
+ parentBundle.internalizedAssets.add(bundleRootId);
578
+ } else {
579
+ canDelete = false;
580
+ }
581
+ }
582
+ if (canDelete) {
583
+ deleteBundle(bundleRoot);
584
+ }
585
+ }
586
+ function assignInlineConstants(parentAsset, bundle) {
587
+ for (let inlineConstant of inlineConstantDeps.get(parentAsset)) {
588
+ if (!bundle.assets.has(inlineConstant)) {
589
+ bundle.assets.add(inlineConstant);
590
+ bundle.size += inlineConstant.stats.size;
591
+ }
592
+ }
593
+ }
594
+
595
+ // Step Insert Or Share: Place all assets into bundles or create shared bundles. Each asset
596
+ // is placed into a single bundle based on the bundle entries it is reachable from.
597
+ // This creates a maximally code split bundle graph with no duplication.
598
+ let reachable = new (_graph().BitSet)(assets.length);
599
+ let reachableNonEntries = new (_graph().BitSet)(assets.length);
600
+ let reachableIntersection = new (_graph().BitSet)(assets.length);
601
+ for (let i = 0; i < assets.length; i++) {
602
+ let asset = assets[i];
603
+ let manualSharedObject = manualAssetToConfig.get(asset);
604
+ if (bundleRoots.has(asset) && inlineConstantDeps.get(asset).size > 0) {
605
+ let entryBundleId = (0, _nullthrows().default)(bundleRoots.get(asset))[0];
606
+ let entryBundle = (0, _nullthrows().default)(bundleGraph.getNode(entryBundleId));
607
+ (0, _assert().default)(entryBundle !== 'root');
608
+ assignInlineConstants(asset, entryBundle);
609
+ }
610
+ if (asset.meta.isConstantModule === true) {
611
+ // Ignore constant modules as they are placed with their direct parents
612
+ continue;
613
+ }
614
+
615
+ // Unreliable bundleRoot assets which need to pulled in by shared bundles or other means.
616
+ // Filter out entries, since they can't have shared bundles.
617
+ // Neither can non-splittable, isolated, or needing of stable name bundles.
618
+ // Reserve those filtered out bundles since we add the asset back into them.
619
+ reachableNonEntries.clear();
620
+ reachableRoots[i].forEach(nodeId => {
621
+ var _ancestorAssets$nodeI;
622
+ let assetId = bundleRootGraph.getNode(nodeId);
623
+ if (assetId == null) return; // deleted
624
+ let a = assets[assetId];
625
+ if (entries.has(a) || !a.isBundleSplittable || bundleRoots.get(a) && (getBundleFromBundleRoot(a).needsStableName || getBundleFromBundleRoot(a).bundleBehavior === 'isolated')) {
626
+ // Add asset to non-splittable bundles.
627
+ addAssetToBundleRoot(asset, a);
628
+ } else if (!((_ancestorAssets$nodeI = ancestorAssets[nodeId]) !== null && _ancestorAssets$nodeI !== void 0 && _ancestorAssets$nodeI.has(i))) {
629
+ // Filter out bundles from this asset's reachable array if
630
+ // bundle does not contain the asset in its ancestry
631
+ reachableNonEntries.add(assetId);
632
+ }
633
+ });
634
+ reachable.bits.set(reachableNonEntries.bits);
635
+
636
+ // If we encounter a "manual" asset, draw an edge from reachable to its MSB
637
+ if (manualSharedObject && !reachable.empty()) {
638
+ let bundle;
639
+ let bundleId;
640
+ let manualSharedBundleKey = manualSharedObject.name + ',' + asset.type;
641
+ let sourceBundles = [];
642
+ reachable.forEach(id => {
643
+ sourceBundles.push((0, _nullthrows().default)(bundleRoots.get(assets[id]))[0]);
644
+ });
645
+ if (!manualSharedMap.has(manualSharedBundleKey)) {
646
+ let firstSourceBundle = (0, _nullthrows().default)(bundleGraph.getNode(sourceBundles[0]));
647
+ (0, _assert().default)(firstSourceBundle !== 'root');
648
+ bundle = createBundle({
649
+ env: firstSourceBundle.env,
650
+ manualSharedBundle: manualSharedObject === null || manualSharedObject === void 0 ? void 0 : manualSharedObject.name,
651
+ sourceBundles: new Set(sourceBundles),
652
+ target: firstSourceBundle.target,
653
+ type: asset.type,
654
+ uniqueKey: manualSharedBundleKey
655
+ });
656
+ bundle.assets.add(asset);
657
+ bundleId = bundleGraph.addNode(bundle);
658
+ manualSharedMap.set(manualSharedBundleKey, bundleId);
659
+ } else {
660
+ bundleId = (0, _nullthrows().default)(manualSharedMap.get(manualSharedBundleKey));
661
+ bundle = (0, _nullthrows().default)(bundleGraph.getNode(bundleId));
662
+ (0, _assert().default)(bundle != null && bundle !== 'root', 'We tried to use the root incorrectly');
663
+ if (!bundle.assets.has(asset)) {
664
+ bundle.assets.add(asset);
665
+ bundle.size += asset.stats.size;
666
+ }
667
+ for (let s of sourceBundles) {
668
+ if (s != bundleId) {
669
+ bundle.sourceBundles.add(s);
670
+ }
671
+ }
672
+ }
673
+ for (let sourceBundleId of sourceBundles) {
674
+ if (bundleId !== sourceBundleId) {
675
+ bundleGraph.addEdge(sourceBundleId, bundleId);
676
+ }
677
+ }
678
+ dependencyBundleGraph.addNodeByContentKeyIfNeeded(String(bundleId), {
679
+ value: bundle,
680
+ type: 'bundle'
681
+ });
682
+ continue;
683
+ }
684
+
685
+ // Finally, filter out bundleRoots (bundles) from this assets
686
+ // reachable if they are subgraphs, and reuse that subgraph bundle
687
+ // by drawing an edge. Essentially, if two bundles within an asset's
688
+ // reachable array, have an ancestor-subgraph relationship, draw that edge.
689
+ // This allows for us to reuse a bundle instead of making a shared bundle if
690
+ // a bundle represents the exact set of assets a set of bundles would share
691
+
692
+ // if a bundle b is a subgraph of another bundle f, reuse it, drawing an edge between the two
693
+ if (config.disableSharedBundles === false) {
694
+ reachableNonEntries.forEach(candidateId => {
695
+ let candidateSourceBundleRoot = assets[candidateId];
696
+ let candidateSourceBundleId = (0, _nullthrows().default)(bundleRoots.get(candidateSourceBundleRoot))[0];
697
+ if (candidateSourceBundleRoot.env.isIsolated()) {
698
+ return;
699
+ }
700
+ let reuseableBundleId = bundles.get(asset.id);
701
+ if (reuseableBundleId != null) {
702
+ reachable.delete(candidateId);
703
+ bundleGraph.addEdge(candidateSourceBundleId, reuseableBundleId);
704
+ let reusableBundle = bundleGraph.getNode(reuseableBundleId);
705
+ (0, _assert().default)(reusableBundle !== 'root' && reusableBundle != null);
706
+ reusableBundle.sourceBundles.add(candidateSourceBundleId);
707
+ } else {
708
+ // Asset is not a bundleRoot, but if its ancestor bundle (in the asset's reachable) can be
709
+ // reused as a subgraph of another bundleRoot in its reachable, reuse it
710
+ reachableIntersection.bits.set(reachableNonEntries.bits);
711
+ reachableIntersection.intersect(reachableAssets[(0, _nullthrows().default)(assetToBundleRootNodeId.get(candidateSourceBundleRoot))]);
712
+ reachableIntersection.forEach(otherCandidateId => {
713
+ // In the case of a circular dependency, you may end up with two
714
+ // reusable bundles that each delete the other, leaving no reusable
715
+ // bundles actually reachable. This check is to avoid assigning the
716
+ // asset to a reusable bundle that has already been marked unreachable.
717
+ if (!reachable.has(otherCandidateId)) return;
718
+ let otherReuseCandidate = assets[otherCandidateId];
719
+ if (candidateSourceBundleRoot === otherReuseCandidate) return;
720
+ let reusableBundleId = (0, _nullthrows().default)(bundles.get(otherReuseCandidate.id));
721
+ reachable.delete(candidateId);
722
+ bundleGraph.addEdge((0, _nullthrows().default)(bundles.get(candidateSourceBundleRoot.id)), reusableBundleId);
723
+ let reusableBundle = bundleGraph.getNode(reusableBundleId);
724
+ (0, _assert().default)(reusableBundle !== 'root' && reusableBundle != null);
725
+ reusableBundle.sourceBundles.add(candidateSourceBundleId);
726
+ });
727
+ }
728
+ });
729
+ }
730
+ let reachableArray = [];
731
+ reachable.forEach(id => {
732
+ reachableArray.push(assets[id]);
733
+ });
734
+
735
+ // Create shared bundles for splittable bundles.
736
+ if (config.disableSharedBundles === false && reachableArray.length > config.minBundles) {
737
+ let sourceBundles = reachableArray.map(a => (0, _nullthrows().default)(bundleRoots.get(a))[0]);
738
+ let key = reachableArray.map(a => a.id).join(',') + '.' + asset.type;
739
+ let bundleId = bundles.get(key);
740
+ let bundle;
741
+ if (bundleId == null) {
742
+ let firstSourceBundle = (0, _nullthrows().default)(bundleGraph.getNode(sourceBundles[0]));
743
+ (0, _assert().default)(firstSourceBundle !== 'root');
744
+ bundle = createBundle({
745
+ env: firstSourceBundle.env,
746
+ sourceBundles: new Set(sourceBundles),
747
+ target: firstSourceBundle.target,
748
+ type: asset.type
749
+ });
750
+ let sharedInternalizedAssets = firstSourceBundle.internalizedAssets ? firstSourceBundle.internalizedAssets.clone() : new (_graph().BitSet)(assets.length);
751
+ for (let p of sourceBundles) {
752
+ let parentBundle = (0, _nullthrows().default)(bundleGraph.getNode(p));
753
+ (0, _assert().default)(parentBundle !== 'root');
754
+ if (parentBundle === firstSourceBundle) continue;
755
+ if (parentBundle.internalizedAssets) {
756
+ sharedInternalizedAssets.intersect(parentBundle.internalizedAssets);
757
+ } else {
758
+ sharedInternalizedAssets.clear();
759
+ }
760
+ }
761
+ bundle.internalizedAssets = sharedInternalizedAssets;
762
+ bundleId = bundleGraph.addNode(bundle);
763
+ bundles.set(key, bundleId);
764
+ } else {
765
+ bundle = (0, _nullthrows().default)(bundleGraph.getNode(bundleId));
766
+ (0, _assert().default)(bundle !== 'root');
767
+ }
768
+ bundle.assets.add(asset);
769
+ bundle.size += asset.stats.size;
770
+ assignInlineConstants(asset, bundle);
771
+ for (let sourceBundleId of sourceBundles) {
772
+ if (bundleId !== sourceBundleId) {
773
+ bundleGraph.addEdge(sourceBundleId, bundleId);
774
+ }
775
+ }
776
+ dependencyBundleGraph.addNodeByContentKeyIfNeeded(String(bundleId), {
777
+ value: bundle,
778
+ type: 'bundle'
779
+ });
780
+ } else if (config.disableSharedBundles === true || reachableArray.length <= config.minBundles) {
781
+ for (let root of reachableArray) {
782
+ addAssetToBundleRoot(asset, root);
783
+ }
784
+ }
785
+ }
786
+ let manualSharedBundleIds = new Set([...manualSharedMap.values()]);
787
+ // Step split manual shared bundles for those that have the "split" property set
788
+ let remainderMap = new (_utils().DefaultMap)(() => []);
789
+ for (let id of manualSharedMap.values()) {
790
+ let manualBundle = bundleGraph.getNode(id);
791
+ (0, _assert().default)(manualBundle !== 'root' && manualBundle != null);
792
+ if (manualBundle.sourceBundles.size > 0) {
793
+ var _manualAssetToConfig$;
794
+ let firstSourceBundle = (0, _nullthrows().default)(bundleGraph.getNode([...manualBundle.sourceBundles][0]));
795
+ (0, _assert().default)(firstSourceBundle !== 'root');
796
+ let firstAsset = [...manualBundle.assets][0];
797
+ let manualSharedObject = manualAssetToConfig.get(firstAsset);
798
+ (0, _assert().default)(manualSharedObject != null);
799
+ let modNum = (_manualAssetToConfig$ = manualAssetToConfig.get(firstAsset)) === null || _manualAssetToConfig$ === void 0 ? void 0 : _manualAssetToConfig$.split;
800
+ if (modNum != null) {
801
+ for (let a of [...manualBundle.assets]) {
802
+ let numRep = getBigIntFromContentKey(a.id);
803
+ // $FlowFixMe Flow doesn't know about BigInt
804
+ let r = Number(numRep % BigInt(modNum));
805
+ remainderMap.get(r).push(a);
806
+ }
807
+ for (let i = 1; i < [...remainderMap.keys()].length; i++) {
808
+ let bundle = createBundle({
809
+ env: firstSourceBundle.env,
810
+ manualSharedBundle: manualSharedObject.name,
811
+ sourceBundles: manualBundle.sourceBundles,
812
+ target: firstSourceBundle.target,
813
+ type: firstSourceBundle.type,
814
+ uniqueKey: manualSharedObject.name + firstSourceBundle.type + i
815
+ });
816
+ bundle.internalizedAssets = manualBundle.internalizedAssets;
817
+ let bundleId = bundleGraph.addNode(bundle);
818
+ manualSharedBundleIds.add(bundleId);
819
+ for (let sourceBundleId of manualBundle.sourceBundles) {
820
+ if (bundleId !== sourceBundleId) {
821
+ bundleGraph.addEdge(sourceBundleId, bundleId);
822
+ }
823
+ }
824
+ for (let sp of remainderMap.get(i)) {
825
+ bundle.assets.add(sp);
826
+ bundle.size += sp.stats.size;
827
+ manualBundle.assets.delete(sp);
828
+ manualBundle.size -= sp.stats.size;
829
+ }
830
+ }
831
+ }
832
+ }
833
+ }
834
+
835
+ // Step insert constant modules into manual shared bundles.
836
+ // We have to do this separately as they're the only case where a single asset can
837
+ // match multiple MSB's
838
+ for (let [asset, msbs] of constantModuleToMSB.entries()) {
839
+ for (let manualSharedObject of msbs) {
840
+ let bundleId = manualSharedMap.get(manualSharedObject.name + ',js');
841
+ if (bundleId == null) continue;
842
+ let bundle = (0, _nullthrows().default)(bundleGraph.getNode(bundleId));
843
+ (0, _assert().default)(bundle != null && bundle !== 'root', 'We tried to use the root incorrectly');
844
+ if (!bundle.assets.has(asset)) {
845
+ bundle.assets.add(asset);
846
+ bundle.size += asset.stats.size;
847
+ }
848
+ }
849
+ }
850
+
851
+ // Step Merge Share Bundles: Merge any shared bundles under the minimum bundle size back into
852
+ // their source bundles, and remove the bundle.
853
+ // We should include "bundle reuse" as shared bundles that may be removed but the bundle itself would have to be retained
854
+ for (let [bundleNodeId, bundle] of bundleGraph.nodes.entries()) {
855
+ if (!bundle || bundle === 'root') continue;
856
+ if (bundle.sourceBundles.size > 0 && bundle.mainEntryAsset == null && bundle.size < config.minBundleSize && !manualSharedBundleIds.has(bundleNodeId)) {
857
+ removeBundle(bundleGraph, bundleNodeId, assetReference);
858
+ }
859
+ }
860
+ let modifiedSourceBundles = new Set();
861
+
862
+ // Step Remove Shared Bundles: Remove shared bundles from bundle groups that hit the parallel request limit.
863
+ if (config.disableSharedBundles === false) {
864
+ for (let bundleGroupId of bundleGraph.getNodeIdsConnectedFrom(rootNodeId)) {
865
+ // Find shared bundles in this bundle group.
866
+ let bundleId = bundleGroupId;
867
+
868
+ // We should include "bundle reuse" as shared bundles that may be removed but the bundle itself would have to be retained
869
+ let bundleIdsInGroup = getBundlesForBundleGroup(bundleId); //get all bundlegrups this bundle is an ancestor of
870
+
871
+ // Filter out inline assests as they should not contribute to PRL
872
+ let numBundlesContributingToPRL = bundleIdsInGroup.reduce((count, b) => {
873
+ let bundle = (0, _nullthrows().default)(bundleGraph.getNode(b));
874
+ (0, _assert().default)(bundle !== 'root');
875
+ return count + (bundle.bundleBehavior !== 'inline');
876
+ }, 0);
877
+ if (numBundlesContributingToPRL > config.maxParallelRequests) {
878
+ let sharedBundleIdsInBundleGroup = bundleIdsInGroup.filter(b => {
879
+ let bundle = (0, _nullthrows().default)(bundleGraph.getNode(b));
880
+ // shared bundles must have source bundles, we could have a bundle
881
+ // connected to another bundle that isnt a shared bundle, so check
882
+ return bundle !== 'root' && bundle.sourceBundles.size > 0 && bundleId != b && !manualSharedBundleIds.has(b);
883
+ });
884
+
885
+ // Sort the bundles so the smallest ones are removed first.
886
+ let sharedBundlesInGroup = sharedBundleIdsInBundleGroup.map(id => ({
887
+ id,
888
+ bundle: (0, _nullthrows().default)(bundleGraph.getNode(id))
889
+ })).map(({
890
+ id,
891
+ bundle
892
+ }) => {
893
+ // For Flow
894
+ (0, _assert().default)(bundle !== 'root');
895
+ return {
896
+ id,
897
+ bundle
898
+ };
899
+ }).sort((a, b) => b.bundle.size - a.bundle.size);
900
+
901
+ // Remove bundles until the bundle group is within the parallel request limit.
902
+ while (sharedBundlesInGroup.length > 0 && numBundlesContributingToPRL > config.maxParallelRequests) {
903
+ let bundleTuple = sharedBundlesInGroup.pop();
904
+ let bundleToRemove = bundleTuple.bundle;
905
+ let bundleIdToRemove = bundleTuple.id;
906
+ //TODO add integration test where bundles in bunlde group > max parallel request limit & only remove a couple shared bundles
907
+ // but total # bundles still exceeds limit due to non shared bundles
908
+
909
+ // Add all assets in the shared bundle into the source bundles that are within this bundle group.
910
+ let sourceBundles = [...bundleToRemove.sourceBundles].filter(b => bundleIdsInGroup.includes(b));
911
+ for (let sourceBundleId of sourceBundles) {
912
+ let sourceBundle = (0, _nullthrows().default)(bundleGraph.getNode(sourceBundleId));
913
+ (0, _assert().default)(sourceBundle !== 'root');
914
+ modifiedSourceBundles.add(sourceBundle);
915
+ bundleToRemove.sourceBundles.delete(sourceBundleId);
916
+ for (let asset of bundleToRemove.assets) {
917
+ addAssetToBundleRoot(asset, (0, _nullthrows().default)(sourceBundle.mainEntryAsset));
918
+ }
919
+ //This case is specific to reused bundles, which can have shared bundles attached to it
920
+ for (let childId of bundleGraph.getNodeIdsConnectedFrom(bundleIdToRemove)) {
921
+ let child = bundleGraph.getNode(childId);
922
+ (0, _assert().default)(child !== 'root' && child != null);
923
+ child.sourceBundles.add(sourceBundleId);
924
+ bundleGraph.addEdge(sourceBundleId, childId);
925
+ }
926
+ // needs to add test case where shared bundle is removed from ONE bundlegroup but not from the whole graph!
927
+ // Remove the edge from this bundle group to the shared bundle.
928
+ // If there is now only a single bundle group that contains this bundle,
929
+ // merge it into the remaining source bundles. If it is orphaned entirely, remove it.
930
+ let incomingNodeCount = bundleGraph.getNodeIdsConnectedTo(bundleIdToRemove).length;
931
+ if (incomingNodeCount <= 2 &&
932
+ //Never fully remove reused bundles
933
+ bundleToRemove.mainEntryAsset == null) {
934
+ // If one bundle group removes a shared bundle, but the other *can* keep it, still remove because that shared bundle is pointless (only one source bundle)
935
+ removeBundle(bundleGraph, bundleIdToRemove, assetReference);
936
+ // Stop iterating through bundleToRemove's sourceBundles as the bundle has been removed.
937
+ break;
938
+ } else {
939
+ bundleGraph.removeEdge(sourceBundleId, bundleIdToRemove);
940
+ }
941
+ }
942
+ numBundlesContributingToPRL--;
943
+ }
944
+ }
945
+ }
946
+ }
947
+ function getBigIntFromContentKey(contentKey) {
948
+ let b = Buffer.alloc(64);
949
+ b.write(contentKey);
950
+ // $FlowFixMe Flow doesn't have BigInt types in this version
951
+ return b.readBigInt64BE();
952
+ }
953
+ // Fix asset order in source bundles as they are likely now incorrect after shared bundle deletion
954
+ if (modifiedSourceBundles.size > 0) {
955
+ let assetOrderMap = new Map(assets.map((a, index) => [a, index]));
956
+ for (let bundle of modifiedSourceBundles) {
957
+ bundle.assets = new Set([...bundle.assets].sort((a, b) => {
958
+ let aIndex = (0, _nullthrows().default)(assetOrderMap.get(a));
959
+ let bIndex = (0, _nullthrows().default)(assetOrderMap.get(b));
960
+ return aIndex - bIndex;
961
+ }));
962
+ }
963
+ }
964
+ function deleteBundle(bundleRoot) {
965
+ bundleGraph.removeNode((0, _nullthrows().default)(bundles.get(bundleRoot.id)));
966
+ bundleRoots.delete(bundleRoot);
967
+ bundles.delete(bundleRoot.id);
968
+ let bundleRootId = assetToBundleRootNodeId.get(bundleRoot);
969
+ if (bundleRootId != null && bundleRootGraph.hasNode(bundleRootId)) {
970
+ bundleRootGraph.removeNode(bundleRootId);
971
+ }
972
+ }
973
+ function getBundlesForBundleGroup(bundleGroupId) {
974
+ let bundlesInABundleGroup = [];
975
+ bundleGraph.traverse(nodeId => {
976
+ bundlesInABundleGroup.push(nodeId);
977
+ }, bundleGroupId);
978
+ return bundlesInABundleGroup;
979
+ }
980
+ function getBundleFromBundleRoot(bundleRoot) {
981
+ let bundle = bundleGraph.getNode((0, _nullthrows().default)(bundleRoots.get(bundleRoot))[0]);
982
+ (0, _assert().default)(bundle !== 'root' && bundle != null);
983
+ return bundle;
984
+ }
985
+ function addAssetToBundleRoot(asset, bundleRoot) {
986
+ let [bundleId, bundleGroupId] = (0, _nullthrows().default)(bundleRoots.get(bundleRoot));
987
+ let bundle = (0, _nullthrows().default)(bundleGraph.getNode(bundleId));
988
+ (0, _assert().default)(bundle !== 'root');
989
+ if (asset.type !== bundle.type) {
990
+ let bundleGroup = (0, _nullthrows().default)(bundleGraph.getNode(bundleGroupId));
991
+ (0, _assert().default)(bundleGroup !== 'root');
992
+ let key = (0, _nullthrows().default)(bundleGroup.mainEntryAsset).id + '.' + asset.type;
993
+ let typeChangeBundleId = bundles.get(key);
994
+ if (typeChangeBundleId == null) {
995
+ let typeChangeBundle = createBundle({
996
+ uniqueKey: key,
997
+ needsStableName: bundle.needsStableName,
998
+ bundleBehavior: bundle.bundleBehavior,
999
+ type: asset.type,
1000
+ target: bundle.target,
1001
+ env: bundle.env
1002
+ });
1003
+ typeChangeBundleId = bundleGraph.addNode(typeChangeBundle);
1004
+ bundleGraph.addEdge(bundleId, typeChangeBundleId);
1005
+ bundles.set(key, typeChangeBundleId);
1006
+ bundle = typeChangeBundle;
1007
+ } else {
1008
+ bundle = (0, _nullthrows().default)(bundleGraph.getNode(typeChangeBundleId));
1009
+ (0, _assert().default)(bundle !== 'root');
1010
+ }
1011
+ }
1012
+ bundle.assets.add(asset);
1013
+ bundle.size += asset.stats.size;
1014
+ assignInlineConstants(asset, bundle);
1015
+ }
1016
+ function removeBundle(bundleGraph, bundleId, assetReference) {
1017
+ let bundle = (0, _nullthrows().default)(bundleGraph.getNode(bundleId));
1018
+ (0, _assert().default)(bundle !== 'root');
1019
+ for (let asset of bundle.assets) {
1020
+ assetReference.set(asset, assetReference.get(asset).filter(t => !t.includes(bundle)));
1021
+ for (let sourceBundleId of bundle.sourceBundles) {
1022
+ let sourceBundle = (0, _nullthrows().default)(bundleGraph.getNode(sourceBundleId));
1023
+ (0, _assert().default)(sourceBundle !== 'root');
1024
+ addAssetToBundleRoot(asset, (0, _nullthrows().default)(sourceBundle.mainEntryAsset));
1025
+ }
1026
+ }
1027
+ bundleGraph.removeNode(bundleId);
1028
+ }
1029
+ return {
1030
+ assets,
1031
+ bundleGraph,
1032
+ dependencyBundleGraph,
1033
+ bundleGroupBundleIds,
1034
+ assetReference,
1035
+ manualAssetToBundle
1036
+ };
1037
+ }
1038
+ function createBundle(opts) {
1039
+ if (opts.asset == null) {
1040
+ return {
1041
+ assets: new Set(),
1042
+ bundleBehavior: opts.bundleBehavior,
1043
+ env: (0, _nullthrows().default)(opts.env),
1044
+ mainEntryAsset: null,
1045
+ manualSharedBundle: opts.manualSharedBundle,
1046
+ needsStableName: Boolean(opts.needsStableName),
1047
+ size: 0,
1048
+ sourceBundles: opts.sourceBundles ?? new Set(),
1049
+ target: opts.target,
1050
+ type: (0, _nullthrows().default)(opts.type),
1051
+ uniqueKey: opts.uniqueKey
1052
+ };
1053
+ }
1054
+ let asset = (0, _nullthrows().default)(opts.asset);
1055
+ return {
1056
+ assets: new Set([asset]),
1057
+ bundleBehavior: opts.bundleBehavior ?? asset.bundleBehavior,
1058
+ env: opts.env ?? asset.env,
1059
+ mainEntryAsset: asset,
1060
+ manualSharedBundle: opts.manualSharedBundle,
1061
+ needsStableName: Boolean(opts.needsStableName),
1062
+ size: asset.stats.size,
1063
+ sourceBundles: opts.sourceBundles ?? new Set(),
1064
+ target: opts.target,
1065
+ type: opts.type ?? asset.type,
1066
+ uniqueKey: opts.uniqueKey
1067
+ };
1068
+ }