@sgedda/mockifyer-fetch 1.8.87 → 1.8.92

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.
@@ -19,8 +19,12 @@
19
19
  * 15. POST /mockifyer-network-events/snapshot — write hops JSON/NDJSON under atlas-html/
20
20
  * 16. POST /mockifyer-network-events/render — render Atlas HTML from buffer hops
21
21
  * 17. POST /mockifyer-network-events/clear — clear ring buffer
22
- * 18. Metro terminal key `t` — start/stop Atlas capture (stop generates HTML; stream auto-starts; `atlasKey: false` to disable). `a` is reserved for Android.
23
- * 19. Metro terminal key `m` — open Mockifyer dashboard in the browser (`dashboardKey: false` to disable)
22
+ * 18. GET /mockifyer-atlas-live — live hop stream web page (SSE + expand/collapse)
23
+ * 19. GET /mockifyer-atlas-trace?id= — re-call a hop with X-Mockifyer-Include-Trace (`&format=html` opens a result tab)
24
+ * 20. GET /mockifyer-atlas-capture — Atlas `t` capture session active flag
25
+ * 21. Metro terminal key `t` — start/stop Atlas capture (start opens live stream; stop ends capture; Render docs on the live page writes HTML; stream auto-starts; `atlasKey: false` to disable). `a` is reserved for Android.
26
+ * 22. Metro terminal key `m` — open Mockifyer dashboard in the browser (`dashboardKey: false` to disable)
27
+ * 23. On hop ingest / Atlas render — pull nested hops from dashboard `/api/network-events/trace` (remote BFF → dashboard → Atlas)
24
28
  *
25
29
  * The Hybrid Provider (recommended) uses POST /mockifyer-save for instant file sync.
26
30
  * Legacy polling-based sync is still available for backward compatibility.
@@ -60,14 +64,28 @@ import {
60
64
  type NetworkEvent,
61
65
  getMetroNetworkEventBuffer,
62
66
  resolveNetworkEventBodyRelPaths,
67
+ networkBodySpillRelPath,
63
68
  analyzeMetroNetworkEvents,
64
69
  createEmptyAtlasDocMap,
65
70
  buildAtlasHarJson,
71
+ buildAtlasLiveStreamHtml,
72
+ buildAtlasTraceReplayHtml,
73
+ buildAtlasTracePendingHtml,
74
+ ATLAS_LIVE_STREAM_PATH,
75
+ ATLAS_TRACE_REPLAY_PATH,
76
+ ATLAS_TRACE_REPLAY_TIMEOUT_MS,
77
+ ATLAS_CAPTURE_SESSION_PATH,
78
+ replayNetworkEventWithIncludeTrace,
79
+ setMetroAtlasCaptureSessionActive,
80
+ isMetroAtlasCaptureSessionActive,
81
+ normalizeDashboardBaseUrl,
82
+ pullDashboardDescendantsForParents,
66
83
  } from "@sgedda/mockifyer-core";
67
84
  import {
68
85
  attachMetroAtlasKeyHandler,
69
86
  notifyMetroAtlasStreamClientConnected,
70
87
  notifyMetroAtlasStreamClientDisconnected,
88
+ resolveMetroDashboardUrl,
71
89
  type AtlasKeyOption,
72
90
  } from "./metro-atlas-key-handlers";
73
91
 
@@ -78,7 +96,8 @@ export interface MetroSyncMiddlewareOptions {
78
96
  mockDataPath?: string;
79
97
  /**
80
98
  * Metro terminal key that starts/stops Atlas capture (default `"t"`).
81
- * Start clears the hop buffer; stop generates HTML (same as `POST /mockifyer-network-events/render`).
99
+ * Start clears the hop buffer; stop ends capture. Write HTML via live page
100
+ * “Render docs” (`POST /mockifyer-network-events/render`) or the CLI.
82
101
  * Pass `false` to disable. `a` is reserved by Metro for Android.
83
102
  */
84
103
  atlasKey?: AtlasKeyOption;
@@ -115,8 +134,193 @@ const DEFAULT_SCENARIO = "default";
115
134
  /** Atlas render POSTs can include many hops + body spills — avoid O(n²) string concat. */
116
135
  const MAX_METRO_POST_BODY_BYTES = 64 * 1024 * 1024;
117
136
 
137
+ /**
138
+ * Debounce so a burst of hops triggers one dashboard read, and remote BFF children
139
+ * (logged slightly after the parent) have landed before we ask.
140
+ */
141
+ const DASHBOARD_ENRICH_DEBOUNCE_MS = 1_500;
142
+
143
+ /** Hard deadline for the enrichment on Atlas stop — `t` must never hang on a slow store. */
144
+ const DASHBOARD_ENRICH_DEADLINE_MS = 4_000;
145
+
118
146
  let autoSyncInterval: NodeJS.Timeout | null = null;
119
147
 
148
+ /** Last dashboard base seen on a hop POST (device proxy URL). */
149
+ let lastHopDashboardBaseUrl: string | undefined;
150
+ let dashboardEnrichTimer: ReturnType<typeof setTimeout> | null = null;
151
+ let dashboardEnrichInFlight: Promise<number> | null = null;
152
+
153
+ function clearDashboardTraceEnrichmentSchedules(): void {
154
+ if (dashboardEnrichTimer) {
155
+ clearTimeout(dashboardEnrichTimer);
156
+ dashboardEnrichTimer = null;
157
+ }
158
+ dashboardEnrichInFlight = null;
159
+ }
160
+
161
+ function resolveAtlasEnrichmentDashboardUrl(
162
+ middlewareDashboardUrl: string | undefined,
163
+ hopHint?: string,
164
+ ): string | undefined {
165
+ const fromHop = normalizeDashboardBaseUrl(hopHint);
166
+ if (fromHop) {
167
+ lastHopDashboardBaseUrl = fromHop;
168
+ return fromHop;
169
+ }
170
+ if (lastHopDashboardBaseUrl) {
171
+ return lastHopDashboardBaseUrl;
172
+ }
173
+ const hasExplicit =
174
+ Boolean(middlewareDashboardUrl?.trim()) ||
175
+ Boolean(
176
+ typeof process !== "undefined" &&
177
+ process.env.MOCKIFYER_DASHBOARD_URL?.trim(),
178
+ );
179
+ if (!hasExplicit) {
180
+ return undefined;
181
+ }
182
+ return normalizeDashboardBaseUrl(
183
+ resolveMetroDashboardUrl(middlewareDashboardUrl),
184
+ );
185
+ }
186
+
187
+ /**
188
+ * Merge remote-service children into the Metro buffer with a single dashboard read.
189
+ * Buffered hop ids are the parents; descendants are linked by `parentRequestId`.
190
+ * Returns how many new hops were appended. Never throws.
191
+ */
192
+ async function enrichMetroBufferFromDashboard(options: {
193
+ dashboardBaseUrl: string;
194
+ mockDataPath: string;
195
+ timeoutMs?: number;
196
+ }): Promise<number> {
197
+ if (!options.dashboardBaseUrl) {
198
+ return 0;
199
+ }
200
+ if (dashboardEnrichInFlight) {
201
+ return dashboardEnrichInFlight;
202
+ }
203
+
204
+ const flight = (async (): Promise<number> => {
205
+ const buffer = getMetroNetworkEventBuffer();
206
+ const existing = buffer.list();
207
+ const parentRequestIds = [
208
+ ...new Set(
209
+ existing
210
+ .map((event) => event.requestId?.trim())
211
+ .filter((id): id is string => Boolean(id)),
212
+ ),
213
+ ];
214
+ if (parentRequestIds.length === 0) {
215
+ return 0;
216
+ }
217
+
218
+ const children = await pullDashboardDescendantsForParents({
219
+ dashboardBaseUrl: options.dashboardBaseUrl,
220
+ parentRequestIds,
221
+ existing,
222
+ timeoutMs: options.timeoutMs,
223
+ });
224
+
225
+ let added = 0;
226
+ for (const child of children) {
227
+ const stored = buffer.append(child);
228
+ appendNetworkEventNdjson(options.mockDataPath, stored);
229
+ added += 1;
230
+ }
231
+ return added;
232
+ })();
233
+
234
+ dashboardEnrichInFlight = flight;
235
+ try {
236
+ return await flight;
237
+ } catch {
238
+ return 0;
239
+ } finally {
240
+ dashboardEnrichInFlight = null;
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Render the current Metro hop buffer to Atlas HTML and log the outcome.
246
+ * Returns the same shape as {@link renderNetworkEventsAtlasHtml}. When the
247
+ * buffer is empty, leaves any existing `index.html` alone.
248
+ */
249
+ function renderBufferedAtlasHtml(options: {
250
+ projectRoot: string;
251
+ mockDataPath: string;
252
+ scenario?: string;
253
+ }): {
254
+ success: boolean;
255
+ written: number;
256
+ outputDir: string;
257
+ indexPath: string;
258
+ hopCount: number;
259
+ error?: string;
260
+ } {
261
+ const events = [...getMetroNetworkEventBuffer().list()].reverse();
262
+ const outDir = path.join(options.mockDataPath, "atlas-html");
263
+ const indexPath = path.join(outDir, "index.html");
264
+ const relativeFromRoot = path
265
+ .relative(options.projectRoot, outDir)
266
+ .split(path.sep)
267
+ .join("/");
268
+ if (events.length === 0) {
269
+ console.warn(
270
+ `[Mockifyer] Atlas: 0 hops — keeping the existing ${indexPath}`,
271
+ );
272
+ console.warn(
273
+ "[Mockifyer] Atlas: no hops reached Metro. Check that Mockifyer is enabled in the app " +
274
+ "(runtimeMode 'manual' needs the dev-menu switch), that the app made requests during the " +
275
+ "session, and that hops arrive: curl http://localhost:8081/mockifyer-network-events",
276
+ );
277
+ return {
278
+ success: false,
279
+ written: 0,
280
+ outputDir: relativeFromRoot,
281
+ indexPath,
282
+ hopCount: 0,
283
+ error: "0 hops — existing index.html left unchanged",
284
+ };
285
+ }
286
+ const startedAt = Date.now();
287
+ const result = renderNetworkEventsAtlasHtml(
288
+ options.projectRoot,
289
+ options.mockDataPath,
290
+ events,
291
+ options.scenario,
292
+ );
293
+ if (result.success) {
294
+ const elapsedMs = Date.now() - startedAt;
295
+ console.log(
296
+ `[Mockifyer] Atlas HTML (${result.hopCount} hop(s), ${elapsedMs}ms) → ${result.indexPath}`,
297
+ );
298
+ } else {
299
+ console.error(
300
+ `[Mockifyer] Atlas render failed: ${result.error ?? "unknown"}`,
301
+ );
302
+ }
303
+ return result;
304
+ }
305
+
306
+ /** Coalesce hop-ingest bursts into one dashboard read. */
307
+ function scheduleDashboardTraceEnrichment(options: {
308
+ dashboardBaseUrl: string;
309
+ mockDataPath: string;
310
+ }): void {
311
+ if (!options.dashboardBaseUrl) {
312
+ return;
313
+ }
314
+ if (dashboardEnrichTimer) {
315
+ clearTimeout(dashboardEnrichTimer);
316
+ }
317
+ dashboardEnrichTimer = setTimeout(() => {
318
+ dashboardEnrichTimer = null;
319
+ void enrichMetroBufferFromDashboard(options);
320
+ }, DASHBOARD_ENRICH_DEBOUNCE_MS);
321
+ dashboardEnrichTimer.unref?.();
322
+ }
323
+
120
324
  /**
121
325
  * Buffer an incoming request body with `Buffer.concat` (not `body += chunk`).
122
326
  * Large Atlas render payloads hang for minutes with quadratic string concatenation.
@@ -1024,9 +1228,158 @@ function saveAtlasScreenshot(
1024
1228
  }
1025
1229
  }
1026
1230
 
1231
+ /**
1232
+ * Candidate relative body paths for a hop (refs first, then id / requestId variants).
1233
+ * Spills key by requestId when present, but older captures / races can land under event.id.
1234
+ */
1235
+ function candidateBodyRelPaths(
1236
+ event: NetworkEvent,
1237
+ side: "req" | "res",
1238
+ ): string[] {
1239
+ const preferred = resolveNetworkEventBodyRelPaths(event);
1240
+ const out: string[] = [side === "req" ? preferred.req : preferred.res];
1241
+ const push = (rel: string | undefined) => {
1242
+ const trimmed = rel?.trim();
1243
+ if (!trimmed || out.includes(trimmed)) return;
1244
+ out.push(trimmed);
1245
+ };
1246
+ if (side === "req") push(event.requestBodyRef);
1247
+ else push(event.responseBodyRef);
1248
+ push(networkBodySpillRelPath(event.id, event.requestId, side));
1249
+ push(networkBodySpillRelPath(event.id, null, side));
1250
+ if (event.requestId?.trim()) {
1251
+ push(networkBodySpillRelPath(event.requestId, event.requestId, side));
1252
+ }
1253
+ return out;
1254
+ }
1255
+
1027
1256
  const BODY_SPILL_REL_PATTERN =
1028
1257
  /^bodies\/[A-Za-z0-9._-]+-(req|res)\.(json|txt)$/;
1029
1258
 
1259
+ /**
1260
+ * Locate a full body on disk or in the Metro spill buffer.
1261
+ * Writes a buffer hit for *this* hop only — never flushes the whole spill map
1262
+ * (that blocked Metro for seconds on every req/res/trace click).
1263
+ */
1264
+ function findExistingBodyFile(options: {
1265
+ projectRoot: string;
1266
+ mockDataPath: string;
1267
+ event: NetworkEvent;
1268
+ side: "req" | "res";
1269
+ }): { abs: string; rel: string; text?: string } | null {
1270
+ const outDir = path.join(options.mockDataPath, "atlas-html");
1271
+ const outDirResolved = path.resolve(outDir);
1272
+ const snapshot = getNetworkBodySpillSnapshot();
1273
+
1274
+ for (const rel of candidateBodyRelPaths(options.event, options.side)) {
1275
+ // Validate path: reject absolute paths, parent traversal, and paths outside atlas-html
1276
+ if (!rel || rel.includes("..") || path.isAbsolute(rel)) {
1277
+ continue;
1278
+ }
1279
+ const abs = path.resolve(outDir, rel);
1280
+ const outDirPrefix = outDirResolved.endsWith(path.sep)
1281
+ ? outDirResolved
1282
+ : outDirResolved + path.sep;
1283
+ if (abs !== outDirResolved && !abs.startsWith(outDirPrefix)) {
1284
+ continue;
1285
+ }
1286
+
1287
+ const fromBuffer = snapshot[rel];
1288
+ if (typeof fromBuffer === "string" && fromBuffer.length > 0) {
1289
+ const saved = saveAtlasBodySpill(
1290
+ options.projectRoot,
1291
+ options.mockDataPath,
1292
+ rel,
1293
+ fromBuffer,
1294
+ );
1295
+ if (saved.success && saved.filePath) {
1296
+ return { abs: saved.filePath, rel, text: fromBuffer };
1297
+ }
1298
+ return {
1299
+ abs,
1300
+ rel,
1301
+ text: fromBuffer,
1302
+ };
1303
+ }
1304
+ if (fs.existsSync(abs)) {
1305
+ return { abs, rel };
1306
+ }
1307
+ }
1308
+ return null;
1309
+ }
1310
+
1311
+ /**
1312
+ * Read spilled request body text for a live include-trace re-call (optional).
1313
+ * Prefer in-memory spill; fall back to disk. Does not flush other hops.
1314
+ */
1315
+ function readSpilledRequestBodyText(
1316
+ projectRoot: string,
1317
+ mockDataPath: string,
1318
+ event: NetworkEvent,
1319
+ ): string | undefined {
1320
+ const snapshot = getNetworkBodySpillSnapshot();
1321
+ for (const rel of candidateBodyRelPaths(event, "req")) {
1322
+ const fromBuffer = snapshot[rel];
1323
+ if (typeof fromBuffer === "string" && fromBuffer.length > 0) {
1324
+ return fromBuffer;
1325
+ }
1326
+ }
1327
+ const found = findExistingBodyFile({
1328
+ projectRoot,
1329
+ mockDataPath,
1330
+ event,
1331
+ side: "req",
1332
+ });
1333
+ if (!found) return undefined;
1334
+ if (typeof found.text === "string") return found.text;
1335
+ try {
1336
+ return fs.readFileSync(found.abs, "utf8");
1337
+ } catch {
1338
+ return undefined;
1339
+ }
1340
+ }
1341
+
1342
+ /**
1343
+ * Nested hops already in the Metro buffer for this request (shown on the
1344
+ * include-trace HTML result page before the live re-call payload).
1345
+ */
1346
+ function formatCapturedTraceLines(
1347
+ events: readonly NetworkEvent[],
1348
+ root: NetworkEvent,
1349
+ ): string[] {
1350
+ const byParent = new Map<string, NetworkEvent[]>();
1351
+ for (const ev of events) {
1352
+ const parent =
1353
+ typeof ev.parentRequestId === "string" ? ev.parentRequestId.trim() : "";
1354
+ if (!parent) continue;
1355
+ const list = byParent.get(parent) ?? [];
1356
+ list.push(ev);
1357
+ byParent.set(parent, list);
1358
+ }
1359
+
1360
+ const lines: string[] = [];
1361
+ const guard = new Set<string>();
1362
+ const walk = (ev: NetworkEvent, depth: number): void => {
1363
+ const id =
1364
+ (typeof ev.requestId === "string" && ev.requestId.trim()) ||
1365
+ (typeof ev.id === "string" ? ev.id.trim() : "");
1366
+ if (id && guard.has(id)) return;
1367
+ if (id) guard.add(id);
1368
+ const indent = depth > 0 ? `${" ".repeat(depth)}` : "";
1369
+ const status = ev.status != null ? String(ev.status) : "—";
1370
+ const ms = ev.durationMs != null ? `${ev.durationMs}ms` : "";
1371
+ lines.push(
1372
+ `${indent}${(ev.method || "?").toUpperCase()} ${status} ${ms} ${ev.url || ev.path || ""}`.trimEnd(),
1373
+ );
1374
+ if (!id) return;
1375
+ for (const kid of byParent.get(id) || []) {
1376
+ walk(kid, depth + 1);
1377
+ }
1378
+ };
1379
+ walk(root, 0);
1380
+ return lines;
1381
+ }
1382
+
1030
1383
  /**
1031
1384
  * Persist a full hop body spill from the device (RN) under atlas-html/bodies/.
1032
1385
  */
@@ -1281,26 +1634,22 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1281
1634
  atlasKey: options?.atlasKey,
1282
1635
  dashboardKey: options?.dashboardKey,
1283
1636
  dashboardUrl: options?.dashboardUrl,
1284
- onSessionStart: () => {
1285
- getMetroNetworkEventBuffer().clear();
1637
+ onSessionStart: (reason) => {
1638
+ clearDashboardTraceEnrichmentSchedules();
1639
+ // Explicit `t` starts a clean session. Live-stream connect must NOT wipe hops
1640
+ // already in the buffer (that made the live page look empty and empty HTML on stop).
1641
+ if (reason === "key") {
1642
+ lastHopDashboardBaseUrl = undefined;
1643
+ getMetroNetworkEventBuffer().clear();
1644
+ }
1645
+ setMetroAtlasCaptureSessionActive(true);
1286
1646
  },
1287
- onSessionStop: () => {
1288
- const buffer = getMetroNetworkEventBuffer();
1289
- const events = [...buffer.list()].reverse();
1290
- const result = renderNetworkEventsAtlasHtml(
1291
- projectRoot,
1292
- mockDataPath,
1293
- events,
1647
+ onSessionStop: async () => {
1648
+ setMetroAtlasCaptureSessionActive(false);
1649
+ const hopCount = getMetroNetworkEventBuffer().list().length;
1650
+ console.log(
1651
+ `[Mockifyer] Atlas: capture ended with ${hopCount} hop(s) in buffer — use live page “Render docs” (or POST /mockifyer-network-events/render) to write HTML.`,
1294
1652
  );
1295
- if (result.success) {
1296
- console.log(
1297
- `[Mockifyer] Atlas HTML (${result.hopCount} hop(s)) → ${result.indexPath}`,
1298
- );
1299
- } else {
1300
- console.error(
1301
- `[Mockifyer] Atlas render failed: ${result.error ?? "unknown"}`,
1302
- );
1303
- }
1304
1653
  },
1305
1654
  });
1306
1655
 
@@ -1315,6 +1664,179 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1315
1664
  return;
1316
1665
  }
1317
1666
 
1667
+ // Atlas `t` capture session flag — device / live page poll this for session UI.
1668
+ if (
1669
+ (url === ATLAS_CAPTURE_SESSION_PATH ||
1670
+ url === `${ATLAS_CAPTURE_SESSION_PATH}/`) &&
1671
+ req.method === "GET"
1672
+ ) {
1673
+ res.setHeader("Content-Type", "application/json");
1674
+ res.setHeader("Cache-Control", "no-store");
1675
+ res.end(
1676
+ JSON.stringify({
1677
+ success: true,
1678
+ active: isMetroAtlasCaptureSessionActive(),
1679
+ }),
1680
+ );
1681
+ return;
1682
+ }
1683
+
1684
+ // Live Atlas hop stream page (browser EventSource → same SSE as mockifyer-atlas CLI)
1685
+ if (
1686
+ (url === ATLAS_LIVE_STREAM_PATH || url === `${ATLAS_LIVE_STREAM_PATH}/`) &&
1687
+ req.method === "GET"
1688
+ ) {
1689
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1690
+ res.setHeader("Cache-Control", "no-store");
1691
+ res.end(
1692
+ buildAtlasLiveStreamHtml({
1693
+ dashboardUrl: resolveMetroDashboardUrl(options?.dashboardUrl),
1694
+ }),
1695
+ );
1696
+ return;
1697
+ }
1698
+
1699
+ // Re-call a buffered hop with X-Mockifyer-Include-Trace (live page "trace" link).
1700
+ // Live HTTP only — nested hops come back on the response; no disk/Redis store required.
1701
+ // `format=html` returns a result page (new browser tab); default remains JSON.
1702
+ if (req.method === "GET" && url === ATLAS_TRACE_REPLAY_PATH) {
1703
+ const fullUrl = String(req.url || "");
1704
+ const q = fullUrl.includes("?")
1705
+ ? fullUrl.slice(fullUrl.indexOf("?") + 1)
1706
+ : "";
1707
+ const params = new URLSearchParams(q);
1708
+ const hopId = (params.get("id") || "").trim();
1709
+ const includeBodies = params.get("bodies") !== "0";
1710
+ const wantHtml =
1711
+ params.get("format") === "html" ||
1712
+ String(req.headers?.accept || "").includes("text/html");
1713
+ if (!hopId) {
1714
+ res.statusCode = 400;
1715
+ if (wantHtml) {
1716
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1717
+ res.end(
1718
+ buildAtlasTraceReplayHtml(
1719
+ {
1720
+ success: false,
1721
+ hopId: "",
1722
+ method: "",
1723
+ url: "",
1724
+ error: "id query param required",
1725
+ requestHeaders: {},
1726
+ },
1727
+ {
1728
+ atlasLiveUrl: ATLAS_LIVE_STREAM_PATH,
1729
+ dashboardUrl: resolveMetroDashboardUrl(options?.dashboardUrl),
1730
+ },
1731
+ ),
1732
+ );
1733
+ } else {
1734
+ res.setHeader("Content-Type", "application/json");
1735
+ res.end(
1736
+ JSON.stringify({ success: false, error: "id query param required" }),
1737
+ );
1738
+ }
1739
+ return;
1740
+ }
1741
+ const buffer = getMetroNetworkEventBuffer();
1742
+ const events = buffer.list();
1743
+ const event =
1744
+ events.find((e) => e && (e.id === hopId || e.requestId === hopId)) ??
1745
+ undefined;
1746
+
1747
+ // format=html without wait=1: return a shell immediately so the tab is not
1748
+ // blank while the include-trace re-call runs (can be many seconds).
1749
+ if (wantHtml && params.get("wait") !== "1") {
1750
+ const waitParams = new URLSearchParams(params);
1751
+ waitParams.set("format", "html");
1752
+ waitParams.set("wait", "1");
1753
+ res.statusCode = 200;
1754
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1755
+ res.setHeader("Cache-Control", "no-store");
1756
+ res.end(
1757
+ buildAtlasTracePendingHtml({
1758
+ hopId,
1759
+ method: event?.method,
1760
+ url: event?.url,
1761
+ resultUrl: `${ATLAS_TRACE_REPLAY_PATH}?${waitParams.toString()}`,
1762
+ atlasLiveUrl: ATLAS_LIVE_STREAM_PATH,
1763
+ dashboardUrl: resolveMetroDashboardUrl(options?.dashboardUrl),
1764
+ timeoutMs: ATLAS_TRACE_REPLAY_TIMEOUT_MS,
1765
+ }),
1766
+ );
1767
+ return;
1768
+ }
1769
+
1770
+ const spilledRequestBody = event
1771
+ ? readSpilledRequestBodyText(projectRoot, mockDataPath, event)
1772
+ : undefined;
1773
+ const capturedLines = event
1774
+ ? formatCapturedTraceLines(events, event)
1775
+ : undefined;
1776
+ void replayNetworkEventWithIncludeTrace(events, hopId, {
1777
+ includeBodies,
1778
+ requestBody: spilledRequestBody,
1779
+ timeoutMs: ATLAS_TRACE_REPLAY_TIMEOUT_MS,
1780
+ })
1781
+ .then((result) => {
1782
+ if (res.writableEnded) return;
1783
+ res.statusCode = result.success
1784
+ ? 200
1785
+ : result.error === "hop not found"
1786
+ ? 404
1787
+ : 502;
1788
+ res.setHeader("Cache-Control", "no-store");
1789
+ if (wantHtml) {
1790
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1791
+ res.end(
1792
+ buildAtlasTraceReplayHtml(result, {
1793
+ capturedLines,
1794
+ atlasLiveUrl: ATLAS_LIVE_STREAM_PATH,
1795
+ dashboardUrl: resolveMetroDashboardUrl(options?.dashboardUrl),
1796
+ requestBody:
1797
+ spilledRequestBody ||
1798
+ (typeof event?.requestBodyPreview === "string"
1799
+ ? event.requestBodyPreview
1800
+ : undefined),
1801
+ }),
1802
+ );
1803
+ } else {
1804
+ res.setHeader("Content-Type", "application/json");
1805
+ res.end(JSON.stringify(result));
1806
+ }
1807
+ })
1808
+ .catch((error: unknown) => {
1809
+ if (res.writableEnded) return;
1810
+ const message =
1811
+ error instanceof Error ? error.message : String(error);
1812
+ res.statusCode = 500;
1813
+ res.setHeader("Cache-Control", "no-store");
1814
+ if (wantHtml) {
1815
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1816
+ res.end(
1817
+ buildAtlasTraceReplayHtml(
1818
+ {
1819
+ success: false,
1820
+ hopId,
1821
+ method: event?.method || "",
1822
+ url: event?.url || "",
1823
+ error: message,
1824
+ requestHeaders: {},
1825
+ },
1826
+ {
1827
+ atlasLiveUrl: ATLAS_LIVE_STREAM_PATH,
1828
+ dashboardUrl: resolveMetroDashboardUrl(options?.dashboardUrl),
1829
+ },
1830
+ ),
1831
+ );
1832
+ } else {
1833
+ res.setHeader("Content-Type", "application/json");
1834
+ res.end(JSON.stringify({ success: false, hopId, error: message }));
1835
+ }
1836
+ });
1837
+ return;
1838
+ }
1839
+
1318
1840
  // Live hop ring buffer for `mockifyer-atlas` interactive CLI
1319
1841
  if (url === "/mockifyer-network-events" && req.method === "POST") {
1320
1842
  collectRequestBodyUtf8(req, (err, body) => {
@@ -1328,6 +1850,7 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1328
1850
  const parsed = JSON.parse(body) as {
1329
1851
  event?: NetworkEvent;
1330
1852
  events?: NetworkEvent[];
1853
+ dashboardBaseUrl?: string;
1331
1854
  };
1332
1855
  const incoming: NetworkEvent[] = [];
1333
1856
  if (parsed.event && typeof parsed.event === "object") {
@@ -1355,6 +1878,13 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1355
1878
  appendNetworkEventNdjson(mockDataPath, stored);
1356
1879
  return stored;
1357
1880
  });
1881
+ const dashboardBaseUrl = resolveAtlasEnrichmentDashboardUrl(
1882
+ options?.dashboardUrl,
1883
+ parsed.dashboardBaseUrl,
1884
+ );
1885
+ if (dashboardBaseUrl) {
1886
+ scheduleDashboardTraceEnrichment({ dashboardBaseUrl, mockDataPath });
1887
+ }
1358
1888
  res.statusCode = 201;
1359
1889
  res.setHeader("Content-Type", "application/json");
1360
1890
  res.end(
@@ -1362,6 +1892,7 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1362
1892
  success: true,
1363
1893
  count: saved.length,
1364
1894
  size: buffer.size,
1895
+ atlasCaptureActive: isMetroAtlasCaptureSessionActive(),
1365
1896
  }),
1366
1897
  );
1367
1898
  } catch (error) {
@@ -1513,22 +2044,37 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1513
2044
  // empty / ignore
1514
2045
  }
1515
2046
  }
1516
- const buffer = getMetroNetworkEventBuffer();
1517
- const events = [...buffer.list()].reverse();
1518
- const result = renderNetworkEventsAtlasHtml(
1519
- projectRoot,
1520
- mockDataPath,
1521
- events,
1522
- scenario,
2047
+ const dashboardBaseUrl = resolveAtlasEnrichmentDashboardUrl(
2048
+ options?.dashboardUrl,
1523
2049
  );
1524
- res.statusCode = result.success ? 201 : 500;
1525
- res.setHeader("Content-Type", "application/json");
1526
- res.end(JSON.stringify(result));
2050
+ const finishRender = () => {
2051
+ const result = renderBufferedAtlasHtml({
2052
+ projectRoot,
2053
+ mockDataPath,
2054
+ scenario,
2055
+ });
2056
+ res.statusCode = result.success ? 201 : 500;
2057
+ res.setHeader("Content-Type", "application/json");
2058
+ res.end(JSON.stringify(result));
2059
+ };
2060
+ if (!dashboardBaseUrl) {
2061
+ finishRender();
2062
+ return;
2063
+ }
2064
+ void enrichMetroBufferFromDashboard({
2065
+ dashboardBaseUrl,
2066
+ mockDataPath,
2067
+ timeoutMs: DASHBOARD_ENRICH_DEADLINE_MS,
2068
+ }).then(() => {
2069
+ finishRender();
2070
+ });
1527
2071
  });
1528
2072
  return;
1529
2073
  }
1530
2074
 
1531
2075
  if (url === "/mockifyer-network-events/clear" && req.method === "POST") {
2076
+ clearDashboardTraceEnrichmentSchedules();
2077
+ lastHopDashboardBaseUrl = undefined;
1532
2078
  const buffer = getMetroNetworkEventBuffer();
1533
2079
  buffer.clear();
1534
2080
  res.setHeader("Content-Type", "application/json");
@@ -1606,6 +2152,10 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1606
2152
 
1607
2153
  // Generate-on-click for terminal OSC-8 links (terminals cannot hijack OSC-8).
1608
2154
  // GET /mockifyer-atlas-open?id=<hopId>&side=req|res|html
2155
+ //
2156
+ // req/res must stay fast: look up the hop + flush/serve the body spill only.
2157
+ // Never rebuild the full Atlas HTML site here — that used to hang for seconds
2158
+ // when the buffer was large (writeAtlasDocHtml for every hop).
1609
2159
  if (
1610
2160
  req.method === "GET" &&
1611
2161
  (url === "/mockifyer-atlas-open" || url.startsWith("/mockifyer-atlas-open?"))
@@ -1619,22 +2169,27 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1619
2169
  sideParam === "req" || sideParam === "res" ? sideParam : "html";
1620
2170
 
1621
2171
  const buffer = getMetroNetworkEventBuffer();
1622
- // Buffer is newest-first; render expects chronological / display order.
1623
- const events = [...buffer.list()].reverse();
1624
- const rendered = renderNetworkEventsAtlasHtml(projectRoot, mockDataPath, events);
1625
- if (!rendered.success) {
1626
- res.statusCode = 500;
1627
- res.setHeader("Content-Type", "application/json");
1628
- res.end(
1629
- JSON.stringify({
1630
- success: false,
1631
- error: rendered.error || "atlas render failed",
1632
- }),
1633
- );
1634
- return;
1635
- }
2172
+ const listed = buffer.list();
1636
2173
 
1637
2174
  if (side === "html") {
2175
+ // Full site rebuild only when opening the Atlas index (terminal / html link).
2176
+ const events = [...listed].reverse();
2177
+ const rendered = renderNetworkEventsAtlasHtml(
2178
+ projectRoot,
2179
+ mockDataPath,
2180
+ events,
2181
+ );
2182
+ if (!rendered.success) {
2183
+ res.statusCode = 500;
2184
+ res.setHeader("Content-Type", "application/json");
2185
+ res.end(
2186
+ JSON.stringify({
2187
+ success: false,
2188
+ error: rendered.error || "atlas render failed",
2189
+ }),
2190
+ );
2191
+ return;
2192
+ }
1638
2193
  res.statusCode = 302;
1639
2194
  res.setHeader("Location", "/atlas-html/index.html");
1640
2195
  res.end();
@@ -1643,8 +2198,8 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1643
2198
 
1644
2199
  const event =
1645
2200
  (hopId
1646
- ? events.find((e) => e && (e.id === hopId || e.requestId === hopId))
1647
- : undefined) || events[0];
2201
+ ? listed.find((e) => e && (e.id === hopId || e.requestId === hopId))
2202
+ : undefined) || listed[0];
1648
2203
  if (!event) {
1649
2204
  res.statusCode = 404;
1650
2205
  res.setHeader("Content-Type", "application/json");
@@ -1652,53 +2207,94 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1652
2207
  return;
1653
2208
  }
1654
2209
 
1655
- const rels = resolveNetworkEventBodyRelPaths(event);
1656
- const rel = side === "req" ? rels.req : rels.res;
1657
- const abs = path.join(mockDataPath, "atlas-html", rel);
1658
- const outDir = path.join(mockDataPath, "atlas-html");
1659
- // Prefer real spill buffer / disk — never materialize the truncated Metro
1660
- // hop preview (often ~512 bytes) as the "full body" JSON page.
1661
- flushNetworkBodySpillsToDir(outDir);
1662
- const fromBuffer = getNetworkBodySpillSnapshot()[rel];
1663
- if (typeof fromBuffer === "string" && fromBuffer.length > 0) {
1664
- const saved = saveAtlasBodySpill(
1665
- projectRoot,
1666
- mockDataPath,
1667
- rel,
1668
- fromBuffer,
1669
- );
1670
- if (!saved.success) {
1671
- res.statusCode = 500;
1672
- res.setHeader("Content-Type", "application/json");
1673
- res.end(
1674
- JSON.stringify({
1675
- success: false,
1676
- error: saved.error || "Failed to write full body spill",
1677
- }),
2210
+ const found = findExistingBodyFile({
2211
+ projectRoot,
2212
+ mockDataPath,
2213
+ event,
2214
+ side,
2215
+ });
2216
+ if (found) {
2217
+ // Serve the body directly — a 302 to /atlas-html/... is a second hop and
2218
+ // used to queue behind other sync Atlas work in Metro.
2219
+ let text = found.text;
2220
+ if (typeof text !== "string") {
2221
+ try {
2222
+ text = fs.readFileSync(found.abs, "utf8");
2223
+ } catch {
2224
+ text = undefined;
2225
+ }
2226
+ }
2227
+ if (typeof text === "string") {
2228
+ const ext = path.extname(found.rel).toLowerCase();
2229
+ res.statusCode = 200;
2230
+ res.setHeader(
2231
+ "Content-Type",
2232
+ ext === ".json"
2233
+ ? "application/json; charset=utf-8"
2234
+ : "text/plain; charset=utf-8",
2235
+ );
2236
+ res.setHeader("Cache-Control", "no-store");
2237
+ res.setHeader("X-Mockifyer-Body-Source", "spill");
2238
+ res.setHeader(
2239
+ "X-Mockifyer-Body-Rel",
2240
+ found.rel.split(path.sep).join("/"),
1678
2241
  );
2242
+ res.end(text);
1679
2243
  return;
1680
2244
  }
1681
- } else if (!fs.existsSync(abs)) {
1682
- res.statusCode = 404;
1683
- res.setHeader("Content-Type", "application/json");
2245
+ res.statusCode = 302;
2246
+ res.setHeader(
2247
+ "Location",
2248
+ `/atlas-html/${found.rel.split(path.sep).join("/")}`,
2249
+ );
2250
+ res.end();
2251
+ return;
2252
+ }
2253
+
2254
+ // Spill not on disk yet (race) or never uploaded — still return the captured
2255
+ // preview so open/trace UX is usable. Do not write preview as the spill file.
2256
+ const preview =
2257
+ side === "req" ? event.requestBodyPreview : event.responseBodyPreview;
2258
+ if (typeof preview === "string" && preview.length > 0) {
2259
+ const preferred = resolveNetworkEventBodyRelPaths(event);
2260
+ res.statusCode = 200;
2261
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
2262
+ res.setHeader("Cache-Control", "no-store");
2263
+ res.setHeader("X-Mockifyer-Body-Source", "preview");
2264
+ res.setHeader(
2265
+ "X-Mockifyer-Body-Note",
2266
+ "Full spill file missing; showing hop preview",
2267
+ );
1684
2268
  res.end(
1685
- JSON.stringify({
1686
- success: false,
1687
- error:
1688
- "Full body not available on disk yet. Enable captureBodies / body spill, re-hit the endpoint, then open again. Refusing to write the truncated hop preview as the full body file.",
1689
- hopId: event.id,
1690
- side,
1691
- relativePath: rel,
1692
- }),
2269
+ JSON.stringify(
2270
+ {
2271
+ success: true,
2272
+ source: "preview",
2273
+ hopId: event.id,
2274
+ side,
2275
+ relativePath: side === "req" ? preferred.req : preferred.res,
2276
+ preview,
2277
+ },
2278
+ null,
2279
+ 2,
2280
+ ),
1693
2281
  );
1694
2282
  return;
1695
2283
  }
1696
- res.statusCode = 302;
1697
- res.setHeader(
1698
- "Location",
1699
- `/atlas-html/${rel.split(path.sep).join("/")}`,
2284
+
2285
+ const preferred = resolveNetworkEventBodyRelPaths(event);
2286
+ res.statusCode = 404;
2287
+ res.setHeader("Content-Type", "application/json");
2288
+ res.end(
2289
+ JSON.stringify({
2290
+ success: false,
2291
+ error:
2292
+ "No full body spill on disk and no hop preview. Re-hit the endpoint during Atlas capture, then open again.",
2293
+ hopId: event.id,
2294
+ side,
2295
+ relativePath: side === "req" ? preferred.req : preferred.res,
2296
+ }),
1700
2297
  );
1701
- res.end();
1702
2298
  return;
1703
2299
  }
1704
2300