@atlaspack/core 2.35.0 → 2.36.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.
@@ -3,7 +3,9 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
+ exports.SourceMapHashRefRewriteStream = void 0;
6
7
  exports.applyReplacementsToSourceMap = applyReplacementsToSourceMap;
8
+ exports.applyReplacementsToVLQMappings = applyReplacementsToVLQMappings;
7
9
  exports.computeSourceMapRoot = computeSourceMapRoot;
8
10
  exports.default = createWriteBundleRequest;
9
11
  var _constants = require("../constants");
@@ -78,7 +80,7 @@ function _featureFlags() {
78
80
  }
79
81
  var _EnvironmentManager = require("../EnvironmentManager");
80
82
  function _sourceMap() {
81
- const data = _interopRequireDefault(require("@atlaspack/source-map"));
83
+ const data = require("@atlaspack/source-map");
82
84
  _sourceMap = function () {
83
85
  return data;
84
86
  };
@@ -90,6 +92,9 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
90
92
  const HASH_REF_PREFIX_LEN = _constants.HASH_REF_PREFIX.length;
91
93
  const BOUNDARY_LENGTH = _constants.HASH_REF_PREFIX.length + 32 - 1;
92
94
  const HASH_REF_PLACEHOLDER_LEN = HASH_REF_PREFIX_LEN + _constants.HASH_REF_HASH_LEN;
95
+
96
+ // The JSON key prefix we scan for in the source map stream.
97
+ const MAPPINGS_KEY_BUF = Buffer.from('"mappings":"');
93
98
  /**
94
99
  * Writes a bundle to the dist directory, replacing hash references with the final content hashes.
95
100
  */
@@ -179,21 +184,11 @@ async function run({
179
184
  await writeFiles(contentStream, info, hashRefToNameHash, options, config, outputFS, filePath, writeOptions, devDeps, api, bundleReplacements);
180
185
  const hasSourceMap = await options.cache.has(mapKey);
181
186
  if (mapKey && env.sourceMap && !env.sourceMap.inline && hasSourceMap) {
187
+ const mapEntry = await options.cache.getBlob(mapKey);
182
188
  let mapStream;
183
189
  if ((0, _featureFlags().getFeatureFlag)('fixSourceMapHashRefs') && bundleReplacements && bundleReplacements.length > 0) {
184
- const mapEntry = await options.cache.getBlob(mapKey);
185
- const mapBuffer = Buffer.isBuffer(mapEntry) ? mapEntry : Buffer.from(mapEntry);
186
- const projectRoot = typeof options.projectRoot === 'string' ? options.projectRoot : String(options.projectRoot);
187
- const sourceMap = new (_sourceMap().default)(projectRoot, mapBuffer);
188
- applyReplacementsToSourceMap(sourceMap, bundleReplacements);
189
- const mapJson = await sourceMap.stringify({
190
- format: 'string',
191
- file: name,
192
- sourceRoot: computeSourceMapRoot(bundle, options)
193
- });
194
- mapStream = (0, _utils().blobToStream)(Buffer.from(typeof mapJson === 'string' ? mapJson : JSON.stringify(mapJson), 'utf8'));
190
+ mapStream = (0, _utils().blobToStream)(mapEntry).pipe(new SourceMapHashRefRewriteStream(bundleReplacements));
195
191
  } else {
196
- const mapEntry = await options.cache.getBlob(mapKey);
197
192
  mapStream = (0, _utils().blobToStream)(mapEntry);
198
193
  }
199
194
  await writeFiles(mapStream, info, hashRefToNameHash, options, config, outputFS, (0, _projectPath.toProjectPathUnsafe)((0, _projectPath.fromProjectPathRelative)(filePath) + '.map'), writeOptions, devDeps, api);
@@ -228,6 +223,178 @@ function applyReplacementsToSourceMap(sourceMap, replacements) {
228
223
  }
229
224
  }
230
225
 
226
+ /**
227
+ * Applies hash-ref replacement column offsets directly to a VLQ mappings
228
+ * string without deserializing the full source map into a native struct.
229
+ *
230
+ * Each replacement r describes a hash-ref that was substituted in the output
231
+ * file. r.column is in the progressively-shifted post-replacement coordinate
232
+ * space (matching the already-shifted source map state after all previous
233
+ * offsetColumns calls), so thresholds are applied sequentially against the
234
+ * running absCol values exactly as the native offsetColumns implementation does.
235
+ */
236
+ function applyReplacementsToVLQMappings(mappings, replacements) {
237
+ if (replacements.length === 0) return mappings;
238
+
239
+ // Group replacements by line (0-indexed), sorted by column ascending.
240
+ const byLine = new Map();
241
+ for (const r of replacements) {
242
+ let arr = byLine.get(r.line);
243
+ if (!arr) {
244
+ arr = [];
245
+ byLine.set(r.line, arr);
246
+ }
247
+ arr.push(r);
248
+ }
249
+ for (const arr of byLine.values()) {
250
+ arr.sort((a, b) => a.column - b.column);
251
+ }
252
+ const lines = mappings.split(';');
253
+ const resultLines = [];
254
+ for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
255
+ const lineReps = byLine.get(lineIdx);
256
+ if (!lineReps || lineReps.length === 0) {
257
+ resultLines.push(lines[lineIdx]);
258
+ continue;
259
+ }
260
+ const line = lines[lineIdx];
261
+ if (!line) {
262
+ resultLines.push('');
263
+ continue;
264
+ }
265
+
266
+ // Decode segment column deltas to absolute columns.
267
+ const segments = line.split(',');
268
+ const colVlqEnds = [];
269
+ const absCols = [];
270
+ let absCol = 0;
271
+ for (const seg of segments) {
272
+ const {
273
+ value: colDelta,
274
+ nextPos
275
+ } = (0, _sourceMap().decodeVLQ)(seg, 0);
276
+ absCol += colDelta;
277
+ colVlqEnds.push(nextPos);
278
+ absCols.push(absCol);
279
+ }
280
+
281
+ // Apply each replacement's column shift sequentially against the
282
+ // current absCol values (which have already been adjusted by previous
283
+ // replacements on this line), mirroring the sequential offsetColumns calls.
284
+ for (const r of lineReps) {
285
+ const delta = r.newLength - r.originalLength;
286
+ if (delta === 0) continue;
287
+ const threshold = r.column + r.originalLength;
288
+ for (let i = 0; i < absCols.length; i++) {
289
+ if (absCols[i] >= threshold) {
290
+ absCols[i] += delta;
291
+ }
292
+ }
293
+ }
294
+
295
+ // Re-encode with updated absolute columns; only the leading column VLQ
296
+ // field of each segment changes – the tail bytes are sliced unchanged.
297
+ const resultSegments = [];
298
+ let prevAbsCol = 0;
299
+ for (let i = 0; i < segments.length; i++) {
300
+ const newDelta = absCols[i] - prevAbsCol;
301
+ prevAbsCol = absCols[i];
302
+ resultSegments.push((0, _sourceMap().encodeVLQ)(newDelta) + segments[i].slice(colVlqEnds[i]));
303
+ }
304
+ resultLines.push(resultSegments.join(','));
305
+ }
306
+ return resultLines.join(';');
307
+ }
308
+ /**
309
+ * A Transform stream that rewrites the "mappings" VLQ field of a source map
310
+ * JSON to account for hash-ref replacements, without ever loading the full
311
+ * JSON object or the native Rust SourceMapInner into memory.
312
+ *
313
+ * Field order in cached source maps (from partialVlqMapToSourceMap / toVLQ):
314
+ * mappings → sources → sourcesContent → names → version → file → sourceRoot
315
+ *
316
+ * "mappings" is the very first field, so we scan only a tiny header before
317
+ * switching to zero-copy passthrough for the bulk sourcesContent bytes.
318
+ */
319
+ class SourceMapHashRefRewriteStream extends _stream().Transform {
320
+ constructor(replacements) {
321
+ super();
322
+ this.replacements = replacements;
323
+ this.state = 'scanning';
324
+ this.scanBuf = Buffer.alloc(0);
325
+ this.mappingsBufs = [];
326
+ }
327
+
328
+ // @ts-expect-error TS7006
329
+ _transform(chunk, _encoding, cb) {
330
+ if (this.state === 'passthrough') {
331
+ this.push(chunk);
332
+ cb();
333
+ return;
334
+ }
335
+ if (this.state === 'scanning') {
336
+ const combined = Buffer.concat([this.scanBuf, chunk]);
337
+ const idx = combined.indexOf(MAPPINGS_KEY_BUF);
338
+ if (idx === -1) {
339
+ // Key not yet found – hold back enough bytes to handle a split key.
340
+ const keepLen = Math.min(combined.length, MAPPINGS_KEY_BUF.length - 1);
341
+ if (combined.length > keepLen) {
342
+ this.push(combined.slice(0, combined.length - keepLen));
343
+ }
344
+ this.scanBuf = combined.slice(combined.length - keepLen);
345
+ cb();
346
+ return;
347
+ }
348
+
349
+ // Emit everything up to and including the key.
350
+ const keyEnd = idx + MAPPINGS_KEY_BUF.length;
351
+ this.push(combined.slice(0, keyEnd));
352
+ this.scanBuf = Buffer.alloc(0);
353
+ this.state = 'buffering';
354
+ this._bufferingTransform(combined.slice(keyEnd), cb);
355
+ return;
356
+ }
357
+
358
+ // state === 'buffering'
359
+ this._bufferingTransform(chunk, cb);
360
+ }
361
+
362
+ // @ts-expect-error TS7006
363
+ _bufferingTransform(chunk, cb) {
364
+ // Mappings values contain only base64 chars, ';', and ',' – no escaping –
365
+ // so scanning for the closing '"' (0x22) is safe.
366
+ const closeIdx = chunk.indexOf(0x22);
367
+ if (closeIdx === -1) {
368
+ this.mappingsBufs.push(chunk);
369
+ cb();
370
+ return;
371
+ }
372
+ this.mappingsBufs.push(chunk.slice(0, closeIdx));
373
+
374
+ // VLQ chars are all ASCII (<128), so latin1 round-trips without loss.
375
+ const mappingsStr = Buffer.concat(this.mappingsBufs).toString('latin1');
376
+ const rewritten = applyReplacementsToVLQMappings(mappingsStr, this.replacements);
377
+ this.push(Buffer.from(rewritten, 'latin1'));
378
+
379
+ // Emit the closing '"' and everything remaining in one push.
380
+ this.push(chunk.slice(closeIdx));
381
+ this.state = 'passthrough';
382
+ this.mappingsBufs = [];
383
+ cb();
384
+ }
385
+
386
+ // @ts-expect-error TS7006
387
+ _flush(cb) {
388
+ if (this.state === 'scanning' && this.scanBuf.length > 0) {
389
+ this.push(this.scanBuf);
390
+ } else if (this.state === 'buffering') {
391
+ // Malformed JSON – flush whatever we buffered as-is.
392
+ this.push(Buffer.concat(this.mappingsBufs));
393
+ }
394
+ cb();
395
+ }
396
+ }
397
+
231
398
  /**
232
399
  * Computes the sourceRoot for a source map file. This is the relative path from
233
400
  * the output directory back to the project root, so that source paths (stored
@@ -238,6 +405,7 @@ function applyReplacementsToSourceMap(sourceMap, replacements) {
238
405
  *
239
406
  * This logic must stay in sync with PackagerRunner.generateSourceMap.
240
407
  */
408
+ exports.SourceMapHashRefRewriteStream = SourceMapHashRefRewriteStream;
241
409
  function computeSourceMapRoot(bundle, options) {
242
410
  let name = (0, _nullthrows().default)(bundle.name);
243
411
  let filePath = (0, _projectPath.joinProjectPath)(bundle.target.distDir, name);
@@ -17,6 +17,13 @@ import type { BundleGraphResult } from './BundleGraphRequest';
17
17
  * Throws an assertion error if duplicate bundle names are found.
18
18
  */
19
19
  export declare function validateBundles(bundleGraph: InternalBundleGraph): void;
20
+ /**
21
+ * Dump a canonical JSON snapshot of the bundle graph for parity comparison.
22
+ * Gated by ATLASPACK_DUMP_BUNDLE_GRAPH environment variable which specifies the output directory.
23
+ * The snapshot captures bundle identity, type, contained assets, and bundle group structure
24
+ * in a deterministic, sorted format suitable for diffing.
25
+ */
26
+ export declare function dumpBundleGraphSnapshot(bundleGraph: InternalBundleGraph, variant: 'js' | 'rust'): void;
20
27
  /**
21
28
  * Names a bundle by running through the configured namers until one returns a name.
22
29
  */
@@ -4,6 +4,7 @@ import type { StaticRunOpts } from '../RequestTracker';
4
4
  import type { Bundle, PackagedBundleInfo, AtlaspackOptions } from '../types';
5
5
  import type BundleGraph from '../BundleGraph';
6
6
  import type { BundleInfo } from '../PackagerRunner';
7
+ import { Transform } from 'stream';
7
8
  import { requestTypes } from '../RequestTracker';
8
9
  import SourceMap from '@atlaspack/source-map';
9
10
  export type HashRefReplacement = {
@@ -33,6 +34,38 @@ export type WriteBundleRequest = {
33
34
  */
34
35
  export default function createWriteBundleRequest(input: WriteBundleRequestInput): WriteBundleRequest;
35
36
  export declare function applyReplacementsToSourceMap(sourceMap: SourceMap, replacements: HashRefReplacement[]): void;
37
+ /**
38
+ * Applies hash-ref replacement column offsets directly to a VLQ mappings
39
+ * string without deserializing the full source map into a native struct.
40
+ *
41
+ * Each replacement r describes a hash-ref that was substituted in the output
42
+ * file. r.column is in the progressively-shifted post-replacement coordinate
43
+ * space (matching the already-shifted source map state after all previous
44
+ * offsetColumns calls), so thresholds are applied sequentially against the
45
+ * running absCol values exactly as the native offsetColumns implementation does.
46
+ */
47
+ export declare function applyReplacementsToVLQMappings(mappings: string, replacements: HashRefReplacement[]): string;
48
+ /**
49
+ * A Transform stream that rewrites the "mappings" VLQ field of a source map
50
+ * JSON to account for hash-ref replacements, without ever loading the full
51
+ * JSON object or the native Rust SourceMapInner into memory.
52
+ *
53
+ * Field order in cached source maps (from partialVlqMapToSourceMap / toVLQ):
54
+ * mappings → sources → sourcesContent → names → version → file → sourceRoot
55
+ *
56
+ * "mappings" is the very first field, so we scan only a tiny header before
57
+ * switching to zero-copy passthrough for the bulk sourcesContent bytes.
58
+ */
59
+ export declare class SourceMapHashRefRewriteStream extends Transform {
60
+ private replacements;
61
+ private state;
62
+ private scanBuf;
63
+ private mappingsBufs;
64
+ constructor(replacements: HashRefReplacement[]);
65
+ _transform(chunk: Buffer, _encoding: string, cb: any): void;
66
+ private _bufferingTransform;
67
+ _flush(cb: any): void;
68
+ }
36
69
  /**
37
70
  * Computes the sourceRoot for a source map file. This is the relative path from
38
71
  * the output directory back to the project root, so that source paths (stored
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atlaspack/core",
3
- "version": "2.35.0",
3
+ "version": "2.36.0",
4
4
  "license": "(MIT OR Apache-2.0)",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -24,21 +24,21 @@
24
24
  "dependencies": {
25
25
  "@mischnic/json-sourcemap": "^0.1.0",
26
26
  "@atlaspack/build-cache": "2.13.13",
27
- "@atlaspack/cache": "3.2.50",
27
+ "@atlaspack/cache": "3.2.51",
28
28
  "@atlaspack/diagnostic": "2.14.4",
29
29
  "@atlaspack/events": "2.14.4",
30
30
  "@atlaspack/feature-flags": "2.30.1",
31
- "@atlaspack/fs": "2.15.50",
32
- "@atlaspack/graph": "3.6.17",
33
- "@atlaspack/logger": "2.14.47",
34
- "@atlaspack/package-manager": "2.14.55",
35
- "@atlaspack/plugin": "2.14.55",
36
- "@atlaspack/profiler": "2.15.16",
37
- "@atlaspack/rust": "3.24.0",
38
- "@atlaspack/types": "2.15.45",
39
- "@atlaspack/utils": "3.3.7",
40
- "@atlaspack/workers": "2.14.55",
41
- "@atlaspack/source-map": "3.2.10",
31
+ "@atlaspack/fs": "2.15.51",
32
+ "@atlaspack/graph": "3.6.18",
33
+ "@atlaspack/logger": "2.14.48",
34
+ "@atlaspack/package-manager": "2.14.56",
35
+ "@atlaspack/plugin": "2.14.56",
36
+ "@atlaspack/profiler": "2.15.17",
37
+ "@atlaspack/rust": "3.24.1",
38
+ "@atlaspack/types": "2.15.46",
39
+ "@atlaspack/utils": "3.3.8",
40
+ "@atlaspack/workers": "2.14.56",
41
+ "@atlaspack/source-map": "3.3.0",
42
42
  "base-x": "^3.0.8",
43
43
  "browserslist": "^4.6.6",
44
44
  "clone": "^2.1.1",
@@ -43,6 +43,7 @@ import {
43
43
  nameBundle,
44
44
  loadPluginConfigWithDevDeps,
45
45
  runDevDepRequest as runDevDepRequestShared,
46
+ dumpBundleGraphSnapshot,
46
47
  } from './BundleGraphRequestUtils';
47
48
  import createAssetGraphRequestJS from './AssetGraphRequest';
48
49
  import {createAssetGraphRequestRust} from './AssetGraphRequestRust';
@@ -396,16 +397,20 @@ class BundlerRunner {
396
397
  }
397
398
 
398
399
  // this the normal bundle workflow (bundle, optimizing, run-times, naming)
399
- await bundler.bundle({
400
- bundleGraph: mutableBundleGraph,
401
- config: this.configs.get(plugin.name)?.result,
402
- options: this.pluginOptions,
403
- logger,
404
- tracer,
400
+ await instrumentAsync('bundle (V2)', async () => {
401
+ await bundler.bundle({
402
+ bundleGraph: mutableBundleGraph,
403
+ config: this.configs.get(plugin.name)?.result,
404
+ options: this.pluginOptions,
405
+ logger,
406
+ tracer,
407
+ });
405
408
  });
406
409
 
407
410
  measurement && measurement.end();
408
411
 
412
+ dumpBundleGraphSnapshot(internalBundleGraph, 'js');
413
+
409
414
  if (this.pluginOptions.mode === 'production') {
410
415
  let optimizeMeasurement;
411
416
  try {
@@ -32,6 +32,7 @@ import {
32
32
  nameBundle,
33
33
  loadPluginConfigWithDevDeps,
34
34
  runDevDepRequest,
35
+ dumpBundleGraphSnapshot,
35
36
  } from './BundleGraphRequestUtils';
36
37
  import {toEnvironmentRef} from '../EnvironmentManager';
37
38
  import {getEnvironmentHash} from '../Environment';
@@ -109,6 +110,8 @@ export default function createBundleGraphRequestRust(
109
110
  () => getBundleGraph(serializedBundleGraph),
110
111
  );
111
112
 
113
+ dumpBundleGraphSnapshot(bundleGraph, 'rust');
114
+
112
115
  const runner = new NativeBundlerRunner(
113
116
  {api, options} as any,
114
117
  input.optionsRef,
@@ -17,11 +17,13 @@ import type {
17
17
  } from '../types';
18
18
 
19
19
  import assert from 'assert';
20
+ import fs from 'fs';
20
21
  import nullthrows from 'nullthrows';
22
+ import path from 'path';
21
23
  import {PluginLogger} from '@atlaspack/logger';
22
24
  import ThrowableDiagnostic, {errorToDiagnostic} from '@atlaspack/diagnostic';
23
25
  import {unique, setSymmetricDifference} from '@atlaspack/utils';
24
- import InternalBundleGraph from '../BundleGraph';
26
+ import InternalBundleGraph, {bundleGraphEdgeTypes} from '../BundleGraph';
25
27
  import BundleGraph from '../public/BundleGraph';
26
28
  import {Bundle, NamedBundle} from '../public/Bundle';
27
29
  import PluginOptions from '../public/PluginOptions';
@@ -66,6 +68,160 @@ export function validateBundles(bundleGraph: InternalBundleGraph): void {
66
68
  );
67
69
  }
68
70
 
71
+ /**
72
+ * Dump a canonical JSON snapshot of the bundle graph for parity comparison.
73
+ * Gated by ATLASPACK_DUMP_BUNDLE_GRAPH environment variable which specifies the output directory.
74
+ * The snapshot captures bundle identity, type, contained assets, and bundle group structure
75
+ * in a deterministic, sorted format suitable for diffing.
76
+ */
77
+ export function dumpBundleGraphSnapshot(
78
+ bundleGraph: InternalBundleGraph,
79
+ variant: 'js' | 'rust',
80
+ ): void {
81
+ let outDir = process.env.ATLASPACK_DUMP_BUNDLE_GRAPH;
82
+ if (!outDir) return;
83
+
84
+ let filename =
85
+ variant === 'js' ? 'bundle-graph-js.json' : 'bundle-graph-rust.json';
86
+ let outPath = path.join(outDir, filename);
87
+
88
+ fs.mkdirSync(outDir, {recursive: true});
89
+
90
+ let bundles = bundleGraph.getBundles();
91
+ let bundlesSnapshot = bundles
92
+ .map((bundle) => {
93
+ let bundleNodeId = bundleGraph._graph.getNodeIdByContentKey(bundle.id);
94
+ let containedAssetNodeIds = bundleGraph._graph.getNodeIdsConnectedFrom(
95
+ bundleNodeId,
96
+ bundleGraphEdgeTypes.contains,
97
+ );
98
+ let containedAssets = containedAssetNodeIds
99
+ .map((nodeId) => bundleGraph._graph.getNode(nodeId))
100
+ .flatMap((node) => {
101
+ if (node?.type !== 'asset') return [];
102
+ return [
103
+ {
104
+ id: node.value.id,
105
+ filePath: fromProjectPathRelative(node.value.filePath),
106
+ },
107
+ ];
108
+ })
109
+ .sort((a, b) => a.filePath.localeCompare(b.filePath));
110
+
111
+ // Resolve mainEntry and entry asset file paths
112
+ let mainEntryPath: string | null = null;
113
+ let entryAssetPaths: string[] = [];
114
+ if (bundle.mainEntryId) {
115
+ let mainEntryNodeId = bundleGraph._graph.getNodeIdByContentKey(
116
+ bundle.mainEntryId,
117
+ );
118
+ let mainEntryNode = bundleGraph._graph.getNode(mainEntryNodeId);
119
+ if (mainEntryNode?.type === 'asset') {
120
+ mainEntryPath = fromProjectPathRelative(mainEntryNode.value.filePath);
121
+ }
122
+ }
123
+ for (let entryId of bundle.entryAssetIds) {
124
+ let entryNodeId = bundleGraph._graph.getNodeIdByContentKey(entryId);
125
+ let entryNode = bundleGraph._graph.getNode(entryNodeId);
126
+ if (entryNode?.type === 'asset') {
127
+ entryAssetPaths.push(
128
+ fromProjectPathRelative(entryNode.value.filePath),
129
+ );
130
+ }
131
+ }
132
+ entryAssetPaths.sort();
133
+
134
+ return {
135
+ id: bundle.id,
136
+ type: bundle.type,
137
+ bundleBehavior: bundle.bundleBehavior ?? null,
138
+ needsStableName: bundle.needsStableName,
139
+ isSplittable: bundle.isSplittable,
140
+ isPlaceholder: bundle.isPlaceholder,
141
+ mainEntryPath,
142
+ entryAssetPaths,
143
+ assets: containedAssets.map((a) => a.filePath),
144
+ };
145
+ })
146
+ .sort((a, b) => {
147
+ // Sort by mainEntryPath first, then by sorted assets as tiebreaker
148
+ let aKey = a.mainEntryPath || a.assets.join(',');
149
+ let bKey = b.mainEntryPath || b.assets.join(',');
150
+ return aKey.localeCompare(bKey);
151
+ });
152
+
153
+ let bundleGroupsSnapshot = bundleGraph._graph.nodes
154
+ .flatMap((node) => {
155
+ if (node?.type !== 'bundle_group') return [];
156
+
157
+ let bundleGroup = node.value;
158
+
159
+ // Resolve entry asset file path
160
+ let entryAssetPath: string | null = null;
161
+ try {
162
+ let entryNodeId = bundleGraph._graph.getNodeIdByContentKey(
163
+ bundleGroup.entryAssetId,
164
+ );
165
+ let entryNode = bundleGraph._graph.getNode(entryNodeId);
166
+ if (entryNode?.type === 'asset') {
167
+ entryAssetPath = fromProjectPathRelative(entryNode.value.filePath);
168
+ }
169
+ } catch {
170
+ // Content key not found
171
+ }
172
+
173
+ let bundlesInGroup = bundleGraph.getBundlesInBundleGroup(bundleGroup);
174
+ let bundlePaths = bundlesInGroup
175
+ .map((b) => {
176
+ // Use mainEntry file path if available, otherwise bundle id as fallback
177
+ if (b.mainEntryId) {
178
+ try {
179
+ let nodeId = bundleGraph._graph.getNodeIdByContentKey(
180
+ b.mainEntryId,
181
+ );
182
+ let node = bundleGraph._graph.getNode(nodeId);
183
+ if (node?.type === 'asset') {
184
+ return fromProjectPathRelative(node.value.filePath);
185
+ }
186
+ } catch {
187
+ // fallback
188
+ }
189
+ }
190
+ return `[bundle:${b.id}]`;
191
+ })
192
+ .sort();
193
+
194
+ return [
195
+ {
196
+ entryAssetPath:
197
+ entryAssetPath ?? `[unknown:${bundleGroup.entryAssetId}]`,
198
+ bundlePaths,
199
+ },
200
+ ];
201
+ })
202
+ .sort((a, b) => a.entryAssetPath.localeCompare(b.entryAssetPath));
203
+
204
+ let totalAssets = bundleGraph._graph.nodes.filter(
205
+ (node) => node?.type === 'asset',
206
+ ).length;
207
+
208
+ let snapshot = {
209
+ version: 1,
210
+ variant,
211
+ stats: {
212
+ totalBundles: bundlesSnapshot.length,
213
+ totalBundleGroups: bundleGroupsSnapshot.length,
214
+ totalAssets,
215
+ },
216
+ bundles: bundlesSnapshot,
217
+ bundleGroups: bundleGroupsSnapshot,
218
+ };
219
+
220
+ fs.writeFileSync(outPath, JSON.stringify(snapshot, null, 2), 'utf8');
221
+ // eslint-disable-next-line no-console
222
+ console.log(`[BundleGraphSnapshot] Wrote ${variant} snapshot to ${outPath}`);
223
+ }
224
+
69
225
  /**
70
226
  * Names a bundle by running through the configured namers until one returns a name.
71
227
  */