@atlaspack/bundler-default 2.14.4 → 2.14.5-canary.10

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright (c) 2024 Atlassian US., Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.findMergeCandidates = findMergeCandidates;
7
+ function _assert() {
8
+ const data = _interopRequireDefault(require("assert"));
9
+ _assert = function () {
10
+ return data;
11
+ };
12
+ return data;
13
+ }
14
+ function _nullthrows() {
15
+ const data = _interopRequireDefault(require("nullthrows"));
16
+ _nullthrows = function () {
17
+ return data;
18
+ };
19
+ return data;
20
+ }
21
+ function _graph() {
22
+ const data = require("@atlaspack/graph");
23
+ _graph = function () {
24
+ return data;
25
+ };
26
+ return data;
27
+ }
28
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
29
+ // Returns a decimal showing the proportion source bundles are common to
30
+ // both bundles versus the total number of source bundles.
31
+ function scoreBundleMerge(bundleA, bundleB) {
32
+ let sharedSourceBundles = 0;
33
+ let allSourceBundles = new Set([...bundleA.sourceBundles, ...bundleB.sourceBundles]);
34
+ for (let bundle of bundleB.sourceBundles) {
35
+ if (bundleA.sourceBundles.has(bundle)) {
36
+ sharedSourceBundles++;
37
+ }
38
+ }
39
+ return sharedSourceBundles / allSourceBundles.size;
40
+ }
41
+ function getMergeClusters(graph, candidates) {
42
+ let clusters = [];
43
+ for (let candidate of candidates) {
44
+ let cluster = [];
45
+ graph.traverse(nodeId => {
46
+ cluster.push((0, _nullthrows().default)(graph.getNode(nodeId)));
47
+ // Remove node from candidates as it has already been processed
48
+ candidates.delete(nodeId);
49
+ }, candidate);
50
+ clusters.push(cluster);
51
+ }
52
+ return clusters;
53
+ }
54
+ function findMergeCandidates(bundleGraph, bundles, threshold) {
55
+ let graph = new (_graph().ContentGraph)();
56
+ let seen = new Set();
57
+ let candidates = new Set();
58
+
59
+ // Build graph of clustered merge candidates
60
+ for (let bundleId of bundles) {
61
+ let bundle = bundleGraph.getNode(bundleId);
62
+ (0, _assert().default)(bundle && bundle !== 'root');
63
+ if (bundle.type !== 'js') {
64
+ continue;
65
+ }
66
+ for (let otherBundleId of bundles) {
67
+ if (bundleId === otherBundleId) {
68
+ continue;
69
+ }
70
+ let key = [bundleId, otherBundleId].sort().join(':');
71
+ if (seen.has(key)) {
72
+ continue;
73
+ }
74
+ seen.add(key);
75
+ let otherBundle = bundleGraph.getNode(otherBundleId);
76
+ (0, _assert().default)(otherBundle && otherBundle !== 'root');
77
+ let score = scoreBundleMerge(bundle, otherBundle);
78
+ if (score >= threshold) {
79
+ let bundleNode = graph.addNodeByContentKeyIfNeeded(bundleId.toString(), bundleId);
80
+ let otherBundleNode = graph.addNodeByContentKeyIfNeeded(otherBundleId.toString(), otherBundleId);
81
+
82
+ // Add edge in both directions
83
+ graph.addEdge(bundleNode, otherBundleNode);
84
+ graph.addEdge(otherBundleNode, bundleNode);
85
+ candidates.add(bundleNode);
86
+ candidates.add(otherBundleNode);
87
+ }
88
+ }
89
+ }
90
+ return getMergeClusters(graph, candidates);
91
+ }
@@ -53,14 +53,16 @@ const HTTP_OPTIONS = {
53
53
  manualSharedBundles: [],
54
54
  minBundleSize: 30000,
55
55
  maxParallelRequests: 6,
56
- disableSharedBundles: false
56
+ disableSharedBundles: false,
57
+ sharedBundleMergeThreshold: 1
57
58
  },
58
59
  '2': {
59
60
  minBundles: 1,
60
61
  manualSharedBundles: [],
61
62
  minBundleSize: 20000,
62
63
  maxParallelRequests: 25,
63
- disableSharedBundles: false
64
+ disableSharedBundles: false,
65
+ sharedBundleMergeThreshold: 1
64
66
  }
65
67
  };
66
68
  const CONFIG_SCHEMA = {
@@ -115,6 +117,9 @@ const CONFIG_SCHEMA = {
115
117
  },
116
118
  loadConditionalBundlesInParallel: {
117
119
  type: 'boolean'
120
+ },
121
+ sharedBundleMergeThreshold: {
122
+ type: 'number'
118
123
  }
119
124
  },
120
125
  additionalProperties: false
@@ -172,6 +177,7 @@ async function loadBundlerConfig(config, options, logger) {
172
177
  return {
173
178
  minBundles: modeConfig.minBundles ?? defaults.minBundles,
174
179
  minBundleSize: modeConfig.minBundleSize ?? defaults.minBundleSize,
180
+ sharedBundleMergeThreshold: modeConfig.sharedBundleMergeThreshold ?? defaults.sharedBundleMergeThreshold,
175
181
  maxParallelRequests: modeConfig.maxParallelRequests ?? defaults.maxParallelRequests,
176
182
  projectRoot: options.projectRoot,
177
183
  disableSharedBundles: modeConfig.disableSharedBundles ?? defaults.disableSharedBundles,
package/lib/idealGraph.js CHANGED
@@ -47,6 +47,7 @@ function _nullthrows() {
47
47
  };
48
48
  return data;
49
49
  }
50
+ var _bundleMerge = require("./bundleMerge");
50
51
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
51
52
  /* BundleRoot - An asset that is the main entry of a Bundle. */
52
53
  const dependencyPriorityEdges = {
@@ -848,6 +849,12 @@ function createIdealGraph(assetGraph, config, entries, logger) {
848
849
  }
849
850
  }
850
851
 
852
+ // Step merge shared bundles that meet the overlap threshold
853
+ // This step is skipped by default as the threshold defaults to 1
854
+ if (config.sharedBundleMergeThreshold < 1) {
855
+ mergeOverlapBundles();
856
+ }
857
+
851
858
  // Step Merge Share Bundles: Merge any shared bundles under the minimum bundle size back into
852
859
  // their source bundles, and remove the bundle.
853
860
  // We should include "bundle reuse" as shared bundles that may be removed but the bundle itself would have to be retained
@@ -857,9 +864,9 @@ function createIdealGraph(assetGraph, config, entries, logger) {
857
864
  removeBundle(bundleGraph, bundleNodeId, assetReference);
858
865
  }
859
866
  }
860
- let modifiedSourceBundles = new Set();
861
867
 
862
868
  // Step Remove Shared Bundles: Remove shared bundles from bundle groups that hit the parallel request limit.
869
+ let modifiedSourceBundles = new Set();
863
870
  if (config.disableSharedBundles === false) {
864
871
  for (let bundleGroupId of bundleGraph.getNodeIdsConnectedFrom(rootNodeId)) {
865
872
  // Find shared bundles in this bundle group.
@@ -944,6 +951,61 @@ function createIdealGraph(assetGraph, config, entries, logger) {
944
951
  }
945
952
  }
946
953
  }
954
+ function mergeBundles(bundleGraph, bundleToKeepId, bundleToRemoveId, assetReference) {
955
+ let bundleToKeep = (0, _nullthrows().default)(bundleGraph.getNode(bundleToKeepId));
956
+ let bundleToRemove = (0, _nullthrows().default)(bundleGraph.getNode(bundleToRemoveId));
957
+ (0, _assert().default)(bundleToKeep !== 'root' && bundleToRemove !== 'root');
958
+ for (let asset of bundleToRemove.assets) {
959
+ bundleToKeep.assets.add(asset);
960
+ bundleToKeep.size += asset.stats.size;
961
+ let newAssetReference = assetReference.get(asset).map(([dep, bundle]) => bundle === bundleToRemove ? [dep, bundleToKeep] : [dep, bundle]);
962
+ assetReference.set(asset, newAssetReference);
963
+ }
964
+ for (let sourceBundleId of bundleToRemove.sourceBundles) {
965
+ if (bundleToKeep.sourceBundles.has(sourceBundleId)) {
966
+ continue;
967
+ }
968
+ bundleToKeep.sourceBundles.add(sourceBundleId);
969
+ bundleGraph.addEdge(sourceBundleId, bundleToKeepId);
970
+ }
971
+
972
+ // Merge any internalized assets
973
+ if (bundleToRemove.internalizedAssets) {
974
+ if (bundleToKeep.internalizedAssets) {
975
+ bundleToKeep.internalizedAssets.union(bundleToRemove.internalizedAssets);
976
+ } else {
977
+ bundleToKeep.internalizedAssets = bundleToRemove.internalizedAssets;
978
+ }
979
+ }
980
+ bundleGraph.removeNode(bundleToRemoveId);
981
+ }
982
+ function mergeOverlapBundles() {
983
+ // Find all shared bundles
984
+ let sharedBundles = new Set();
985
+ bundleGraph.traverse(nodeId => {
986
+ let bundle = bundleGraph.getNode(nodeId);
987
+ if (!bundle) {
988
+ throw new Error(`Unable to find bundle ${nodeId} in bundle graph`);
989
+ }
990
+ if (bundle === 'root') {
991
+ return;
992
+ }
993
+
994
+ // Only consider JS shared bundles and non-reused bundles.
995
+ // These count potentially be considered for merging in future but they're
996
+ // more complicated to merge
997
+ if (bundle.sourceBundles.size > 0 && bundle.manualSharedBundle == null && !bundle.mainEntryAsset && bundle.type === 'js') {
998
+ sharedBundles.add(nodeId);
999
+ }
1000
+ });
1001
+ let clusters = (0, _bundleMerge.findMergeCandidates)(bundleGraph, Array.from(sharedBundles), config.sharedBundleMergeThreshold);
1002
+ for (let cluster of clusters) {
1003
+ let [mergeTarget, ...rest] = cluster;
1004
+ for (let bundleIdToMerge of rest) {
1005
+ mergeBundles(bundleGraph, mergeTarget, bundleIdToMerge, assetReference);
1006
+ }
1007
+ }
1008
+ }
947
1009
  function getBigIntFromContentKey(contentKey) {
948
1010
  let b = Buffer.alloc(64);
949
1011
  b.write(contentKey);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atlaspack/bundler-default",
3
- "version": "2.14.4",
3
+ "version": "2.14.5-canary.10+e28fbeb3a",
4
4
  "license": "(MIT OR Apache-2.0)",
5
5
  "type": "commonjs",
6
6
  "publishConfig": {
@@ -16,12 +16,13 @@
16
16
  "node": ">= 16.0.0"
17
17
  },
18
18
  "dependencies": {
19
- "@atlaspack/diagnostic": "2.14.1",
20
- "@atlaspack/feature-flags": "2.14.2",
21
- "@atlaspack/graph": "3.4.2",
22
- "@atlaspack/plugin": "2.14.4",
23
- "@atlaspack/rust": "3.2.0",
24
- "@atlaspack/utils": "2.14.4",
19
+ "@atlaspack/diagnostic": "2.14.1-canary.78+e28fbeb3a",
20
+ "@atlaspack/feature-flags": "2.14.1-canary.78+e28fbeb3a",
21
+ "@atlaspack/graph": "3.4.1-canary.78+e28fbeb3a",
22
+ "@atlaspack/plugin": "2.14.5-canary.10+e28fbeb3a",
23
+ "@atlaspack/rust": "3.2.1-canary.10+e28fbeb3a",
24
+ "@atlaspack/utils": "2.14.5-canary.10+e28fbeb3a",
25
25
  "nullthrows": "^1.1.1"
26
- }
26
+ },
27
+ "gitHead": "e28fbeb3a609aad3e44af9b8d3d5fd83dda38941"
27
28
  }
@@ -0,0 +1,103 @@
1
+ // @flow strict-local
2
+
3
+ import invariant from 'assert';
4
+ import nullthrows from 'nullthrows';
5
+ import type {NodeId} from '@atlaspack/graph';
6
+ import type {Bundle, IdealBundleGraph} from './idealGraph';
7
+ import {ContentGraph} from '@atlaspack/graph';
8
+
9
+ // Returns a decimal showing the proportion source bundles are common to
10
+ // both bundles versus the total number of source bundles.
11
+ function scoreBundleMerge(bundleA: Bundle, bundleB: Bundle): number {
12
+ let sharedSourceBundles = 0;
13
+ let allSourceBundles = new Set([
14
+ ...bundleA.sourceBundles,
15
+ ...bundleB.sourceBundles,
16
+ ]);
17
+
18
+ for (let bundle of bundleB.sourceBundles) {
19
+ if (bundleA.sourceBundles.has(bundle)) {
20
+ sharedSourceBundles++;
21
+ }
22
+ }
23
+
24
+ return sharedSourceBundles / allSourceBundles.size;
25
+ }
26
+
27
+ function getMergeClusters(
28
+ graph: ContentGraph<NodeId>,
29
+ candidates: Set<NodeId>,
30
+ ): Array<Array<NodeId>> {
31
+ let clusters = [];
32
+
33
+ for (let candidate of candidates) {
34
+ let cluster: Array<NodeId> = [];
35
+
36
+ graph.traverse((nodeId) => {
37
+ cluster.push(nullthrows(graph.getNode(nodeId)));
38
+ // Remove node from candidates as it has already been processed
39
+ candidates.delete(nodeId);
40
+ }, candidate);
41
+
42
+ clusters.push(cluster);
43
+ }
44
+
45
+ return clusters;
46
+ }
47
+
48
+ export function findMergeCandidates(
49
+ bundleGraph: IdealBundleGraph,
50
+ bundles: Array<NodeId>,
51
+ threshold: number,
52
+ ): Array<Array<NodeId>> {
53
+ let graph = new ContentGraph<NodeId>();
54
+ let seen = new Set<string>();
55
+ let candidates = new Set<NodeId>();
56
+
57
+ // Build graph of clustered merge candidates
58
+ for (let bundleId of bundles) {
59
+ let bundle = bundleGraph.getNode(bundleId);
60
+ invariant(bundle && bundle !== 'root');
61
+ if (bundle.type !== 'js') {
62
+ continue;
63
+ }
64
+
65
+ for (let otherBundleId of bundles) {
66
+ if (bundleId === otherBundleId) {
67
+ continue;
68
+ }
69
+
70
+ let key = [bundleId, otherBundleId].sort().join(':');
71
+
72
+ if (seen.has(key)) {
73
+ continue;
74
+ }
75
+ seen.add(key);
76
+
77
+ let otherBundle = bundleGraph.getNode(otherBundleId);
78
+ invariant(otherBundle && otherBundle !== 'root');
79
+
80
+ let score = scoreBundleMerge(bundle, otherBundle);
81
+
82
+ if (score >= threshold) {
83
+ let bundleNode = graph.addNodeByContentKeyIfNeeded(
84
+ bundleId.toString(),
85
+ bundleId,
86
+ );
87
+ let otherBundleNode = graph.addNodeByContentKeyIfNeeded(
88
+ otherBundleId.toString(),
89
+ otherBundleId,
90
+ );
91
+
92
+ // Add edge in both directions
93
+ graph.addEdge(bundleNode, otherBundleNode);
94
+ graph.addEdge(otherBundleNode, bundleNode);
95
+
96
+ candidates.add(bundleNode);
97
+ candidates.add(otherBundleNode);
98
+ }
99
+ }
100
+ }
101
+
102
+ return getMergeClusters(graph, candidates);
103
+ }
@@ -28,6 +28,7 @@ type BaseBundlerConfig = {|
28
28
  disableSharedBundles?: boolean,
29
29
  manualSharedBundles?: ManualSharedBundles,
30
30
  loadConditionalBundlesInParallel?: boolean,
31
+ sharedBundleMergeThreshold?: number,
31
32
  |};
32
33
 
33
34
  type BundlerConfig = {|
@@ -42,6 +43,7 @@ export type ResolvedBundlerConfig = {|
42
43
  disableSharedBundles: boolean,
43
44
  manualSharedBundles: ManualSharedBundles,
44
45
  loadConditionalBundlesInParallel?: boolean,
46
+ sharedBundleMergeThreshold: number,
45
47
  |};
46
48
 
47
49
  function resolveModeConfig(
@@ -76,6 +78,7 @@ const HTTP_OPTIONS = {
76
78
  minBundleSize: 30000,
77
79
  maxParallelRequests: 6,
78
80
  disableSharedBundles: false,
81
+ sharedBundleMergeThreshold: 1,
79
82
  },
80
83
  '2': {
81
84
  minBundles: 1,
@@ -83,6 +86,7 @@ const HTTP_OPTIONS = {
83
86
  minBundleSize: 20000,
84
87
  maxParallelRequests: 25,
85
88
  disableSharedBundles: false,
89
+ sharedBundleMergeThreshold: 1,
86
90
  },
87
91
  };
88
92
 
@@ -139,6 +143,9 @@ const CONFIG_SCHEMA: SchemaEntity = {
139
143
  loadConditionalBundlesInParallel: {
140
144
  type: 'boolean',
141
145
  },
146
+ sharedBundleMergeThreshold: {
147
+ type: 'number',
148
+ },
142
149
  },
143
150
  additionalProperties: false,
144
151
  };
@@ -224,6 +231,9 @@ export async function loadBundlerConfig(
224
231
  return {
225
232
  minBundles: modeConfig.minBundles ?? defaults.minBundles,
226
233
  minBundleSize: modeConfig.minBundleSize ?? defaults.minBundleSize,
234
+ sharedBundleMergeThreshold:
235
+ modeConfig.sharedBundleMergeThreshold ??
236
+ defaults.sharedBundleMergeThreshold,
227
237
  maxParallelRequests:
228
238
  modeConfig.maxParallelRequests ?? defaults.maxParallelRequests,
229
239
  projectRoot: options.projectRoot,
package/src/idealGraph.js CHANGED
@@ -23,6 +23,7 @@ import {DefaultMap, globToRegex} from '@atlaspack/utils';
23
23
  import invariant from 'assert';
24
24
  import nullthrows from 'nullthrows';
25
25
 
26
+ import {findMergeCandidates} from './bundleMerge';
26
27
  import type {ResolvedBundlerConfig} from './bundlerConfig';
27
28
 
28
29
  /* BundleRoot - An asset that is the main entry of a Bundle. */
@@ -67,7 +68,7 @@ export const idealBundleGraphEdges = Object.freeze({
67
68
  conditional: 2,
68
69
  });
69
70
 
70
- type IdealBundleGraph = Graph<
71
+ export type IdealBundleGraph = Graph<
71
72
  Bundle | 'root',
72
73
  $Values<typeof idealBundleGraphEdges>,
73
74
  >;
@@ -1128,6 +1129,12 @@ export function createIdealGraph(
1128
1129
  }
1129
1130
  }
1130
1131
 
1132
+ // Step merge shared bundles that meet the overlap threshold
1133
+ // This step is skipped by default as the threshold defaults to 1
1134
+ if (config.sharedBundleMergeThreshold < 1) {
1135
+ mergeOverlapBundles();
1136
+ }
1137
+
1131
1138
  // Step Merge Share Bundles: Merge any shared bundles under the minimum bundle size back into
1132
1139
  // their source bundles, and remove the bundle.
1133
1140
  // We should include "bundle reuse" as shared bundles that may be removed but the bundle itself would have to be retained
@@ -1143,9 +1150,9 @@ export function createIdealGraph(
1143
1150
  }
1144
1151
  }
1145
1152
 
1153
+ // Step Remove Shared Bundles: Remove shared bundles from bundle groups that hit the parallel request limit.
1146
1154
  let modifiedSourceBundles = new Set();
1147
1155
 
1148
- // Step Remove Shared Bundles: Remove shared bundles from bundle groups that hit the parallel request limit.
1149
1156
  if (config.disableSharedBundles === false) {
1150
1157
  for (let bundleGroupId of bundleGraph.getNodeIdsConnectedFrom(rootNodeId)) {
1151
1158
  // Find shared bundles in this bundle group.
@@ -1249,6 +1256,93 @@ export function createIdealGraph(
1249
1256
  }
1250
1257
  }
1251
1258
 
1259
+ function mergeBundles(
1260
+ bundleGraph: IdealBundleGraph,
1261
+ bundleToKeepId: NodeId,
1262
+ bundleToRemoveId: NodeId,
1263
+ assetReference: DefaultMap<Asset, Array<[Dependency, Bundle]>>,
1264
+ ) {
1265
+ let bundleToKeep = nullthrows(bundleGraph.getNode(bundleToKeepId));
1266
+ let bundleToRemove = nullthrows(bundleGraph.getNode(bundleToRemoveId));
1267
+ invariant(bundleToKeep !== 'root' && bundleToRemove !== 'root');
1268
+ for (let asset of bundleToRemove.assets) {
1269
+ bundleToKeep.assets.add(asset);
1270
+ bundleToKeep.size += asset.stats.size;
1271
+
1272
+ let newAssetReference = assetReference
1273
+ .get(asset)
1274
+ .map(([dep, bundle]) =>
1275
+ bundle === bundleToRemove ? [dep, bundleToKeep] : [dep, bundle],
1276
+ );
1277
+
1278
+ assetReference.set(asset, newAssetReference);
1279
+ }
1280
+
1281
+ for (let sourceBundleId of bundleToRemove.sourceBundles) {
1282
+ if (bundleToKeep.sourceBundles.has(sourceBundleId)) {
1283
+ continue;
1284
+ }
1285
+
1286
+ bundleToKeep.sourceBundles.add(sourceBundleId);
1287
+ bundleGraph.addEdge(sourceBundleId, bundleToKeepId);
1288
+ }
1289
+
1290
+ // Merge any internalized assets
1291
+ if (bundleToRemove.internalizedAssets) {
1292
+ if (bundleToKeep.internalizedAssets) {
1293
+ bundleToKeep.internalizedAssets.union(
1294
+ bundleToRemove.internalizedAssets,
1295
+ );
1296
+ } else {
1297
+ bundleToKeep.internalizedAssets = bundleToRemove.internalizedAssets;
1298
+ }
1299
+ }
1300
+
1301
+ bundleGraph.removeNode(bundleToRemoveId);
1302
+ }
1303
+
1304
+ function mergeOverlapBundles() {
1305
+ // Find all shared bundles
1306
+ let sharedBundles = new Set<NodeId>();
1307
+ bundleGraph.traverse((nodeId) => {
1308
+ let bundle = bundleGraph.getNode(nodeId);
1309
+
1310
+ if (!bundle) {
1311
+ throw new Error(`Unable to find bundle ${nodeId} in bundle graph`);
1312
+ }
1313
+
1314
+ if (bundle === 'root') {
1315
+ return;
1316
+ }
1317
+
1318
+ // Only consider JS shared bundles and non-reused bundles.
1319
+ // These count potentially be considered for merging in future but they're
1320
+ // more complicated to merge
1321
+ if (
1322
+ bundle.sourceBundles.size > 0 &&
1323
+ bundle.manualSharedBundle == null &&
1324
+ !bundle.mainEntryAsset &&
1325
+ bundle.type === 'js'
1326
+ ) {
1327
+ sharedBundles.add(nodeId);
1328
+ }
1329
+ });
1330
+
1331
+ let clusters = findMergeCandidates(
1332
+ bundleGraph,
1333
+ Array.from(sharedBundles),
1334
+ config.sharedBundleMergeThreshold,
1335
+ );
1336
+
1337
+ for (let cluster of clusters) {
1338
+ let [mergeTarget, ...rest] = cluster;
1339
+
1340
+ for (let bundleIdToMerge of rest) {
1341
+ mergeBundles(bundleGraph, mergeTarget, bundleIdToMerge, assetReference);
1342
+ }
1343
+ }
1344
+ }
1345
+
1252
1346
  function getBigIntFromContentKey(contentKey) {
1253
1347
  let b = Buffer.alloc(64);
1254
1348
  b.write(contentKey);