@atlaspack/core 2.24.1 → 2.24.2-dev-ts-project-refs-d30e9754f.0

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.
Files changed (86) hide show
  1. package/LICENSE +201 -0
  2. package/dist/AssetGraph.js +591 -0
  3. package/dist/Atlaspack.js +656 -0
  4. package/dist/AtlaspackConfig.js +324 -0
  5. package/dist/AtlaspackConfig.schema.js +108 -0
  6. package/dist/BundleGraph.js +1628 -0
  7. package/dist/CommittedAsset.js +142 -0
  8. package/dist/Dependency.js +125 -0
  9. package/dist/Environment.js +132 -0
  10. package/dist/EnvironmentManager.js +108 -0
  11. package/dist/IdentifierRegistry.js +38 -0
  12. package/dist/InternalConfig.js +37 -0
  13. package/dist/PackagerRunner.js +531 -0
  14. package/dist/ReporterRunner.js +151 -0
  15. package/dist/RequestTracker.js +1368 -0
  16. package/dist/SymbolPropagation.js +620 -0
  17. package/dist/TargetDescriptor.schema.js +143 -0
  18. package/dist/Transformation.js +487 -0
  19. package/dist/UncommittedAsset.js +315 -0
  20. package/dist/Validation.js +196 -0
  21. package/dist/applyRuntimes.js +305 -0
  22. package/dist/assetUtils.js +168 -0
  23. package/dist/atlaspack-v3/AtlaspackV3.js +70 -0
  24. package/dist/atlaspack-v3/NapiWorkerPool.js +57 -0
  25. package/dist/atlaspack-v3/fs.js +52 -0
  26. package/dist/atlaspack-v3/index.js +25 -0
  27. package/dist/atlaspack-v3/jsCallable.js +16 -0
  28. package/dist/atlaspack-v3/worker/compat/asset-symbols.js +190 -0
  29. package/dist/atlaspack-v3/worker/compat/bitflags.js +94 -0
  30. package/dist/atlaspack-v3/worker/compat/dependency.js +43 -0
  31. package/dist/atlaspack-v3/worker/compat/environment.js +57 -0
  32. package/dist/atlaspack-v3/worker/compat/index.js +25 -0
  33. package/dist/atlaspack-v3/worker/compat/mutable-asset.js +152 -0
  34. package/dist/atlaspack-v3/worker/compat/plugin-config.js +76 -0
  35. package/dist/atlaspack-v3/worker/compat/plugin-logger.js +26 -0
  36. package/dist/atlaspack-v3/worker/compat/plugin-options.js +122 -0
  37. package/dist/atlaspack-v3/worker/compat/plugin-tracer.js +10 -0
  38. package/dist/atlaspack-v3/worker/compat/target.js +14 -0
  39. package/dist/atlaspack-v3/worker/worker.js +292 -0
  40. package/dist/constants.js +17 -0
  41. package/dist/dumpGraphToGraphViz.js +281 -0
  42. package/dist/index.js +62 -0
  43. package/dist/loadAtlaspackPlugin.js +128 -0
  44. package/dist/loadDotEnv.js +41 -0
  45. package/dist/projectPath.js +83 -0
  46. package/dist/public/Asset.js +279 -0
  47. package/dist/public/Bundle.js +224 -0
  48. package/dist/public/BundleGraph.js +359 -0
  49. package/dist/public/BundleGroup.js +53 -0
  50. package/dist/public/Config.js +286 -0
  51. package/dist/public/Dependency.js +138 -0
  52. package/dist/public/Environment.js +278 -0
  53. package/dist/public/MutableBundleGraph.js +277 -0
  54. package/dist/public/PluginOptions.js +80 -0
  55. package/dist/public/Symbols.js +248 -0
  56. package/dist/public/Target.js +69 -0
  57. package/dist/registerCoreWithSerializer.js +38 -0
  58. package/dist/requests/AssetGraphRequest.js +429 -0
  59. package/dist/requests/AssetGraphRequestRust.js +246 -0
  60. package/dist/requests/AssetRequest.js +130 -0
  61. package/dist/requests/AtlaspackBuildRequest.js +60 -0
  62. package/dist/requests/AtlaspackConfigRequest.js +490 -0
  63. package/dist/requests/BundleGraphRequest.js +441 -0
  64. package/dist/requests/ConfigRequest.js +222 -0
  65. package/dist/requests/DevDepRequest.js +204 -0
  66. package/dist/requests/EntryRequest.js +314 -0
  67. package/dist/requests/PackageRequest.js +65 -0
  68. package/dist/requests/PathRequest.js +349 -0
  69. package/dist/requests/TargetRequest.js +1310 -0
  70. package/dist/requests/ValidationRequest.js +49 -0
  71. package/dist/requests/WriteBundleRequest.js +254 -0
  72. package/dist/requests/WriteBundlesRequest.js +165 -0
  73. package/dist/requests/asset-graph-diff.js +126 -0
  74. package/dist/requests/asset-graph-dot.js +131 -0
  75. package/dist/resolveOptions.js +268 -0
  76. package/dist/rustWorkerThreadDylibHack.js +19 -0
  77. package/dist/serializerCore.browser.js +43 -0
  78. package/dist/summarizeRequest.js +39 -0
  79. package/dist/types.js +31 -0
  80. package/dist/utils.js +172 -0
  81. package/dist/worker.js +130 -0
  82. package/lib/AssetGraph.js +1 -0
  83. package/package.json +22 -22
  84. package/src/AssetGraph.ts +1 -0
  85. package/tsconfig.json +55 -2
  86. package/tsconfig.tsbuildinfo +1 -0
@@ -0,0 +1,1628 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.bundleGraphEdgeTypes = void 0;
7
+ const assert_1 = __importDefault(require("assert"));
8
+ const assert_2 = __importDefault(require("assert"));
9
+ const nullthrows_1 = __importDefault(require("nullthrows"));
10
+ const graph_1 = require("@atlaspack/graph");
11
+ const rust_1 = require("@atlaspack/rust");
12
+ const utils_1 = require("@atlaspack/utils");
13
+ const types_1 = require("./types");
14
+ const utils_2 = require("./utils");
15
+ const Environment_1 = require("./public/Environment");
16
+ const projectPath_1 = require("./projectPath");
17
+ const constants_1 = require("./constants");
18
+ const feature_flags_1 = require("@atlaspack/feature-flags");
19
+ const EnvironmentManager_1 = require("./EnvironmentManager");
20
+ exports.bundleGraphEdgeTypes = {
21
+ // A lack of an edge type indicates to follow the edge while traversing
22
+ // the bundle's contents, e.g. `bundle.traverse()` during packaging.
23
+ null: 1,
24
+ // Used for constant-time checks of presence of a dependency or asset in a bundle,
25
+ // avoiding bundle traversal in cases like `isAssetInAncestors`
26
+ contains: 2,
27
+ // Connections between bundles and bundle groups, for quick traversal of the
28
+ // bundle hierarchy.
29
+ bundle: 3,
30
+ // When dependency -> asset: Indicates that the asset a dependency references
31
+ // is contained in another bundle.
32
+ // When dependency -> bundle: Indicates the bundle is necessary for any bundles
33
+ // with the dependency.
34
+ // When bundle -> bundle: Indicates the target bundle is necessary for the
35
+ // source bundle.
36
+ // This type prevents referenced assets from being traversed from dependencies
37
+ // along the untyped edge, and enables traversal to referenced bundles that are
38
+ // not directly connected to bundle group nodes.
39
+ references: 4,
40
+ // Signals that the dependency is internally resolvable via the bundle's ancestry,
41
+ // and that the bundle connected to the dependency is not necessary for the source bundle.
42
+ internal_async: 5,
43
+ // This type is used to mark an edge between a bundle and a conditional bundle.
44
+ // This allows efficient discovery of conditional bundles in packaging
45
+ conditional: 5,
46
+ };
47
+ function makeReadOnlySet(set) {
48
+ return new Proxy(set, {
49
+ get(target, property) {
50
+ if (property === 'delete' || property === 'add' || property === 'clear') {
51
+ return undefined;
52
+ }
53
+ else {
54
+ // @ts-expect-error TS7053
55
+ let value = target[property];
56
+ return typeof value === 'function' ? value.bind(target) : value;
57
+ }
58
+ },
59
+ });
60
+ }
61
+ /**
62
+ * Stores assets, dependencies, bundle groups, bundles, and the relationships between them.
63
+ * The BundleGraph is passed to the bundler plugin wrapped in a MutableBundleGraph,
64
+ * and is passed to packagers and optimizers wrapped in the public BundleGraph object, both
65
+ * of which implement public api for this structure. This is the internal structure.
66
+ */
67
+ class BundleGraph {
68
+ constructor({ graph, publicIdByAssetId, assetPublicIds, bundleContentHashes, conditions, }) {
69
+ this._targetEntryRoots = new Map();
70
+ this._bundlePublicIds /*: Set<string> */ = new Set();
71
+ this._conditions /*: Map<string, Condition> */ = new Map();
72
+ this._graph = graph;
73
+ this._assetPublicIds = assetPublicIds;
74
+ this._publicIdByAssetId = publicIdByAssetId;
75
+ this._bundleContentHashes = bundleContentHashes;
76
+ this._conditions = conditions;
77
+ }
78
+ /**
79
+ * Produce a BundleGraph from an AssetGraph by removing asset groups and retargeting dependencies
80
+ * based on the symbol data (resolving side-effect free reexports).
81
+ */
82
+ static fromAssetGraph(assetGraph, isProduction, publicIdByAssetId = new Map(), assetPublicIds = new Set()) {
83
+ let graph = new graph_1.ContentGraph();
84
+ let assetGroupIds = new Map();
85
+ let dependencies = new Map();
86
+ let assetGraphNodeIdToBundleGraphNodeId = new Map();
87
+ let conditions = new Map();
88
+ let placeholderToDependency = new Map();
89
+ let assetGraphRootNode = assetGraph.rootNodeId != null
90
+ ? assetGraph.getNode(assetGraph.rootNodeId)
91
+ : null;
92
+ (0, assert_2.default)(assetGraphRootNode != null && assetGraphRootNode.type === 'root');
93
+ assetGraph.dfsFast((nodeId) => {
94
+ let node = assetGraph.getNode(nodeId);
95
+ if (node != null && node.type === 'asset') {
96
+ let { id: assetId } = node.value;
97
+ // Generate a new, short public id for this asset to use.
98
+ // If one already exists, use it.
99
+ let publicId = publicIdByAssetId.get(assetId);
100
+ if (publicId == null) {
101
+ publicId = (0, utils_2.getPublicId)(assetId, (existing) => assetPublicIds.has(existing));
102
+ publicIdByAssetId.set(assetId, publicId);
103
+ assetPublicIds.add(publicId);
104
+ }
105
+ }
106
+ else if (node != null && node.type === 'asset_group') {
107
+ assetGroupIds.set(nodeId, assetGraph.getNodeIdsConnectedFrom(nodeId));
108
+ }
109
+ else if ((0, feature_flags_1.getFeatureFlag)('conditionalBundlingApi') &&
110
+ node != null &&
111
+ node.type === 'dependency') {
112
+ // The dependency placeholders in the `importCond` calls that will be in the transformed
113
+ // code need to be mapped to the "real" dependencies, so we need access to a map of placeholders
114
+ // to dependencies
115
+ const dep = node.value;
116
+ // @ts-expect-error TS2322
117
+ const placeholder = dep.meta?.placeholder;
118
+ if (placeholder != null) {
119
+ placeholderToDependency.set(placeholder, dep);
120
+ }
121
+ }
122
+ });
123
+ let walkVisited = new Set();
124
+ function walk(nodeId) {
125
+ if (walkVisited.has(nodeId))
126
+ return;
127
+ walkVisited.add(nodeId);
128
+ let node = (0, nullthrows_1.default)(assetGraph.getNode(nodeId));
129
+ if ((0, feature_flags_1.getFeatureFlag)('conditionalBundlingApi') && node.type === 'asset') {
130
+ const asset = node.value;
131
+ if (Array.isArray(asset.meta.conditions)) {
132
+ for (const condition of asset.meta.conditions) {
133
+ // Resolve the placeholders that were attached to the asset in JSTransformer to dependencies,
134
+ // as well as create a public id for the condition.
135
+ const { key, ifTruePlaceholder, ifFalsePlaceholder, } = condition;
136
+ const condHash = (0, rust_1.hashString)(`${key}:${ifTruePlaceholder}:${ifFalsePlaceholder}`);
137
+ const condPublicId = (0, utils_2.getPublicId)(condHash, (v) => conditions.has(v));
138
+ if (conditions.has(condHash)) {
139
+ throw new Error('Unexpected duplicate asset');
140
+ }
141
+ else {
142
+ conditions.set(condHash, {
143
+ publicId: condPublicId,
144
+ assets: new Set([asset]),
145
+ key,
146
+ ifTrueDependency: (0, nullthrows_1.default)(placeholderToDependency.get(ifTruePlaceholder), 'ifTruePlaceholder was undefined'),
147
+ ifFalseDependency: (0, nullthrows_1.default)(placeholderToDependency.get(ifFalsePlaceholder), 'ifFalsePlaceholder was undefined'),
148
+ });
149
+ }
150
+ }
151
+ }
152
+ }
153
+ if (node.type === 'dependency' &&
154
+ node.value.symbols != null &&
155
+ (0, EnvironmentManager_1.fromEnvironmentId)(node.value.env).shouldScopeHoist &&
156
+ // Disable in dev mode because this feature is at odds with safeToIncrementallyBundle
157
+ isProduction) {
158
+ let nodeValueSymbols = node.value.symbols;
159
+ // asset -> symbols that should be imported directly from that asset
160
+ let targets = new utils_1.DefaultMap(() => new Map());
161
+ let externalSymbols = new Set();
162
+ let hasAmbiguousSymbols = false;
163
+ for (let [symbol, resolvedSymbol] of node.usedSymbolsUp) {
164
+ if (resolvedSymbol) {
165
+ targets
166
+ .get(resolvedSymbol.asset)
167
+ .set(symbol, resolvedSymbol.symbol ?? symbol);
168
+ }
169
+ else if (resolvedSymbol === null) {
170
+ externalSymbols.add(symbol);
171
+ }
172
+ else if (resolvedSymbol === undefined) {
173
+ hasAmbiguousSymbols = true;
174
+ break;
175
+ }
176
+ }
177
+ if (
178
+ // Only perform retargeting when there is an imported symbol
179
+ // - If the target is side-effect-free, the symbols point to the actual target and removing
180
+ // the original dependency resolution is fine
181
+ // - Otherwise, keep this dependency unchanged for its potential side effects
182
+ node.usedSymbolsUp.size > 0 &&
183
+ // Only perform retargeting if the dependency only points to a single asset (e.g. CSS modules)
184
+ !hasAmbiguousSymbols &&
185
+ // It doesn't make sense to retarget dependencies where `*` is used, because the
186
+ // retargeting won't enable any benefits in that case (apart from potentially even more
187
+ // code being generated).
188
+ !node.usedSymbolsUp.has('*') &&
189
+ // TODO We currently can't rename imports in async imports, e.g. from
190
+ // (parcelRequire("...")).then(({ a }) => a);
191
+ // to
192
+ // (parcelRequire("...")).then(({ a: b }) => a);
193
+ // or
194
+ // (parcelRequire("...")).then((a)=>a);
195
+ // if the reexporting asset did `export {a as b}` or `export * as a`
196
+ node.value.priority === types_1.Priority.sync &&
197
+ // For every asset, no symbol is imported multiple times (with a different local name).
198
+ // Don't retarget because this cannot be resolved without also changing the asset symbols
199
+ // (and the asset content itself).
200
+ [...targets].every(([, t]) => new Set([...t.values()]).size === t.size)) {
201
+ let isReexportAll = nodeValueSymbols.get('*')?.local === '*';
202
+ let reexportAllLoc = isReexportAll
203
+ ? (0, nullthrows_1.default)(nodeValueSymbols.get('*')).loc
204
+ : undefined;
205
+ // TODO adjust sourceAssetIdNode.value.dependencies ?
206
+ let deps = [
207
+ // Keep the original dependency
208
+ {
209
+ asset: null,
210
+ dep: graph.addNodeByContentKey(node.id, {
211
+ ...node,
212
+ value: {
213
+ ...node.value,
214
+ symbols: new Map(
215
+ // @ts-expect-error TS2769
216
+ [...nodeValueSymbols].filter(([k]) => externalSymbols.has(k))),
217
+ },
218
+ usedSymbolsUp: new Map(
219
+ // @ts-expect-error TS2769
220
+ [...node.usedSymbolsUp].filter(([k]) => externalSymbols.has(k))),
221
+ usedSymbolsDown: new Set(),
222
+ excluded: externalSymbols.size === 0,
223
+ }),
224
+ },
225
+ ...[...targets].map(([asset, target]) => {
226
+ let newNodeId = (0, rust_1.hashString)(node.id + [...target.keys()].join(','));
227
+ let symbols = new Map();
228
+ for (let [as, from] of target) {
229
+ let existing = nodeValueSymbols.get(as);
230
+ if (existing) {
231
+ symbols.set(from, existing);
232
+ }
233
+ else {
234
+ (0, assert_2.default)(isReexportAll);
235
+ if (as === from) {
236
+ // Keep the export-all for non-renamed reexports, this still correctly models
237
+ // ambiguous resolution with multiple export-alls.
238
+ symbols.set('*', {
239
+ isWeak: true,
240
+ local: '*',
241
+ loc: reexportAllLoc,
242
+ });
243
+ }
244
+ else {
245
+ let local = `${node.value.id}$rewrite$${asset}$${from}`;
246
+ symbols.set(from, {
247
+ isWeak: true,
248
+ local,
249
+ loc: reexportAllLoc,
250
+ });
251
+ if (node.value.sourceAssetId != null) {
252
+ let sourceAssetId = (0, nullthrows_1.default)(assetGraphNodeIdToBundleGraphNodeId.get(assetGraph.getNodeIdByContentKey(node.value.sourceAssetId)));
253
+ let sourceAsset = (0, nullthrows_1.default)(graph.getNode(sourceAssetId));
254
+ (0, assert_2.default)(sourceAsset.type === 'asset');
255
+ let sourceAssetSymbols = sourceAsset.value.symbols;
256
+ if (sourceAssetSymbols) {
257
+ // The `as == from` case above should handle multiple export-alls causing
258
+ // ambiguous resolution. So the current symbol is unambiguous and shouldn't
259
+ // already exist on the importer.
260
+ (0, assert_2.default)(!sourceAssetSymbols.has(as));
261
+ sourceAssetSymbols.set(as, {
262
+ loc: reexportAllLoc,
263
+ local: local,
264
+ });
265
+ }
266
+ }
267
+ }
268
+ }
269
+ }
270
+ let usedSymbolsUp = new Map([...node.usedSymbolsUp]
271
+ // @ts-expect-error TS2769
272
+ .filter(([k]) => target.has(k) || k === '*')
273
+ .map(([k, v]) => [target.get(k) ?? k, v]));
274
+ return {
275
+ asset,
276
+ dep: graph.addNodeByContentKey(newNodeId, {
277
+ ...node,
278
+ id: newNodeId,
279
+ value: {
280
+ ...node.value,
281
+ id: newNodeId,
282
+ symbols,
283
+ },
284
+ usedSymbolsUp,
285
+ // This is only a temporary helper needed during symbol propagation and is never
286
+ // read afterwards (and also not exposed through the public API).
287
+ usedSymbolsDown: new Set(),
288
+ }),
289
+ };
290
+ }),
291
+ ];
292
+ dependencies.set(nodeId, deps);
293
+ // Jump to the dependencies that are used in this dependency
294
+ for (let id of targets.keys()) {
295
+ walk(assetGraph.getNodeIdByContentKey(id));
296
+ }
297
+ return;
298
+ }
299
+ else {
300
+ // No special handling
301
+ let bundleGraphNodeId = graph.addNodeByContentKey(node.id, node);
302
+ assetGraphNodeIdToBundleGraphNodeId.set(nodeId, bundleGraphNodeId);
303
+ }
304
+ }
305
+ // Don't copy over asset groups into the bundle graph.
306
+ else if (node.type !== 'asset_group') {
307
+ let nodeToAdd = node.type === 'asset'
308
+ ? {
309
+ ...node,
310
+ value: { ...node.value, symbols: new Map(node.value.symbols) },
311
+ }
312
+ : node;
313
+ let bundleGraphNodeId = graph.addNodeByContentKey(node.id, nodeToAdd);
314
+ if (node.id === assetGraphRootNode?.id) {
315
+ graph.setRootNodeId(bundleGraphNodeId);
316
+ }
317
+ assetGraphNodeIdToBundleGraphNodeId.set(nodeId, bundleGraphNodeId);
318
+ }
319
+ for (let id of assetGraph.getNodeIdsConnectedFrom(nodeId)) {
320
+ walk(id);
321
+ }
322
+ }
323
+ walk((0, nullthrows_1.default)(assetGraph.rootNodeId));
324
+ // @ts-expect-error TS2488
325
+ for (let edge of assetGraph.getAllEdges()) {
326
+ if (assetGroupIds.has(edge.from)) {
327
+ continue;
328
+ }
329
+ if (dependencies.has(edge.from)) {
330
+ // Discard previous edge, insert outgoing edges for all split dependencies
331
+ for (let { asset, dep } of (0, nullthrows_1.default)(dependencies.get(edge.from))) {
332
+ if (asset != null) {
333
+ graph.addEdge(dep, (0, nullthrows_1.default)(assetGraphNodeIdToBundleGraphNodeId.get(assetGraph.getNodeIdByContentKey(asset))));
334
+ }
335
+ }
336
+ continue;
337
+ }
338
+ if (!assetGraphNodeIdToBundleGraphNodeId.has(edge.from)) {
339
+ continue;
340
+ }
341
+ let to = dependencies.get(edge.to)?.map((v) => v.dep) ??
342
+ assetGroupIds
343
+ .get(edge.to)
344
+ ?.map((id) => (0, nullthrows_1.default)(assetGraphNodeIdToBundleGraphNodeId.get(id))) ?? [(0, nullthrows_1.default)(assetGraphNodeIdToBundleGraphNodeId.get(edge.to))];
345
+ for (let t of to) {
346
+ graph.addEdge((0, nullthrows_1.default)(assetGraphNodeIdToBundleGraphNodeId.get(edge.from)), t);
347
+ }
348
+ }
349
+ return new BundleGraph({
350
+ graph,
351
+ assetPublicIds,
352
+ bundleContentHashes: new Map(),
353
+ publicIdByAssetId,
354
+ conditions,
355
+ });
356
+ }
357
+ serialize() {
358
+ return {
359
+ $$raw: true,
360
+ graph: this._graph.serialize(),
361
+ assetPublicIds: this._assetPublicIds,
362
+ bundleContentHashes: this._bundleContentHashes,
363
+ publicIdByAssetId: this._publicIdByAssetId,
364
+ conditions: this._conditions,
365
+ };
366
+ }
367
+ static deserialize(serialized) {
368
+ return new BundleGraph({
369
+ graph: graph_1.ContentGraph.deserialize(serialized.graph),
370
+ assetPublicIds: serialized.assetPublicIds,
371
+ bundleContentHashes: serialized.bundleContentHashes,
372
+ publicIdByAssetId: serialized.publicIdByAssetId,
373
+ conditions: serialized.conditions,
374
+ });
375
+ }
376
+ createBundle(opts) {
377
+ // @ts-expect-error TS2339
378
+ let { entryAsset, target } = opts;
379
+ let bundleId = (0, rust_1.hashString)('bundle:' +
380
+ // @ts-expect-error TS2339
381
+ (opts.entryAsset ? opts.entryAsset.id : opts.uniqueKey) +
382
+ (0, projectPath_1.fromProjectPathRelative)(target.distDir) +
383
+ (opts.bundleBehavior ?? ''));
384
+ let existing = this._graph.getNodeByContentKey(bundleId);
385
+ if (existing != null) {
386
+ (0, assert_2.default)(existing.type === 'bundle');
387
+ return existing.value;
388
+ }
389
+ let publicId = (0, utils_2.getPublicId)(bundleId, (existing) => this._bundlePublicIds.has(existing));
390
+ this._bundlePublicIds.add(publicId);
391
+ let isPlaceholder = false;
392
+ if (entryAsset) {
393
+ let entryAssetNode = this._graph.getNodeByContentKey(entryAsset.id);
394
+ (0, assert_2.default)(entryAssetNode?.type === 'asset', 'Entry asset does not exist');
395
+ isPlaceholder = entryAssetNode.requested === false;
396
+ }
397
+ let bundleNode = {
398
+ type: 'bundle',
399
+ id: bundleId,
400
+ value: {
401
+ id: bundleId,
402
+ hashReference: opts.shouldContentHash
403
+ ? constants_1.HASH_REF_PREFIX + bundleId
404
+ : bundleId.slice(-8),
405
+ // @ts-expect-error TS2339
406
+ type: opts.entryAsset ? opts.entryAsset.type : opts.type,
407
+ env: opts.env,
408
+ entryAssetIds: entryAsset ? [entryAsset.id] : [],
409
+ mainEntryId: entryAsset?.id,
410
+ // @ts-expect-error TS2339
411
+ pipeline: opts.entryAsset ? opts.entryAsset.pipeline : opts.pipeline,
412
+ needsStableName: opts.needsStableName,
413
+ bundleBehavior: opts.bundleBehavior != null
414
+ ? types_1.BundleBehavior[opts.bundleBehavior]
415
+ : null,
416
+ // @ts-expect-error TS2339
417
+ isSplittable: opts.entryAsset
418
+ ? // @ts-expect-error TS2339
419
+ opts.entryAsset.isBundleSplittable
420
+ : // @ts-expect-error TS2339
421
+ opts.isSplittable,
422
+ isPlaceholder,
423
+ target,
424
+ name: null,
425
+ displayName: null,
426
+ publicId,
427
+ },
428
+ };
429
+ let bundleNodeId = this._graph.addNodeByContentKey(bundleId, bundleNode);
430
+ // @ts-expect-error TS2339
431
+ if (opts.entryAsset) {
432
+ this._graph.addEdge(bundleNodeId,
433
+ // @ts-expect-error TS2339
434
+ this._graph.getNodeIdByContentKey(opts.entryAsset.id));
435
+ }
436
+ assert_2.default;
437
+ return bundleNode.value;
438
+ }
439
+ addAssetToBundle(asset, bundle) {
440
+ let bundleNodeId = this._graph.getNodeIdByContentKey(bundle.id);
441
+ this._graph.addEdge(bundleNodeId, this._graph.getNodeIdByContentKey(asset.id), exports.bundleGraphEdgeTypes.contains);
442
+ this._graph.addEdge(bundleNodeId, this._graph.getNodeIdByContentKey(asset.id));
443
+ let dependencies = this.getDependencies(asset);
444
+ for (let dependency of dependencies) {
445
+ let dependencyNodeId = this._graph.getNodeIdByContentKey(dependency.id);
446
+ this._graph.addEdge(bundleNodeId, dependencyNodeId, exports.bundleGraphEdgeTypes.contains);
447
+ for (let [bundleGroupNodeId, bundleGroupNode] of this._graph
448
+ .getNodeIdsConnectedFrom(dependencyNodeId)
449
+ .map((id) => [id, (0, nullthrows_1.default)(this._graph.getNode(id))])
450
+ // @ts-expect-error TS2769
451
+ .filter(([, node]) => node.type === 'bundle_group')) {
452
+ // @ts-expect-error TS2339
453
+ (0, assert_2.default)(bundleGroupNode.type === 'bundle_group');
454
+ this._graph.addEdge(bundleNodeId,
455
+ // @ts-expect-error TS2345
456
+ bundleGroupNodeId, exports.bundleGraphEdgeTypes.bundle);
457
+ }
458
+ // If the dependency references a target bundle, add a reference edge from
459
+ // the source bundle to the dependency for easy traversal.
460
+ // TODO: Consider bundle being created from dependency
461
+ if (this._graph
462
+ .getNodeIdsConnectedFrom(dependencyNodeId, exports.bundleGraphEdgeTypes.references)
463
+ .map((id) => (0, nullthrows_1.default)(this._graph.getNode(id)))
464
+ .some((node) => node.type === 'bundle')) {
465
+ this._graph.addEdge(bundleNodeId, dependencyNodeId, exports.bundleGraphEdgeTypes.references);
466
+ }
467
+ }
468
+ }
469
+ addAssetGraphToBundle(asset, bundle, shouldSkipDependency = (d) => this.isDependencySkipped(d)) {
470
+ let assetNodeId = this._graph.getNodeIdByContentKey(asset.id);
471
+ let bundleNodeId = this._graph.getNodeIdByContentKey(bundle.id);
472
+ // The root asset should be reached directly from the bundle in traversal.
473
+ // Its children will be traversed from there.
474
+ this._graph.addEdge(bundleNodeId, assetNodeId);
475
+ this._graph.traverse((nodeId, _, actions) => {
476
+ let node = (0, nullthrows_1.default)(this._graph.getNode(nodeId));
477
+ if (node.type === 'bundle_group') {
478
+ actions.skipChildren();
479
+ return;
480
+ }
481
+ if (node.type === 'dependency' && shouldSkipDependency(node.value)) {
482
+ actions.skipChildren();
483
+ return;
484
+ }
485
+ if (node.type === 'asset' || node.type === 'dependency') {
486
+ this._graph.addEdge(bundleNodeId, nodeId, exports.bundleGraphEdgeTypes.contains);
487
+ }
488
+ if (node.type === 'dependency') {
489
+ for (let [bundleGroupNodeId, bundleGroupNode] of this._graph
490
+ .getNodeIdsConnectedFrom(nodeId)
491
+ .map((id) => [id, (0, nullthrows_1.default)(this._graph.getNode(id))])
492
+ // @ts-expect-error TS2769
493
+ .filter(([, node]) => node.type === 'bundle_group')) {
494
+ // @ts-expect-error TS2339
495
+ (0, assert_2.default)(bundleGroupNode.type === 'bundle_group');
496
+ this._graph.addEdge(bundleNodeId,
497
+ // @ts-expect-error TS2345
498
+ bundleGroupNodeId, exports.bundleGraphEdgeTypes.bundle);
499
+ }
500
+ // If the dependency references a target bundle, add a reference edge from
501
+ // the source bundle to the dependency for easy traversal.
502
+ if (this._graph
503
+ .getNodeIdsConnectedFrom(nodeId, exports.bundleGraphEdgeTypes.references)
504
+ .map((id) => (0, nullthrows_1.default)(this._graph.getNode(id)))
505
+ .some((node) => node.type === 'bundle')) {
506
+ this._graph.addEdge(bundleNodeId, nodeId, exports.bundleGraphEdgeTypes.references);
507
+ this.markDependencyReferenceable(node.value);
508
+ //all bundles that have this dependency need to have an edge from bundle to that dependency
509
+ }
510
+ }
511
+ }, assetNodeId);
512
+ this._bundleContentHashes.delete(bundle.id);
513
+ }
514
+ markDependencyReferenceable(dependency) {
515
+ for (let bundle of this.getBundlesWithDependency(dependency)) {
516
+ this._graph.addEdge(this._graph.getNodeIdByContentKey(bundle.id), this._graph.getNodeIdByContentKey(dependency.id), exports.bundleGraphEdgeTypes.references);
517
+ }
518
+ }
519
+ addEntryToBundle(asset, bundle, shouldSkipDependency) {
520
+ this.addAssetGraphToBundle(asset, bundle, shouldSkipDependency);
521
+ if (!bundle.entryAssetIds.includes(asset.id)) {
522
+ bundle.entryAssetIds.push(asset.id);
523
+ }
524
+ }
525
+ internalizeAsyncDependency(bundle, dependency) {
526
+ if (dependency.priority === types_1.Priority.sync) {
527
+ throw new Error('Expected an async dependency');
528
+ }
529
+ // It's possible for internalized async dependencies to not have
530
+ // reference edges and still have untyped edges.
531
+ // TODO: Maybe don't use internalized async edges at all?
532
+ let dependencyNodeId = this._graph.getNodeIdByContentKey(dependency.id);
533
+ let resolved = this.getResolvedAsset(dependency);
534
+ if (resolved) {
535
+ let resolvedNodeId = this._graph.getNodeIdByContentKey(resolved.id);
536
+ if (!this._graph.hasEdge(dependencyNodeId, resolvedNodeId, exports.bundleGraphEdgeTypes.references)) {
537
+ this._graph.addEdge(dependencyNodeId, resolvedNodeId, exports.bundleGraphEdgeTypes.references);
538
+ this._graph.removeEdge(dependencyNodeId, resolvedNodeId);
539
+ }
540
+ }
541
+ this._graph.addEdge(this._graph.getNodeIdByContentKey(bundle.id), this._graph.getNodeIdByContentKey(dependency.id), exports.bundleGraphEdgeTypes.internal_async);
542
+ this._removeExternalDependency(bundle, dependency);
543
+ }
544
+ isDependencySkipped(dependency) {
545
+ let node = this._graph.getNodeByContentKey(dependency.id);
546
+ (0, assert_2.default)(node && node.type === 'dependency');
547
+ return !!node.hasDeferred || node.excluded;
548
+ }
549
+ getParentBundlesOfBundleGroup(bundleGroup) {
550
+ return this._graph
551
+ .getNodeIdsConnectedTo(this._graph.getNodeIdByContentKey((0, utils_2.getBundleGroupId)(bundleGroup)), exports.bundleGraphEdgeTypes.bundle)
552
+ .map((id) => (0, nullthrows_1.default)(this._graph.getNode(id)))
553
+ .filter((node) => node.type === 'bundle')
554
+ .map((node) => {
555
+ (0, assert_2.default)(node.type === 'bundle');
556
+ return node.value;
557
+ });
558
+ }
559
+ resolveAsyncDependency(dependency, bundle) {
560
+ let depNodeId = this._graph.getNodeIdByContentKey(dependency.id);
561
+ let bundleNodeId = bundle != null ? this._graph.getNodeIdByContentKey(bundle.id) : null;
562
+ if (bundleNodeId != null &&
563
+ this._graph.hasEdge(bundleNodeId, depNodeId, exports.bundleGraphEdgeTypes.internal_async)) {
564
+ let referencedAssetNodeIds = this._graph.getNodeIdsConnectedFrom(depNodeId, exports.bundleGraphEdgeTypes.references);
565
+ let resolved;
566
+ if (referencedAssetNodeIds.length === 0) {
567
+ resolved = this.getResolvedAsset(dependency, bundle);
568
+ }
569
+ else if (referencedAssetNodeIds.length === 1) {
570
+ let referencedAssetNode = this._graph.getNode(referencedAssetNodeIds[0]);
571
+ // If a referenced asset already exists, resolve this dependency to it.
572
+ (0, assert_2.default)(referencedAssetNode?.type === 'asset');
573
+ resolved = referencedAssetNode.value;
574
+ }
575
+ else {
576
+ throw new Error('Dependencies can only reference one asset');
577
+ }
578
+ if (resolved == null) {
579
+ return;
580
+ }
581
+ else {
582
+ return {
583
+ type: 'asset',
584
+ value: resolved,
585
+ };
586
+ }
587
+ }
588
+ let node = this._graph
589
+ .getNodeIdsConnectedFrom(this._graph.getNodeIdByContentKey(dependency.id))
590
+ .map((id) => (0, nullthrows_1.default)(this._graph.getNode(id)))
591
+ .find((node) => node.type === 'bundle_group');
592
+ if (node == null) {
593
+ return;
594
+ }
595
+ (0, assert_2.default)(node.type === 'bundle_group');
596
+ return {
597
+ type: 'bundle_group',
598
+ value: node.value,
599
+ };
600
+ }
601
+ // eslint-disable-next-line no-unused-vars
602
+ getReferencedBundle(dependency, fromBundle) {
603
+ let dependencyNodeId = this._graph.getNodeIdByContentKey(dependency.id);
604
+ // Find an attached bundle via a reference edge (e.g. from createAssetReference).
605
+ let bundleNodes = this._graph
606
+ .getNodeIdsConnectedFrom(dependencyNodeId, exports.bundleGraphEdgeTypes.references)
607
+ .map((id) => (0, nullthrows_1.default)(this._graph.getNode(id)))
608
+ .filter((node) => node.type === 'bundle');
609
+ if (bundleNodes.length) {
610
+ let bundleNode = bundleNodes.find((b) => b.type === 'bundle' && b.value.type === fromBundle.type) || bundleNodes[0];
611
+ (0, assert_2.default)(bundleNode.type === 'bundle');
612
+ return bundleNode.value;
613
+ }
614
+ // If this dependency is async, there will be a bundle group attached to it.
615
+ let node = this._graph
616
+ .getNodeIdsConnectedFrom(dependencyNodeId)
617
+ .map((id) => (0, nullthrows_1.default)(this._graph.getNode(id)))
618
+ .find((node) => node.type === 'bundle_group');
619
+ if (node != null) {
620
+ (0, assert_2.default)(node.type === 'bundle_group');
621
+ return this.getBundlesInBundleGroup(node.value, {
622
+ includeInline: true,
623
+ }).find((b) => {
624
+ if ((0, feature_flags_1.getFeatureFlag)('supportWebpackChunkName')) {
625
+ return b.entryAssetIds.some((id) => id === node.value.entryAssetId);
626
+ }
627
+ else {
628
+ let mainEntryId = b.entryAssetIds[b.entryAssetIds.length - 1];
629
+ return mainEntryId != null && node.value.entryAssetId === mainEntryId;
630
+ }
631
+ });
632
+ }
633
+ }
634
+ removeAssetGraphFromBundle(asset, bundle) {
635
+ let bundleNodeId = this._graph.getNodeIdByContentKey(bundle.id);
636
+ let assetNodeId = this._graph.getNodeIdByContentKey(asset.id);
637
+ // Remove all contains edges from the bundle to the nodes in the asset's
638
+ // subgraph.
639
+ this._graph.traverse((nodeId, context, actions) => {
640
+ let node = (0, nullthrows_1.default)(this._graph.getNode(nodeId));
641
+ if (node.type === 'bundle_group') {
642
+ actions.skipChildren();
643
+ return;
644
+ }
645
+ if (node.type !== 'dependency' && node.type !== 'asset') {
646
+ return;
647
+ }
648
+ if (this._graph.hasEdge(bundleNodeId, nodeId, exports.bundleGraphEdgeTypes.contains)) {
649
+ this._graph.removeEdge(bundleNodeId, nodeId, exports.bundleGraphEdgeTypes.contains,
650
+ // Removing this contains edge should not orphan the connected node. This
651
+ // is disabled for performance reasons as these edges are removed as part
652
+ // of a traversal, and checking for orphans becomes quite expensive in
653
+ // aggregate.
654
+ false /* removeOrphans */);
655
+ }
656
+ else {
657
+ actions.skipChildren();
658
+ }
659
+ if (node.type === 'asset' && this._graph.hasEdge(bundleNodeId, nodeId)) {
660
+ // Remove the untyped edge from the bundle to the node (it's an entry)
661
+ this._graph.removeEdge(bundleNodeId, nodeId);
662
+ let entryIndex = bundle.entryAssetIds.indexOf(node.value.id);
663
+ if (entryIndex >= 0) {
664
+ // Shared bundles have untyped edges to their asset graphs but don't
665
+ // have entry assets. For those that have entry asset ids, remove them.
666
+ bundle.entryAssetIds.splice(entryIndex, 1);
667
+ }
668
+ }
669
+ if (node.type === 'dependency') {
670
+ this._removeExternalDependency(bundle, node.value);
671
+ if (this._graph.hasEdge(bundleNodeId, nodeId, exports.bundleGraphEdgeTypes.references)) {
672
+ this._graph.addEdge(bundleNodeId, nodeId, exports.bundleGraphEdgeTypes.references);
673
+ this.markDependencyReferenceable(node.value);
674
+ }
675
+ if (this._graph.hasEdge(bundleNodeId, nodeId, exports.bundleGraphEdgeTypes.internal_async)) {
676
+ this._graph.removeEdge(bundleNodeId, nodeId, exports.bundleGraphEdgeTypes.internal_async);
677
+ }
678
+ }
679
+ }, assetNodeId);
680
+ // Remove bundle node if it no longer has any entry assets
681
+ if (this._graph.getNodeIdsConnectedFrom(bundleNodeId).length === 0) {
682
+ this.removeBundle(bundle);
683
+ }
684
+ this._bundleContentHashes.delete(bundle.id);
685
+ }
686
+ /**
687
+ * Remove a bundle from the bundle graph. Remove its bundle group if it is
688
+ * the only bundle in the group.
689
+ */
690
+ removeBundle(bundle) {
691
+ // Remove bundle node if it no longer has any entry assets
692
+ let bundleNodeId = this._graph.getNodeIdByContentKey(bundle.id);
693
+ let bundleGroupNodeIds = this._graph.getNodeIdsConnectedTo(bundleNodeId, exports.bundleGraphEdgeTypes.bundle);
694
+ this._graph.removeNode(bundleNodeId);
695
+ let removedBundleGroups = new Set();
696
+ // Remove bundle group node if it no longer has any bundles
697
+ for (let bundleGroupNodeId of bundleGroupNodeIds) {
698
+ let bundleGroupNode = (0, nullthrows_1.default)(this._graph.getNode(bundleGroupNodeId));
699
+ (0, assert_2.default)(bundleGroupNode.type === 'bundle_group');
700
+ let bundleGroup = bundleGroupNode.value;
701
+ if (
702
+ // If the bundle group's entry asset belongs to this bundle, the group
703
+ // was created because of this bundle. Remove the group.
704
+ bundle.entryAssetIds.includes(bundleGroup.entryAssetId) ||
705
+ // If the bundle group is now empty, remove it.
706
+ this.getBundlesInBundleGroup(bundleGroup, { includeInline: true })
707
+ .length === 0) {
708
+ removedBundleGroups.add(bundleGroup);
709
+ this.removeBundleGroup(bundleGroup);
710
+ }
711
+ }
712
+ this._bundleContentHashes.delete(bundle.id);
713
+ return removedBundleGroups;
714
+ }
715
+ removeBundleGroup(bundleGroup) {
716
+ let bundleGroupNode = (0, nullthrows_1.default)(this._graph.getNodeByContentKey((0, utils_2.getBundleGroupId)(bundleGroup)));
717
+ (0, assert_2.default)(bundleGroupNode.type === 'bundle_group');
718
+ let bundlesInGroup = this.getBundlesInBundleGroup(bundleGroupNode.value, {
719
+ includeInline: true,
720
+ });
721
+ for (let bundle of bundlesInGroup) {
722
+ if (this.getBundleGroupsContainingBundle(bundle).length === 1) {
723
+ let removedBundleGroups = this.removeBundle(bundle);
724
+ if (removedBundleGroups.has(bundleGroup)) {
725
+ // This function can be reentered through removeBundle above. In the case this
726
+ // bundle group has already been removed, stop.
727
+ return;
728
+ }
729
+ }
730
+ }
731
+ // This function can be reentered through removeBundle above. In this case,
732
+ // the node may already been removed.
733
+ if (this._graph.hasContentKey(bundleGroupNode.id)) {
734
+ this._graph.removeNode(this._graph.getNodeIdByContentKey(bundleGroupNode.id));
735
+ }
736
+ (0, assert_1.default)(bundlesInGroup.every((bundle) => this.getBundleGroupsContainingBundle(bundle).length > 0));
737
+ }
738
+ _removeExternalDependency(bundle, dependency) {
739
+ let bundleNodeId = this._graph.getNodeIdByContentKey(bundle.id);
740
+ for (let bundleGroupNode of this._graph
741
+ .getNodeIdsConnectedFrom(this._graph.getNodeIdByContentKey(dependency.id))
742
+ .map((id) => (0, nullthrows_1.default)(this._graph.getNode(id)))
743
+ .filter((node) => node.type === 'bundle_group')) {
744
+ let bundleGroupNodeId = this._graph.getNodeIdByContentKey(bundleGroupNode.id);
745
+ if (!this._graph.hasEdge(bundleNodeId, bundleGroupNodeId, exports.bundleGraphEdgeTypes.bundle)) {
746
+ continue;
747
+ }
748
+ let inboundDependencies = this._graph
749
+ .getNodeIdsConnectedTo(bundleGroupNodeId)
750
+ .map((id) => (0, nullthrows_1.default)(this._graph.getNode(id)))
751
+ .filter((node) => node.type === 'dependency')
752
+ .map((node) => {
753
+ (0, assert_2.default)(node.type === 'dependency');
754
+ return node.value;
755
+ });
756
+ // If every inbound dependency to this bundle group does not belong to this bundle,
757
+ // or the dependency is internal to the bundle, then the connection between
758
+ // this bundle and the group is safe to remove.
759
+ if (inboundDependencies.every((dependency) => dependency.specifierType !== types_1.SpecifierType.url &&
760
+ (!this.bundleHasDependency(bundle, dependency) ||
761
+ this._graph.hasEdge(bundleNodeId, this._graph.getNodeIdByContentKey(dependency.id), exports.bundleGraphEdgeTypes.internal_async)))) {
762
+ this._graph.removeEdge(bundleNodeId, bundleGroupNodeId, exports.bundleGraphEdgeTypes.bundle);
763
+ }
764
+ }
765
+ }
766
+ createAssetReference(dependency, asset, bundle) {
767
+ let dependencyId = this._graph.getNodeIdByContentKey(dependency.id);
768
+ let assetId = this._graph.getNodeIdByContentKey(asset.id);
769
+ let bundleId = this._graph.getNodeIdByContentKey(bundle.id);
770
+ this._graph.addEdge(dependencyId, assetId, exports.bundleGraphEdgeTypes.references);
771
+ this._graph.addEdge(dependencyId, bundleId, exports.bundleGraphEdgeTypes.references);
772
+ this.markDependencyReferenceable(dependency);
773
+ if (this._graph.hasEdge(dependencyId, assetId)) {
774
+ this._graph.removeEdge(dependencyId, assetId);
775
+ }
776
+ }
777
+ createBundleReference(from, to) {
778
+ this._graph.addEdge(this._graph.getNodeIdByContentKey(from.id), this._graph.getNodeIdByContentKey(to.id), exports.bundleGraphEdgeTypes.references);
779
+ }
780
+ createBundleConditionalReference(from, to) {
781
+ this._graph.addEdge(this._graph.getNodeIdByContentKey(from.id), this._graph.getNodeIdByContentKey(to.id), exports.bundleGraphEdgeTypes.conditional);
782
+ }
783
+ getBundlesWithAsset(asset) {
784
+ return this._graph
785
+ .getNodeIdsConnectedTo(this._graph.getNodeIdByContentKey(asset.id), exports.bundleGraphEdgeTypes.contains)
786
+ .map((id) => (0, nullthrows_1.default)(this._graph.getNode(id)))
787
+ .filter((node) => node.type === 'bundle')
788
+ .map((node) => {
789
+ (0, assert_2.default)(node.type === 'bundle');
790
+ return node.value;
791
+ });
792
+ }
793
+ getBundlesWithDependency(dependency) {
794
+ return this._graph
795
+ .getNodeIdsConnectedTo((0, nullthrows_1.default)(this._graph.getNodeIdByContentKey(dependency.id)), exports.bundleGraphEdgeTypes.contains)
796
+ .map((id) => (0, nullthrows_1.default)(this._graph.getNode(id)))
797
+ .filter((node) => node.type === 'bundle')
798
+ .map((node) => {
799
+ (0, assert_2.default)(node.type === 'bundle');
800
+ return node.value;
801
+ });
802
+ }
803
+ getDependencyAssets(dependency) {
804
+ return this._graph
805
+ .getNodeIdsConnectedFrom(this._graph.getNodeIdByContentKey(dependency.id))
806
+ .map((id) => (0, nullthrows_1.default)(this._graph.getNode(id)))
807
+ .filter((node) => node.type === 'asset')
808
+ .map((node) => {
809
+ (0, assert_2.default)(node.type === 'asset');
810
+ return node.value;
811
+ });
812
+ }
813
+ getResolvedAsset(dep, bundle) {
814
+ let assets = this.getDependencyAssets(dep);
815
+ let firstAsset = assets[0];
816
+ let resolved =
817
+ // If no bundle is specified, use the first concrete asset.
818
+ bundle == null
819
+ ? firstAsset
820
+ : // Otherwise, find the first asset that belongs to this bundle.
821
+ assets.find((asset) => this.bundleHasAsset(bundle, asset)) ||
822
+ assets.find((a) => a.type === bundle.type) ||
823
+ firstAsset;
824
+ // If a resolution still hasn't been found, return the first referenced asset.
825
+ if (resolved == null) {
826
+ let potential = [];
827
+ this._graph.traverse((nodeId, _, traversal) => {
828
+ let node = (0, nullthrows_1.default)(this._graph.getNode(nodeId));
829
+ if (node.type === 'asset') {
830
+ potential.push(node.value);
831
+ }
832
+ else if (node.id !== dep.id) {
833
+ traversal.skipChildren();
834
+ }
835
+ }, this._graph.getNodeIdByContentKey(dep.id), exports.bundleGraphEdgeTypes.references);
836
+ if (bundle) {
837
+ // @ts-expect-error TS2322
838
+ resolved = potential.find((a) => a.type === bundle.type);
839
+ }
840
+ resolved || (resolved = potential[0]);
841
+ }
842
+ return resolved;
843
+ }
844
+ getDependencies(asset) {
845
+ let nodeId = this._graph.getNodeIdByContentKey(asset.id);
846
+ return this._graph.getNodeIdsConnectedFrom(nodeId).map((id) => {
847
+ let node = (0, nullthrows_1.default)(this._graph.getNode(id));
848
+ (0, assert_2.default)(node.type === 'dependency');
849
+ return node.value;
850
+ });
851
+ }
852
+ traverseAssets(bundle, visit, startAsset) {
853
+ return this.traverseBundle(bundle, (0, graph_1.mapVisitor)((node) => (node.type === 'asset' ? node.value : null), visit), startAsset);
854
+ }
855
+ isAssetReferenced(bundle, asset) {
856
+ // If the asset is available in multiple bundles in the same target, it's referenced.
857
+ if (this.getBundlesWithAsset(asset).filter((b) => b.target.name === bundle.target.name &&
858
+ b.target.distDir === bundle.target.distDir).length > 1) {
859
+ return true;
860
+ }
861
+ let assetNodeId = (0, nullthrows_1.default)(this._graph.getNodeIdByContentKey(asset.id));
862
+ if (this._graph
863
+ .getNodeIdsConnectedTo(assetNodeId, exports.bundleGraphEdgeTypes.references)
864
+ .map((id) => this._graph.getNode(id))
865
+ .some((node) => node?.type === 'dependency' &&
866
+ (node.value.priority === types_1.Priority.lazy ||
867
+ node.value.priority === types_1.Priority.conditional) &&
868
+ node.value.specifierType !== types_1.SpecifierType.url)) {
869
+ // If this asset is referenced by any async dependency, it's referenced.
870
+ return true;
871
+ }
872
+ let dependencies = this._graph
873
+ .getNodeIdsConnectedTo(assetNodeId)
874
+ .map((id) => (0, nullthrows_1.default)(this._graph.getNode(id)))
875
+ .filter((node) => node.type === 'dependency')
876
+ .map((node) => {
877
+ (0, assert_2.default)(node.type === 'dependency');
878
+ return node.value;
879
+ });
880
+ const bundleHasReference = (bundle) => {
881
+ return (!this.bundleHasAsset(bundle, asset) &&
882
+ dependencies.some((dependency) => this.bundleHasDependency(bundle, dependency)));
883
+ };
884
+ let visitedBundles = new Set();
885
+ let siblingBundles = new Set(this.getBundleGroupsContainingBundle(bundle).flatMap((bundleGroup) => this.getBundlesInBundleGroup(bundleGroup, { includeInline: true })));
886
+ // Check if any of this bundle's descendants, referencers, bundles referenced
887
+ // by referencers, or descendants of its referencers use the asset without
888
+ // an explicit reference edge. This can happen if e.g. the asset has been
889
+ // deduplicated.
890
+ return [...siblingBundles].some((referencer) => {
891
+ let isReferenced = false;
892
+ this.traverseBundles((descendant, _, actions) => {
893
+ if (descendant.id === bundle.id) {
894
+ return;
895
+ }
896
+ if (visitedBundles.has(descendant)) {
897
+ actions.skipChildren();
898
+ return;
899
+ }
900
+ visitedBundles.add(descendant);
901
+ if (descendant.type !== bundle.type ||
902
+ (0, EnvironmentManager_1.fromEnvironmentId)(descendant.env).context !==
903
+ (0, EnvironmentManager_1.fromEnvironmentId)(bundle.env).context) {
904
+ actions.skipChildren();
905
+ return;
906
+ }
907
+ if (bundleHasReference(descendant)) {
908
+ isReferenced = true;
909
+ actions.stop();
910
+ return;
911
+ }
912
+ }, referencer);
913
+ return isReferenced;
914
+ });
915
+ }
916
+ hasParentBundleOfType(bundle, type) {
917
+ let parents = this.getParentBundles(bundle);
918
+ return (parents.length > 0 && parents.every((parent) => parent.type === type));
919
+ }
920
+ getParentBundles(bundle) {
921
+ let parentBundles = new Set();
922
+ for (let bundleGroup of this.getBundleGroupsContainingBundle(bundle)) {
923
+ for (let parentBundle of this.getParentBundlesOfBundleGroup(bundleGroup)) {
924
+ parentBundles.add(parentBundle);
925
+ }
926
+ }
927
+ return [...parentBundles];
928
+ }
929
+ isAssetReachableFromBundle(asset, bundle) {
930
+ // If a bundle's environment is isolated, it can't access assets present
931
+ // in any ancestor bundles. Don't consider any assets reachable.
932
+ if (Environment_1.ISOLATED_ENVS.has((0, EnvironmentManager_1.fromEnvironmentId)(bundle.env).context) ||
933
+ !bundle.isSplittable ||
934
+ bundle.bundleBehavior === types_1.BundleBehavior.isolated ||
935
+ bundle.bundleBehavior === types_1.BundleBehavior.inline ||
936
+ bundle.bundleBehavior === types_1.BundleBehavior.inlineIsolated) {
937
+ return false;
938
+ }
939
+ // For an asset to be reachable from a bundle, it must either exist in a sibling bundle,
940
+ // or in an ancestor bundle group reachable from all parent bundles.
941
+ let bundleGroups = this.getBundleGroupsContainingBundle(bundle);
942
+ return bundleGroups.every((bundleGroup) => {
943
+ // If the asset is in any sibling bundles of the original bundle, it is reachable.
944
+ let bundles = this.getBundlesInBundleGroup(bundleGroup);
945
+ if (bundles.some((b) => b.id !== bundle.id &&
946
+ b.bundleBehavior !== types_1.BundleBehavior.isolated &&
947
+ b.bundleBehavior !== types_1.BundleBehavior.inline &&
948
+ b.bundleBehavior !== types_1.BundleBehavior.inlineIsolated &&
949
+ this.bundleHasAsset(b, asset))) {
950
+ return true;
951
+ }
952
+ // Get a list of parent bundle nodes pointing to the bundle group
953
+ let parentBundleNodes = this._graph.getNodeIdsConnectedTo(this._graph.getNodeIdByContentKey((0, utils_2.getBundleGroupId)(bundleGroup)), exports.bundleGraphEdgeTypes.bundle);
954
+ // Check that every parent bundle has a bundle group in its ancestry that contains the asset.
955
+ return parentBundleNodes.every((bundleNodeId) => {
956
+ let bundleNode = (0, nullthrows_1.default)(this._graph.getNode(bundleNodeId));
957
+ if (bundleNode.type !== 'bundle' ||
958
+ bundleNode.value.bundleBehavior === types_1.BundleBehavior.isolated ||
959
+ bundleNode.value.bundleBehavior === types_1.BundleBehavior.inline ||
960
+ bundleNode.value.bundleBehavior === types_1.BundleBehavior.inlineIsolated) {
961
+ return false;
962
+ }
963
+ let isReachable = true;
964
+ this._graph.traverseAncestors(bundleNodeId, (nodeId, ctx, actions) => {
965
+ let node = (0, nullthrows_1.default)(this._graph.getNode(nodeId));
966
+ // If we've reached the root or a context change without
967
+ // finding this asset in the ancestry, it is not reachable.
968
+ if (node.type === 'root' ||
969
+ (node.type === 'bundle' &&
970
+ (node.value.id === bundle.id ||
971
+ (0, EnvironmentManager_1.fromEnvironmentId)(node.value.env).context !==
972
+ (0, EnvironmentManager_1.fromEnvironmentId)(bundle.env).context))) {
973
+ isReachable = false;
974
+ actions.stop();
975
+ return;
976
+ }
977
+ if (node.type === 'bundle_group') {
978
+ let childBundles = this.getBundlesInBundleGroup(node.value);
979
+ if (childBundles.some((b) => b.id !== bundle.id &&
980
+ b.bundleBehavior !== types_1.BundleBehavior.isolated &&
981
+ b.bundleBehavior !== types_1.BundleBehavior.inline &&
982
+ b.bundleBehavior !== types_1.BundleBehavior.inlineIsolated &&
983
+ this.bundleHasAsset(b, asset))) {
984
+ actions.skipChildren();
985
+ return;
986
+ }
987
+ }
988
+ }, [exports.bundleGraphEdgeTypes.references, exports.bundleGraphEdgeTypes.bundle]);
989
+ return isReachable;
990
+ });
991
+ });
992
+ }
993
+ /**
994
+ * TODO: Document why this works like this & why visitor order matters
995
+ * on these use-cases.
996
+ */
997
+ traverseBundle(bundle, visit, startAsset) {
998
+ let entries = !startAsset;
999
+ let bundleNodeId = this._graph.getNodeIdByContentKey(bundle.id);
1000
+ // A modified DFS traversal which traverses entry assets in the same order
1001
+ // as their ids appear in `bundle.entryAssetIds`.
1002
+ return this._graph.dfs({
1003
+ visit: (0, graph_1.mapVisitor)((nodeId, actions) => {
1004
+ let node = (0, nullthrows_1.default)(this._graph.getNode(nodeId));
1005
+ if (nodeId === bundleNodeId) {
1006
+ return;
1007
+ }
1008
+ if (node.type === 'dependency' || node.type === 'asset') {
1009
+ if (this._graph.hasEdge(bundleNodeId, nodeId, exports.bundleGraphEdgeTypes.contains)) {
1010
+ return node;
1011
+ }
1012
+ }
1013
+ actions.skipChildren();
1014
+ }, visit),
1015
+ startNodeId: startAsset
1016
+ ? this._graph.getNodeIdByContentKey(startAsset.id)
1017
+ : bundleNodeId,
1018
+ getChildren: (nodeId) => {
1019
+ let children = this._graph
1020
+ .getNodeIdsConnectedFrom(nodeId)
1021
+ .map((id) => [id, (0, nullthrows_1.default)(this._graph.getNode(id))]);
1022
+ let sorted = entries && bundle.entryAssetIds.length > 0
1023
+ ? // @ts-expect-error TS2345
1024
+ children.sort(([, a], [, b]) => {
1025
+ let aIndex = bundle.entryAssetIds.indexOf(a.id);
1026
+ let bIndex = bundle.entryAssetIds.indexOf(b.id);
1027
+ if (aIndex === bIndex) {
1028
+ // If both don't exist in the entry asset list, or
1029
+ // otherwise have the same index.
1030
+ return 0;
1031
+ }
1032
+ else if (aIndex === -1) {
1033
+ return 1;
1034
+ }
1035
+ else if (bIndex === -1) {
1036
+ return -1;
1037
+ }
1038
+ return aIndex - bIndex;
1039
+ })
1040
+ : children;
1041
+ entries = false;
1042
+ // @ts-expect-error TS2345
1043
+ return sorted.map(([id]) => id);
1044
+ },
1045
+ });
1046
+ }
1047
+ traverse(visit, start) {
1048
+ return this._graph.filteredTraverse((nodeId) => {
1049
+ let node = (0, nullthrows_1.default)(this._graph.getNode(nodeId));
1050
+ if (node.type === 'asset' || node.type === 'dependency') {
1051
+ return node;
1052
+ }
1053
+ }, visit, start ? this._graph.getNodeIdByContentKey(start.id) : undefined, // start with root
1054
+ graph_1.ALL_EDGE_TYPES);
1055
+ }
1056
+ getChildBundles(bundle) {
1057
+ let siblings = new Set(this.getReferencedBundles(bundle));
1058
+ let bundles = [];
1059
+ this.traverseBundles((b, _, actions) => {
1060
+ if (bundle.id === b.id) {
1061
+ return;
1062
+ }
1063
+ if (!siblings.has(b)) {
1064
+ bundles.push(b);
1065
+ }
1066
+ actions.skipChildren();
1067
+ }, bundle);
1068
+ return bundles;
1069
+ }
1070
+ traverseBundles(visit, startBundle) {
1071
+ return this._graph.filteredTraverse((nodeId) => {
1072
+ let node = (0, nullthrows_1.default)(this._graph.getNode(nodeId));
1073
+ return node.type === 'bundle' ? node.value : null;
1074
+ }, visit, startBundle ? this._graph.getNodeIdByContentKey(startBundle.id) : null, [exports.bundleGraphEdgeTypes.bundle, exports.bundleGraphEdgeTypes.references]);
1075
+ }
1076
+ getBundles(opts) {
1077
+ let bundles = [];
1078
+ this.traverseBundles((bundle) => {
1079
+ if (opts?.includeInline ||
1080
+ (bundle.bundleBehavior !== types_1.BundleBehavior.inline &&
1081
+ bundle.bundleBehavior !== types_1.BundleBehavior.inlineIsolated)) {
1082
+ bundles.push(bundle);
1083
+ }
1084
+ });
1085
+ return bundles;
1086
+ }
1087
+ getTotalSize(asset) {
1088
+ let size = 0;
1089
+ this._graph.traverse((nodeId, _, actions) => {
1090
+ let node = (0, nullthrows_1.default)(this._graph.getNode(nodeId));
1091
+ if (node.type === 'bundle_group') {
1092
+ actions.skipChildren();
1093
+ return;
1094
+ }
1095
+ if (node.type === 'asset') {
1096
+ size += node.value.stats.size;
1097
+ }
1098
+ }, this._graph.getNodeIdByContentKey(asset.id));
1099
+ return size;
1100
+ }
1101
+ getReferencingBundles(bundle) {
1102
+ let referencingBundles = new Set();
1103
+ this._graph.traverseAncestors(this._graph.getNodeIdByContentKey(bundle.id), (nodeId) => {
1104
+ let node = (0, nullthrows_1.default)(this._graph.getNode(nodeId));
1105
+ if (node.type === 'bundle' && node.value.id !== bundle.id) {
1106
+ referencingBundles.add(node.value);
1107
+ }
1108
+ }, exports.bundleGraphEdgeTypes.references);
1109
+ return [...referencingBundles];
1110
+ }
1111
+ getBundleGroupsContainingBundle(bundle) {
1112
+ let bundleGroups = new Set();
1113
+ for (let currentBundle of [bundle, ...this.getReferencingBundles(bundle)]) {
1114
+ for (let bundleGroup of this.getDirectParentBundleGroups(currentBundle)) {
1115
+ bundleGroups.add(bundleGroup);
1116
+ }
1117
+ }
1118
+ return [...bundleGroups];
1119
+ }
1120
+ getDirectParentBundleGroups(bundle) {
1121
+ return this._graph
1122
+ .getNodeIdsConnectedTo((0, nullthrows_1.default)(this._graph.getNodeIdByContentKey(bundle.id)), exports.bundleGraphEdgeTypes.bundle)
1123
+ .map((id) => (0, nullthrows_1.default)(this._graph.getNode(id)))
1124
+ .filter((node) => node.type === 'bundle_group')
1125
+ .map((node) => {
1126
+ (0, assert_2.default)(node.type === 'bundle_group');
1127
+ return node.value;
1128
+ });
1129
+ }
1130
+ getBundlesInBundleGroup(bundleGroup, opts) {
1131
+ let bundles = new Set();
1132
+ for (let bundleNodeId of this._graph.getNodeIdsConnectedFrom(this._graph.getNodeIdByContentKey((0, utils_2.getBundleGroupId)(bundleGroup)), exports.bundleGraphEdgeTypes.bundle)) {
1133
+ let bundleNode = (0, nullthrows_1.default)(this._graph.getNode(bundleNodeId));
1134
+ (0, assert_2.default)(bundleNode.type === 'bundle');
1135
+ let bundle = bundleNode.value;
1136
+ if (opts?.includeInline ||
1137
+ (bundle.bundleBehavior !== types_1.BundleBehavior.inline &&
1138
+ bundle.bundleBehavior !== types_1.BundleBehavior.inlineIsolated)) {
1139
+ bundles.add(bundle);
1140
+ }
1141
+ for (let referencedBundle of this.getReferencedBundles(bundle, {
1142
+ includeInline: opts?.includeInline,
1143
+ })) {
1144
+ bundles.add(referencedBundle);
1145
+ }
1146
+ }
1147
+ return [...bundles];
1148
+ }
1149
+ getReferencedBundles(bundle, opts) {
1150
+ let recursive = opts?.recursive ?? true;
1151
+ let includeInline = opts?.includeInline ?? false;
1152
+ let referencedBundles = new Set();
1153
+ this._graph.dfs({
1154
+ visit: (nodeId, _, actions) => {
1155
+ let node = (0, nullthrows_1.default)(this._graph.getNode(nodeId));
1156
+ if (node.type !== 'bundle') {
1157
+ return;
1158
+ }
1159
+ if (node.value.id === bundle.id) {
1160
+ return;
1161
+ }
1162
+ if (includeInline ||
1163
+ (node.value.bundleBehavior !== types_1.BundleBehavior.inline &&
1164
+ node.value.bundleBehavior !== types_1.BundleBehavior.inlineIsolated)) {
1165
+ referencedBundles.add(node.value);
1166
+ }
1167
+ if (!recursive) {
1168
+ actions.skipChildren();
1169
+ }
1170
+ },
1171
+ startNodeId: this._graph.getNodeIdByContentKey(bundle.id),
1172
+ getChildren: (nodeId) =>
1173
+ // Shared bundles seem to depend on being used in the opposite order
1174
+ // they were added.
1175
+ // TODO: Should this be the case?
1176
+ this._graph.getNodeIdsConnectedFrom(nodeId, exports.bundleGraphEdgeTypes.references),
1177
+ });
1178
+ // @ts-expect-error TS2322
1179
+ return [...referencedBundles];
1180
+ }
1181
+ getIncomingDependencies(asset) {
1182
+ if (!this._graph.hasContentKey(asset.id)) {
1183
+ return [];
1184
+ }
1185
+ // Dependencies can be a a parent node via an untyped edge (like in the AssetGraph but without AssetGroups)
1186
+ // or they can be parent nodes via a 'references' edge
1187
+ return this._graph
1188
+ .getNodeIdsConnectedTo(this._graph.getNodeIdByContentKey(asset.id), graph_1.ALL_EDGE_TYPES)
1189
+ .map((id) => (0, nullthrows_1.default)(this._graph.getNode(id)))
1190
+ .filter((n) => n.type === 'dependency')
1191
+ .map((n) => {
1192
+ (0, assert_2.default)(n.type === 'dependency');
1193
+ return n.value;
1194
+ });
1195
+ }
1196
+ getAssetWithDependency(dep) {
1197
+ if (!this._graph.hasContentKey(dep.id)) {
1198
+ return null;
1199
+ }
1200
+ let res = null;
1201
+ let count = 0;
1202
+ this._graph.forEachNodeIdConnectedTo(this._graph.getNodeIdByContentKey(dep.id),
1203
+ // @ts-expect-error TS2345
1204
+ (node) => {
1205
+ res = node;
1206
+ count += 1;
1207
+ if (count > 1) {
1208
+ throw new Error('Expected a single asset to be connected to a dependency');
1209
+ }
1210
+ }, 1);
1211
+ let resNode = res != null ? this._graph.getNode(res) : null;
1212
+ if (resNode?.type === 'asset') {
1213
+ return resNode.value;
1214
+ }
1215
+ }
1216
+ bundleHasAsset(bundle, asset) {
1217
+ let bundleNodeId = this._graph.getNodeIdByContentKey(bundle.id);
1218
+ let assetNodeId = this._graph.getNodeIdByContentKey(asset.id);
1219
+ return this._graph.hasEdge(bundleNodeId, assetNodeId, exports.bundleGraphEdgeTypes.contains);
1220
+ }
1221
+ bundleHasDependency(bundle, dependency) {
1222
+ let bundleNodeId = this._graph.getNodeIdByContentKey(bundle.id);
1223
+ let dependencyNodeId = this._graph.getNodeIdByContentKey(dependency.id);
1224
+ return this._graph.hasEdge(bundleNodeId, dependencyNodeId, exports.bundleGraphEdgeTypes.contains);
1225
+ }
1226
+ filteredTraverse(bundleNodeId, filter, visit) {
1227
+ return this._graph.filteredTraverse(filter, visit, bundleNodeId);
1228
+ }
1229
+ getSymbolResolution(asset, symbol, boundary) {
1230
+ let assetOutside = boundary && !this.bundleHasAsset(boundary, asset);
1231
+ let identifier = asset.symbols?.get(symbol)?.local;
1232
+ if (symbol === '*') {
1233
+ return {
1234
+ asset,
1235
+ exportSymbol: '*',
1236
+ symbol: identifier ?? null,
1237
+ loc: asset.symbols?.get(symbol)?.loc,
1238
+ };
1239
+ }
1240
+ let found = false;
1241
+ let nonStaticDependency = false;
1242
+ let skipped = false;
1243
+ let deps = this.getDependencies(asset).reverse();
1244
+ let potentialResults = [];
1245
+ for (let dep of deps) {
1246
+ let depSymbols = dep.symbols;
1247
+ if (!depSymbols) {
1248
+ nonStaticDependency = true;
1249
+ continue;
1250
+ }
1251
+ // If this is a re-export, find the original module.
1252
+ let symbolLookup = new Map([...depSymbols].map(([key, val]) => [val.local, key]));
1253
+ let depSymbol = symbolLookup.get(identifier);
1254
+ if (depSymbol != null) {
1255
+ let resolved = this.getResolvedAsset(dep, boundary);
1256
+ if (!resolved || resolved.id === asset.id) {
1257
+ // External module or self-reference
1258
+ return {
1259
+ asset,
1260
+ exportSymbol: symbol,
1261
+ symbol: identifier,
1262
+ loc: asset.symbols?.get(symbol)?.loc,
1263
+ };
1264
+ }
1265
+ if (assetOutside) {
1266
+ // We found the symbol, but `asset` is outside, return `asset` and the original symbol
1267
+ found = true;
1268
+ break;
1269
+ }
1270
+ if (this.isDependencySkipped(dep)) {
1271
+ // We found the symbol and `dep` was skipped
1272
+ skipped = true;
1273
+ break;
1274
+ }
1275
+ let { asset: resolvedAsset, symbol: resolvedSymbol, exportSymbol, loc, } = this.getSymbolResolution(resolved, depSymbol, boundary);
1276
+ if (!loc) {
1277
+ // Remember how we got there
1278
+ loc = asset.symbols?.get(symbol)?.loc;
1279
+ }
1280
+ return {
1281
+ asset: resolvedAsset,
1282
+ symbol: resolvedSymbol,
1283
+ exportSymbol,
1284
+ loc,
1285
+ };
1286
+ }
1287
+ // If this module exports wildcards, resolve the original module.
1288
+ // Default exports are excluded from wildcard exports.
1289
+ // Wildcard reexports are never listed in the reexporting asset's symbols.
1290
+ if (identifier == null &&
1291
+ depSymbols.get('*')?.local === '*' &&
1292
+ symbol !== 'default') {
1293
+ let resolved = this.getResolvedAsset(dep, boundary);
1294
+ if (!resolved) {
1295
+ continue;
1296
+ }
1297
+ let result = this.getSymbolResolution(resolved, symbol, boundary);
1298
+ // We found the symbol
1299
+ if (result.symbol != undefined) {
1300
+ if (assetOutside) {
1301
+ // ..., but `asset` is outside, return `asset` and the original symbol
1302
+ found = true;
1303
+ break;
1304
+ }
1305
+ if (this.isDependencySkipped(dep)) {
1306
+ // We found the symbol and `dep` was skipped
1307
+ skipped = true;
1308
+ break;
1309
+ }
1310
+ return {
1311
+ asset: result.asset,
1312
+ symbol: result.symbol,
1313
+ exportSymbol: result.exportSymbol,
1314
+ loc: resolved.symbols?.get(symbol)?.loc,
1315
+ };
1316
+ }
1317
+ if (result.symbol === null) {
1318
+ found = true;
1319
+ if (boundary && !this.bundleHasAsset(boundary, result.asset)) {
1320
+ // If the returned asset is outside (and it's the first asset that is outside), return it.
1321
+ if (!assetOutside) {
1322
+ return {
1323
+ asset: result.asset,
1324
+ symbol: result.symbol,
1325
+ exportSymbol: result.exportSymbol,
1326
+ loc: resolved.symbols?.get(symbol)?.loc,
1327
+ };
1328
+ }
1329
+ else {
1330
+ // Otherwise the original asset will be returned at the end.
1331
+ break;
1332
+ }
1333
+ }
1334
+ else {
1335
+ // We didn't find it in this dependency, but it might still be there: bailout.
1336
+ // Continue searching though, with the assumption that there are no conficting reexports
1337
+ // and there might be a another (re)export (where we might statically find the symbol).
1338
+ potentialResults.push({
1339
+ asset: result.asset,
1340
+ symbol: result.symbol,
1341
+ exportSymbol: result.exportSymbol,
1342
+ loc: resolved.symbols?.get(symbol)?.loc,
1343
+ });
1344
+ }
1345
+ }
1346
+ }
1347
+ }
1348
+ // We didn't find the exact symbol...
1349
+ if (potentialResults.length == 1) {
1350
+ // ..., but if it does exist, it has to be behind this one reexport.
1351
+ return potentialResults[0];
1352
+ }
1353
+ else {
1354
+ let result = identifier;
1355
+ if (skipped) {
1356
+ // ... and it was excluded (by symbol propagation) or deferred.
1357
+ // @ts-expect-error TS2322
1358
+ result = false;
1359
+ }
1360
+ else {
1361
+ // ... and there is no single reexport, but it might still be exported:
1362
+ if (found) {
1363
+ // Fallback to namespace access, because of a bundle boundary.
1364
+ // @ts-expect-error TS2322
1365
+ result = null;
1366
+ }
1367
+ else if (result === undefined) {
1368
+ // If not exported explicitly by the asset (= would have to be in * or a reexport-all) ...
1369
+ if (nonStaticDependency || asset.symbols?.has('*')) {
1370
+ // ... and if there are non-statically analyzable dependencies or it's a CJS asset,
1371
+ // fallback to namespace access.
1372
+ // @ts-expect-error TS2322
1373
+ result = null;
1374
+ }
1375
+ // (It shouldn't be possible for the symbol to be in a reexport-all and to end up here).
1376
+ // Otherwise return undefined to report that the symbol wasn't found.
1377
+ }
1378
+ }
1379
+ return {
1380
+ asset,
1381
+ exportSymbol: symbol,
1382
+ symbol: result,
1383
+ loc: asset.symbols?.get(symbol)?.loc,
1384
+ };
1385
+ }
1386
+ }
1387
+ getAssetById(contentKey) {
1388
+ let node = this._graph.getNodeByContentKey(contentKey);
1389
+ if (node == null) {
1390
+ throw new Error('Node not found');
1391
+ }
1392
+ else if (node.type !== 'asset') {
1393
+ throw new Error('Node was not an asset');
1394
+ }
1395
+ return node.value;
1396
+ }
1397
+ getAssetPublicId(asset) {
1398
+ let publicId = this._publicIdByAssetId.get(asset.id);
1399
+ if (publicId == null) {
1400
+ throw new Error("Asset or it's public id not found");
1401
+ }
1402
+ return publicId;
1403
+ }
1404
+ getExportedSymbols(asset, boundary) {
1405
+ if (!asset.symbols) {
1406
+ return [];
1407
+ }
1408
+ let symbols = [];
1409
+ for (let symbol of asset.symbols.keys()) {
1410
+ symbols.push({
1411
+ ...this.getSymbolResolution(asset, symbol, boundary),
1412
+ exportAs: symbol,
1413
+ });
1414
+ }
1415
+ let deps = this.getDependencies(asset);
1416
+ for (let dep of deps) {
1417
+ let depSymbols = dep.symbols;
1418
+ if (!depSymbols)
1419
+ continue;
1420
+ if (depSymbols.get('*')?.local === '*') {
1421
+ let resolved = this.getResolvedAsset(dep, boundary);
1422
+ if (!resolved)
1423
+ continue;
1424
+ let exported = this.getExportedSymbols(resolved, boundary)
1425
+ .filter((s) => s.exportSymbol !== 'default')
1426
+ .map((s) => s.exportSymbol !== '*' ? { ...s, exportAs: s.exportSymbol } : s);
1427
+ symbols.push(...exported);
1428
+ }
1429
+ }
1430
+ return symbols;
1431
+ }
1432
+ getContentHash(bundle) {
1433
+ let existingHash = this._bundleContentHashes.get(bundle.id);
1434
+ if (existingHash != null) {
1435
+ return existingHash;
1436
+ }
1437
+ let hash = new rust_1.Hash();
1438
+ // TODO: sort??
1439
+ this.traverseAssets(bundle, (asset) => {
1440
+ {
1441
+ hash.writeString([this.getAssetPublicId(asset), asset.id, asset.outputHash].join(':'));
1442
+ }
1443
+ });
1444
+ let hashHex = hash.finish();
1445
+ this._bundleContentHashes.set(bundle.id, hashHex);
1446
+ return hashHex;
1447
+ }
1448
+ getInlineBundles(bundle) {
1449
+ let bundles = [];
1450
+ let seen = new Set();
1451
+ let addReferencedBundles = (bundle) => {
1452
+ if (seen.has(bundle.id)) {
1453
+ return;
1454
+ }
1455
+ seen.add(bundle.id);
1456
+ let referencedBundles = this.getReferencedBundles(bundle, {
1457
+ includeInline: true,
1458
+ });
1459
+ for (let referenced of referencedBundles) {
1460
+ if (referenced.bundleBehavior === types_1.BundleBehavior.inline ||
1461
+ referenced.bundleBehavior === types_1.BundleBehavior.inlineIsolated) {
1462
+ bundles.push(referenced);
1463
+ addReferencedBundles(referenced);
1464
+ }
1465
+ }
1466
+ };
1467
+ addReferencedBundles(bundle);
1468
+ this.traverseBundles((childBundle, _, traversal) => {
1469
+ if (childBundle.bundleBehavior === types_1.BundleBehavior.inline ||
1470
+ childBundle.bundleBehavior === types_1.BundleBehavior.inlineIsolated) {
1471
+ bundles.push(childBundle);
1472
+ }
1473
+ else if (childBundle.id !== bundle.id) {
1474
+ traversal.skipChildren();
1475
+ }
1476
+ }, bundle);
1477
+ return bundles;
1478
+ }
1479
+ getHash(bundle) {
1480
+ let hash = new rust_1.Hash();
1481
+ hash.writeString(bundle.id + JSON.stringify(bundle.target) + this.getContentHash(bundle));
1482
+ if (bundle.isPlaceholder) {
1483
+ hash.writeString('placeholder');
1484
+ }
1485
+ let inlineBundles = this.getInlineBundles(bundle);
1486
+ for (let inlineBundle of inlineBundles) {
1487
+ hash.writeString(this.getContentHash(inlineBundle));
1488
+ }
1489
+ for (let referencedBundle of this.getReferencedBundles(bundle)) {
1490
+ hash.writeString(referencedBundle.id);
1491
+ }
1492
+ hash.writeString(JSON.stringify((0, utils_1.objectSortedEntriesDeep)((0, EnvironmentManager_1.fromEnvironmentId)(bundle.env))));
1493
+ return hash.finish();
1494
+ }
1495
+ getBundleGraphHash() {
1496
+ let hashes = '';
1497
+ for (let bundle of this.getBundles()) {
1498
+ hashes += this.getHash(bundle);
1499
+ }
1500
+ return (0, rust_1.hashString)(hashes);
1501
+ }
1502
+ addBundleToBundleGroup(bundle, bundleGroup) {
1503
+ let bundleGroupNodeId = this._graph.getNodeIdByContentKey((0, utils_2.getBundleGroupId)(bundleGroup));
1504
+ let bundleNodeId = this._graph.getNodeIdByContentKey(bundle.id);
1505
+ if (this._graph.hasEdge(bundleGroupNodeId, bundleNodeId, exports.bundleGraphEdgeTypes.bundle)) {
1506
+ // Bundle group already has bundle
1507
+ return;
1508
+ }
1509
+ this._graph.addEdge(bundleGroupNodeId, bundleNodeId);
1510
+ this._graph.addEdge(bundleGroupNodeId, bundleNodeId, exports.bundleGraphEdgeTypes.bundle);
1511
+ for (let entryAssetId of bundle.entryAssetIds) {
1512
+ let entryAssetNodeId = this._graph.getNodeIdByContentKey(entryAssetId);
1513
+ if (this._graph.hasEdge(bundleGroupNodeId, entryAssetNodeId)) {
1514
+ this._graph.removeEdge(bundleGroupNodeId, entryAssetNodeId);
1515
+ }
1516
+ }
1517
+ }
1518
+ getUsedSymbolsAsset(asset) {
1519
+ let node = this._graph.getNodeByContentKey(asset.id);
1520
+ (0, assert_2.default)(node && node.type === 'asset');
1521
+ return node.value.symbols
1522
+ ? makeReadOnlySet(new Set(node.usedSymbols.keys()))
1523
+ : null;
1524
+ }
1525
+ getUsedSymbolsDependency(dep) {
1526
+ let node = this._graph.getNodeByContentKey(dep.id);
1527
+ (0, assert_2.default)(node && node.type === 'dependency');
1528
+ return node.value.symbols
1529
+ ? makeReadOnlySet(new Set(node.usedSymbolsUp.keys()))
1530
+ : null;
1531
+ }
1532
+ merge(other) {
1533
+ let otherGraphIdToThisNodeId = new Map();
1534
+ for (let [otherNodeId, otherNode] of other._graph.nodes.entries()) {
1535
+ if (!otherNode)
1536
+ continue;
1537
+ if (this._graph.hasContentKey(otherNode.id)) {
1538
+ let existingNodeId = this._graph.getNodeIdByContentKey(otherNode.id);
1539
+ otherGraphIdToThisNodeId.set(otherNodeId, existingNodeId);
1540
+ let existingNode = (0, nullthrows_1.default)(this._graph.getNode(existingNodeId));
1541
+ // Merge symbols, recompute dep.excluded based on that
1542
+ if (existingNode.type === 'asset') {
1543
+ (0, assert_2.default)(otherNode.type === 'asset');
1544
+ existingNode.usedSymbols = new Set([
1545
+ ...existingNode.usedSymbols,
1546
+ ...otherNode.usedSymbols,
1547
+ ]);
1548
+ }
1549
+ else if (existingNode.type === 'dependency') {
1550
+ (0, assert_2.default)(otherNode.type === 'dependency');
1551
+ existingNode.usedSymbolsDown = new Set([
1552
+ ...existingNode.usedSymbolsDown,
1553
+ ...otherNode.usedSymbolsDown,
1554
+ ]);
1555
+ existingNode.usedSymbolsUp = new Map([
1556
+ ...existingNode.usedSymbolsUp,
1557
+ ...otherNode.usedSymbolsUp,
1558
+ ]);
1559
+ existingNode.excluded =
1560
+ (existingNode.excluded || Boolean(existingNode.hasDeferred)) &&
1561
+ (otherNode.excluded || Boolean(otherNode.hasDeferred));
1562
+ }
1563
+ }
1564
+ else {
1565
+ let updateNodeId = this._graph.addNodeByContentKey(otherNode.id, otherNode);
1566
+ otherGraphIdToThisNodeId.set(otherNodeId, updateNodeId);
1567
+ }
1568
+ }
1569
+ // @ts-expect-error TS2488
1570
+ for (let edge of other._graph.getAllEdges()) {
1571
+ this._graph.addEdge((0, nullthrows_1.default)(otherGraphIdToThisNodeId.get(edge.from)), (0, nullthrows_1.default)(otherGraphIdToThisNodeId.get(edge.to)), edge.type);
1572
+ }
1573
+ }
1574
+ isEntryBundleGroup(bundleGroup) {
1575
+ return this._graph
1576
+ .getNodeIdsConnectedTo((0, nullthrows_1.default)(this._graph.getNodeIdByContentKey((0, utils_2.getBundleGroupId)(bundleGroup))), exports.bundleGraphEdgeTypes.bundle)
1577
+ .map((id) => (0, nullthrows_1.default)(this._graph.getNode(id)))
1578
+ .some((n) => n.type === 'root');
1579
+ }
1580
+ /**
1581
+ * Update the asset in a Bundle Graph and clear the associated Bundle hash.
1582
+ */
1583
+ updateAsset(asset) {
1584
+ this._graph.updateNode(this._graph.getNodeIdByContentKey(asset.id), asset);
1585
+ let bundles = this.getBundlesWithAsset(asset.value);
1586
+ for (let bundle of bundles) {
1587
+ // the bundle content will change with a modified asset
1588
+ this._bundleContentHashes.delete(bundle.id);
1589
+ }
1590
+ }
1591
+ getEntryRoot(projectRoot, target) {
1592
+ let cached = this._targetEntryRoots.get(target.distDir);
1593
+ if (cached != null) {
1594
+ return cached;
1595
+ }
1596
+ let entryBundleGroupIds = this._graph.getNodeIdsConnectedFrom((0, nullthrows_1.default)(this._graph.rootNodeId), exports.bundleGraphEdgeTypes.bundle);
1597
+ let entries = [];
1598
+ for (let bundleGroupId of entryBundleGroupIds) {
1599
+ let bundleGroupNode = this._graph.getNode(bundleGroupId);
1600
+ (0, assert_2.default)(bundleGroupNode?.type === 'bundle_group');
1601
+ if (bundleGroupNode.value.target.distDir === target.distDir) {
1602
+ let entryAssetNode = this._graph.getNodeByContentKey(bundleGroupNode.value.entryAssetId);
1603
+ (0, assert_2.default)(entryAssetNode?.type === 'asset');
1604
+ entries.push((0, projectPath_1.fromProjectPath)(projectRoot, entryAssetNode.value.filePath));
1605
+ }
1606
+ }
1607
+ let root = (0, utils_1.getRootDir)(entries);
1608
+ this._targetEntryRoots.set(target.distDir, root);
1609
+ return root;
1610
+ }
1611
+ getReferencedConditionalBundles(bundle) {
1612
+ let referencedBundles = new Set();
1613
+ this._graph.dfs({
1614
+ visit: (nodeId) => {
1615
+ let node = (0, nullthrows_1.default)(this._graph.getNode(nodeId));
1616
+ if (node.type !== 'bundle' || node.value.id === bundle.id) {
1617
+ return;
1618
+ }
1619
+ referencedBundles.add(node.value);
1620
+ },
1621
+ startNodeId: this._graph.getNodeIdByContentKey(bundle.id),
1622
+ getChildren: (nodeId) => this._graph.getNodeIdsConnectedFrom(nodeId, exports.bundleGraphEdgeTypes.conditional),
1623
+ });
1624
+ // @ts-expect-error TS2322
1625
+ return [...referencedBundles];
1626
+ }
1627
+ }
1628
+ exports.default = BundleGraph;