@sgedda/mockifyer-fetch 1.8.86 → 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
  */
@@ -1274,30 +1627,29 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1274
1627
  `[MetroSyncMiddleware] Initialized with projectRoot: ${projectRoot}, mockDataPath: ${mockDataPath}`,
1275
1628
  );
1276
1629
 
1630
+ /** Last scenario announced at info. Polls of an unchanged scenario stay quiet. */
1631
+ let announcedScenario: string | undefined;
1632
+
1277
1633
  attachMetroAtlasKeyHandler({
1278
1634
  atlasKey: options?.atlasKey,
1279
1635
  dashboardKey: options?.dashboardKey,
1280
1636
  dashboardUrl: options?.dashboardUrl,
1281
- onSessionStart: () => {
1282
- 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);
1283
1646
  },
1284
- onSessionStop: () => {
1285
- const buffer = getMetroNetworkEventBuffer();
1286
- const events = [...buffer.list()].reverse();
1287
- const result = renderNetworkEventsAtlasHtml(
1288
- projectRoot,
1289
- mockDataPath,
1290
- 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.`,
1291
1652
  );
1292
- if (result.success) {
1293
- console.log(
1294
- `[Mockifyer] Atlas HTML (${result.hopCount} hop(s)) → ${result.indexPath}`,
1295
- );
1296
- } else {
1297
- console.error(
1298
- `[Mockifyer] Atlas render failed: ${result.error ?? "unknown"}`,
1299
- );
1300
- }
1301
1653
  },
1302
1654
  });
1303
1655
 
@@ -1312,6 +1664,179 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1312
1664
  return;
1313
1665
  }
1314
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
+
1315
1840
  // Live hop ring buffer for `mockifyer-atlas` interactive CLI
1316
1841
  if (url === "/mockifyer-network-events" && req.method === "POST") {
1317
1842
  collectRequestBodyUtf8(req, (err, body) => {
@@ -1325,6 +1850,7 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1325
1850
  const parsed = JSON.parse(body) as {
1326
1851
  event?: NetworkEvent;
1327
1852
  events?: NetworkEvent[];
1853
+ dashboardBaseUrl?: string;
1328
1854
  };
1329
1855
  const incoming: NetworkEvent[] = [];
1330
1856
  if (parsed.event && typeof parsed.event === "object") {
@@ -1352,6 +1878,13 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1352
1878
  appendNetworkEventNdjson(mockDataPath, stored);
1353
1879
  return stored;
1354
1880
  });
1881
+ const dashboardBaseUrl = resolveAtlasEnrichmentDashboardUrl(
1882
+ options?.dashboardUrl,
1883
+ parsed.dashboardBaseUrl,
1884
+ );
1885
+ if (dashboardBaseUrl) {
1886
+ scheduleDashboardTraceEnrichment({ dashboardBaseUrl, mockDataPath });
1887
+ }
1355
1888
  res.statusCode = 201;
1356
1889
  res.setHeader("Content-Type", "application/json");
1357
1890
  res.end(
@@ -1359,6 +1892,7 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1359
1892
  success: true,
1360
1893
  count: saved.length,
1361
1894
  size: buffer.size,
1895
+ atlasCaptureActive: isMetroAtlasCaptureSessionActive(),
1362
1896
  }),
1363
1897
  );
1364
1898
  } catch (error) {
@@ -1510,22 +2044,37 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1510
2044
  // empty / ignore
1511
2045
  }
1512
2046
  }
1513
- const buffer = getMetroNetworkEventBuffer();
1514
- const events = [...buffer.list()].reverse();
1515
- const result = renderNetworkEventsAtlasHtml(
1516
- projectRoot,
1517
- mockDataPath,
1518
- events,
1519
- scenario,
2047
+ const dashboardBaseUrl = resolveAtlasEnrichmentDashboardUrl(
2048
+ options?.dashboardUrl,
1520
2049
  );
1521
- res.statusCode = result.success ? 201 : 500;
1522
- res.setHeader("Content-Type", "application/json");
1523
- 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
+ });
1524
2071
  });
1525
2072
  return;
1526
2073
  }
1527
2074
 
1528
2075
  if (url === "/mockifyer-network-events/clear" && req.method === "POST") {
2076
+ clearDashboardTraceEnrichmentSchedules();
2077
+ lastHopDashboardBaseUrl = undefined;
1529
2078
  const buffer = getMetroNetworkEventBuffer();
1530
2079
  buffer.clear();
1531
2080
  res.setHeader("Content-Type", "application/json");
@@ -1603,6 +2152,10 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1603
2152
 
1604
2153
  // Generate-on-click for terminal OSC-8 links (terminals cannot hijack OSC-8).
1605
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).
1606
2159
  if (
1607
2160
  req.method === "GET" &&
1608
2161
  (url === "/mockifyer-atlas-open" || url.startsWith("/mockifyer-atlas-open?"))
@@ -1616,22 +2169,27 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1616
2169
  sideParam === "req" || sideParam === "res" ? sideParam : "html";
1617
2170
 
1618
2171
  const buffer = getMetroNetworkEventBuffer();
1619
- // Buffer is newest-first; render expects chronological / display order.
1620
- const events = [...buffer.list()].reverse();
1621
- const rendered = renderNetworkEventsAtlasHtml(projectRoot, mockDataPath, events);
1622
- if (!rendered.success) {
1623
- res.statusCode = 500;
1624
- res.setHeader("Content-Type", "application/json");
1625
- res.end(
1626
- JSON.stringify({
1627
- success: false,
1628
- error: rendered.error || "atlas render failed",
1629
- }),
1630
- );
1631
- return;
1632
- }
2172
+ const listed = buffer.list();
1633
2173
 
1634
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
+ }
1635
2193
  res.statusCode = 302;
1636
2194
  res.setHeader("Location", "/atlas-html/index.html");
1637
2195
  res.end();
@@ -1640,8 +2198,8 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1640
2198
 
1641
2199
  const event =
1642
2200
  (hopId
1643
- ? events.find((e) => e && (e.id === hopId || e.requestId === hopId))
1644
- : undefined) || events[0];
2201
+ ? listed.find((e) => e && (e.id === hopId || e.requestId === hopId))
2202
+ : undefined) || listed[0];
1645
2203
  if (!event) {
1646
2204
  res.statusCode = 404;
1647
2205
  res.setHeader("Content-Type", "application/json");
@@ -1649,53 +2207,94 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
1649
2207
  return;
1650
2208
  }
1651
2209
 
1652
- const rels = resolveNetworkEventBodyRelPaths(event);
1653
- const rel = side === "req" ? rels.req : rels.res;
1654
- const abs = path.join(mockDataPath, "atlas-html", rel);
1655
- const outDir = path.join(mockDataPath, "atlas-html");
1656
- // Prefer real spill buffer / disk — never materialize the truncated Metro
1657
- // hop preview (often ~512 bytes) as the "full body" JSON page.
1658
- flushNetworkBodySpillsToDir(outDir);
1659
- const fromBuffer = getNetworkBodySpillSnapshot()[rel];
1660
- if (typeof fromBuffer === "string" && fromBuffer.length > 0) {
1661
- const saved = saveAtlasBodySpill(
1662
- projectRoot,
1663
- mockDataPath,
1664
- rel,
1665
- fromBuffer,
1666
- );
1667
- if (!saved.success) {
1668
- res.statusCode = 500;
1669
- res.setHeader("Content-Type", "application/json");
1670
- res.end(
1671
- JSON.stringify({
1672
- success: false,
1673
- error: saved.error || "Failed to write full body spill",
1674
- }),
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("/"),
1675
2241
  );
2242
+ res.end(text);
1676
2243
  return;
1677
2244
  }
1678
- } else if (!fs.existsSync(abs)) {
1679
- res.statusCode = 404;
1680
- 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
+ );
1681
2268
  res.end(
1682
- JSON.stringify({
1683
- success: false,
1684
- error:
1685
- "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.",
1686
- hopId: event.id,
1687
- side,
1688
- relativePath: rel,
1689
- }),
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
+ ),
1690
2281
  );
1691
2282
  return;
1692
2283
  }
1693
- res.statusCode = 302;
1694
- res.setHeader(
1695
- "Location",
1696
- `/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
+ }),
1697
2297
  );
1698
- res.end();
1699
2298
  return;
1700
2299
  }
1701
2300
 
@@ -2084,59 +2683,53 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
2084
2683
 
2085
2684
  // Handle GET endpoint for scenario config
2086
2685
  if (url === "/mockifyer-scenario-config" && req.method === "GET") {
2686
+ const writeScenarioResponse = (scenario: string): void => {
2687
+ if (announcedScenario !== scenario) {
2688
+ logger.info(`[MetroSyncMiddleware] Active scenario: ${scenario}`);
2689
+ announcedScenario = scenario;
2690
+ }
2691
+ res.setHeader("Content-Type", "application/json");
2692
+ res.end(
2693
+ JSON.stringify({
2694
+ success: true,
2695
+ currentScenario: scenario,
2696
+ }),
2697
+ );
2698
+ };
2699
+
2087
2700
  try {
2088
2701
  // Check environment variable first (highest priority)
2089
2702
  if (process.env.MOCKIFYER_SCENARIO) {
2090
- logger.info(
2703
+ logger.debug(
2091
2704
  `[MetroSyncMiddleware] Using scenario from MOCKIFYER_SCENARIO env var: ${process.env.MOCKIFYER_SCENARIO}`,
2092
2705
  );
2093
- res.setHeader("Content-Type", "application/json");
2094
- res.end(
2095
- JSON.stringify({
2096
- success: true,
2097
- currentScenario: process.env.MOCKIFYER_SCENARIO,
2098
- }),
2099
- );
2706
+ writeScenarioResponse(process.env.MOCKIFYER_SCENARIO);
2100
2707
  return;
2101
2708
  }
2102
2709
 
2103
2710
  const configPath = path.join(mockDataPath, "scenario-config.json");
2104
2711
  const resolvedPath = path.resolve(configPath);
2105
- logger.info(
2712
+ logger.debug(
2106
2713
  `[MetroSyncMiddleware] Reading scenario config from: ${resolvedPath}`,
2107
2714
  );
2108
- logger.info(
2715
+ logger.debug(
2109
2716
  `[MetroSyncMiddleware] mockDataPath: ${mockDataPath}, projectRoot: ${projectRoot}`,
2110
2717
  );
2111
2718
 
2112
2719
  if (fs.existsSync(configPath)) {
2113
2720
  const fileContent = fs.readFileSync(configPath, "utf-8");
2114
- logger.info(`[MetroSyncMiddleware] File content: ${fileContent}`);
2721
+ logger.debug(`[MetroSyncMiddleware] File content: ${fileContent}`);
2115
2722
  const config = JSON.parse(fileContent);
2116
2723
  const scenario = config.currentScenario || DEFAULT_SCENARIO;
2117
- logger.info(
2724
+ logger.debug(
2118
2725
  `[MetroSyncMiddleware] Found scenario in config: ${scenario} (from file: ${JSON.stringify(config)})`,
2119
2726
  );
2120
-
2121
- res.setHeader("Content-Type", "application/json");
2122
- // Return format expected by ExpoFileSystemProvider: { success: true, currentScenario: ... }
2123
- res.end(
2124
- JSON.stringify({
2125
- success: true,
2126
- currentScenario: scenario,
2127
- }),
2128
- );
2727
+ writeScenarioResponse(scenario);
2129
2728
  } else {
2130
- logger.info(
2729
+ logger.debug(
2131
2730
  `[MetroSyncMiddleware] Config file not found at ${resolvedPath}, returning default scenario`,
2132
2731
  );
2133
- res.setHeader("Content-Type", "application/json");
2134
- res.end(
2135
- JSON.stringify({
2136
- success: true,
2137
- currentScenario: DEFAULT_SCENARIO,
2138
- }),
2139
- );
2732
+ writeScenarioResponse(DEFAULT_SCENARIO);
2140
2733
  }
2141
2734
  } catch (error) {
2142
2735
  logger.error(