@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sgedda/mockifyer-fetch",
3
- "version": "1.8.87",
3
+ "version": "1.8.92",
4
4
  "description": "Mockifyer for Fetch - API mocking and logging utility for storing and replaying API responses",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -49,7 +49,7 @@
49
49
  },
50
50
  "license": "MIT",
51
51
  "dependencies": {
52
- "@sgedda/mockifyer-core": "^1.10.162"
52
+ "@sgedda/mockifyer-core": "^1.10.171"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@types/node": "^20.11.24",
package/src/index.ts CHANGED
@@ -77,6 +77,7 @@ import {
77
77
  unwrapAndMergeInlineTraceEnvelope,
78
78
  unwrapInlineTraceEnvelopeEmittingNetworkEvents,
79
79
  resolveNetworkLogIncludeTraceOptions,
80
+ resolveNetworkLogIncludeTraceOptionsAsync,
80
81
  getInlineTraceEnvelopeBusinessBody,
81
82
  resolveRecordResponses,
82
83
  applyOutboundRequestCorrelation,
@@ -97,6 +98,8 @@ import {
97
98
  resolveRuntimeEnabledStorage,
98
99
  savePersistedRuntimeEnabled,
99
100
  type MockifyerRuntimeEnabledStorage,
101
+ outboundHeadersToRecord,
102
+ appendParamsToUrl,
100
103
  } from '@sgedda/mockifyer-core';
101
104
  import { logger, setLogLevel } from '@sgedda/mockifyer-core';
102
105
  import {
@@ -178,13 +181,26 @@ class MockifyerClass {
178
181
  });
179
182
  }
180
183
 
181
- private applyOutboundCorrelation(config: unknown): RequestCorrelationContext {
184
+ private async applyOutboundCorrelation(config: unknown): Promise<RequestCorrelationContext> {
182
185
  return applyOutboundRequestCorrelation(
183
186
  config as { headers?: unknown; url?: unknown; method?: unknown },
184
- resolveNetworkLogIncludeTraceOptions(this.config)
187
+ await resolveNetworkLogIncludeTraceOptionsAsync(this.config)
185
188
  );
186
189
  }
187
190
 
191
+ /**
192
+ * Full outbound URL including `params` — hop logs / Atlas curl / include-trace
193
+ * must not drop the query string (fetch splits search into `config.params`).
194
+ */
195
+ private resolveLoggedRequestUrl(
196
+ config?: { url?: string; params?: Record<string, unknown> } | null,
197
+ fallbackUrl?: string,
198
+ ): string {
199
+ const raw = (fallbackUrl || config?.url || '').trim();
200
+ if (!raw) return '';
201
+ return appendParamsToUrl(raw, config?.params);
202
+ }
203
+
188
204
  /** Best-effort dashboard network log. */
189
205
  private logNetworkEvent(
190
206
  partial: Parameters<typeof emitMockifyerNetworkEvent>[0]['event'] & {
@@ -193,7 +209,9 @@ class MockifyerClass {
193
209
  requestBody?: unknown;
194
210
  responseBody?: unknown;
195
211
  },
196
- correlation?: RequestCorrelationContext
212
+ correlation?: RequestCorrelationContext,
213
+ /** Final outbound header bag (after auth interceptors). */
214
+ requestHeadersSource?: unknown
197
215
  ): void {
198
216
  const scenario =
199
217
  this.config.proxy?.scenario?.trim() ||
@@ -201,6 +219,8 @@ class MockifyerClass {
201
219
 
202
220
  const { requestBody, responseBody, ...eventPartial } = partial;
203
221
  const businessResponseBody = getInlineTraceEnvelopeBusinessBody(responseBody);
222
+ const requestHeaders =
223
+ eventPartial.requestHeaders ?? outboundHeadersToRecord(requestHeadersSource);
204
224
 
205
225
  if (!this.config.proxy?.baseUrl) {
206
226
  recordInlineTraceHopFromExchange({
@@ -231,6 +251,7 @@ class MockifyerClass {
231
251
  transport: eventPartial.transport ?? 'fetch',
232
252
  requestId: correlation?.requestId ?? eventPartial.requestId,
233
253
  parentRequestId: correlation?.parentRequestId ?? eventPartial.parentRequestId,
254
+ requestHeaders,
234
255
  requestBodyPreview: eventPartial.requestBodyPreview,
235
256
  responseBodyPreview: eventPartial.responseBodyPreview,
236
257
  },
@@ -841,7 +862,7 @@ class MockifyerClass {
841
862
  useProxyLane: { proxyBaseUrl: this.config.proxy?.baseUrl, resolvedClientId: this.config.clientId },
842
863
  })
843
864
  ) {
844
- this.applyOutboundCorrelation(config);
865
+ await this.applyOutboundCorrelation(config);
845
866
  (config as any).__mockifyer_bypass = true;
846
867
  return config;
847
868
  }
@@ -854,7 +875,7 @@ class MockifyerClass {
854
875
  return config;
855
876
  }
856
877
 
857
- let correlation = this.applyOutboundCorrelation(config);
878
+ let correlation = await this.applyOutboundCorrelation(config);
858
879
  this.stashRequestCorrelation(config, correlation);
859
880
 
860
881
  // Normalize empty params: treat {} the same as undefined for consistent matching
@@ -921,14 +942,15 @@ class MockifyerClass {
921
942
  this.logNetworkEvent(
922
943
  {
923
944
  method: (request.method || 'GET').toUpperCase(),
924
- url: request.url,
945
+ url: this.resolveLoggedRequestUrl(config, request.url),
925
946
  source: 'mock-hit',
926
947
  status: mockData.response.status,
927
948
  requestHash: networkEventHashFromRequestKey(requestKey),
928
949
  requestBody: request.data,
929
950
  responseBody: mockResponseBody,
930
951
  },
931
- correlation
952
+ correlation,
953
+ request.headers ?? config.headers
932
954
  );
933
955
  const responseHeaders = {
934
956
  ...mockData.response.headers,
@@ -1090,7 +1112,7 @@ class MockifyerClass {
1090
1112
  const shouldLogMockOrLimit =
1091
1113
  isLimitReached || (isMocked && this.usesDashboardProxy());
1092
1114
  if (shouldLogMockOrLimit) {
1093
- const reqUrl = response.config?.url || url;
1115
+ const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
1094
1116
  const reqMethod = (response.config?.method || 'GET').toUpperCase();
1095
1117
  const startTime = (response.config as any).__mockifyer_startTime;
1096
1118
  const durationMs = startTime ? Date.now() - startTime : undefined;
@@ -1115,9 +1137,13 @@ class MockifyerClass {
1115
1137
  }
1116
1138
  : {}),
1117
1139
  },
1118
- this.readRequestCorrelation(response.config)
1140
+ this.readRequestCorrelation(response.config),
1141
+ response.config?.headers
1119
1142
  );
1120
1143
  }
1144
+ // Mock hits return before the upstream path. Still emit nested service
1145
+ // hops and strip mockifyerTrace so the caller sees the business body.
1146
+ this.unwrapResponseInlineTrace(response);
1121
1147
  return response;
1122
1148
  }
1123
1149
 
@@ -1130,9 +1156,9 @@ class MockifyerClass {
1130
1156
  const startTime = (response.config as any).__mockifyer_startTime;
1131
1157
  const durationMs = startTime ? Date.now() - startTime : undefined;
1132
1158
 
1133
- const reqUrl = response.config?.url || url;
1159
+ const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
1134
1160
  const reqMethod = (response.config?.method || 'GET').toUpperCase();
1135
- // Parent hop first, then unwrap nested mockifyerTrace from downstream services.
1161
+ // Parent hop first, then unwrap nested service hops from downstream services.
1136
1162
  this.logNetworkEvent(
1137
1163
  {
1138
1164
  method: reqMethod,
@@ -1143,7 +1169,8 @@ class MockifyerClass {
1143
1169
  requestBody: response.config?.data,
1144
1170
  responseBody: response.data,
1145
1171
  },
1146
- this.readRequestCorrelation(response.config)
1172
+ this.readRequestCorrelation(response.config),
1173
+ response.config?.headers
1147
1174
  );
1148
1175
  this.unwrapResponseInlineTrace(response);
1149
1176
 
@@ -1184,7 +1211,7 @@ class MockifyerClass {
1184
1211
  return response;
1185
1212
  }
1186
1213
 
1187
- const reqUrl = response.config?.url || url;
1214
+ const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
1188
1215
  const reqMethod = (response.config?.method || 'GET').toUpperCase();
1189
1216
  this.logNetworkEvent(
1190
1217
  {
@@ -1199,7 +1226,8 @@ class MockifyerClass {
1199
1226
  requestBody: response.config?.data,
1200
1227
  responseBody: response.data,
1201
1228
  },
1202
- this.readRequestCorrelation(response.config)
1229
+ this.readRequestCorrelation(response.config),
1230
+ response.config?.headers
1203
1231
  );
1204
1232
  this.unwrapResponseInlineTrace(response);
1205
1233
 
@@ -1216,7 +1244,7 @@ class MockifyerClass {
1216
1244
  if (requestKey) {
1217
1245
  this.processingRequests.delete(requestKey);
1218
1246
  }
1219
- const reqUrl = error.config?.url || '';
1247
+ const reqUrl = this.resolveLoggedRequestUrl(error.config);
1220
1248
  if (reqUrl) {
1221
1249
  this.logNetworkEvent(
1222
1250
  {
@@ -1228,7 +1256,8 @@ class MockifyerClass {
1228
1256
  requestBody: error.config?.data,
1229
1257
  responseBody: error.response?.data,
1230
1258
  },
1231
- this.readRequestCorrelation(error.config)
1259
+ this.readRequestCorrelation(error.config),
1260
+ error.config?.headers
1232
1261
  );
1233
1262
  }
1234
1263
  this.throwWithMockifyerRequestId(error);
@@ -1,17 +1,23 @@
1
1
  /**
2
2
  * Metro terminal keys for Mockifyer:
3
- * - `t` (default): start/stop Atlas capture (stop generates HTML)
3
+ * - `t` (default): start/stop Atlas capture (start opens the live stream page;
4
+ * stop ends capture — generate HTML from the live page “Render docs” button)
4
5
  * - `m` (default): open the Mockifyer dashboard in the browser
5
6
  *
6
- * Opening `mockifyer-atlas` (SSE `/mockifyer-network-events/stream`) auto-starts
7
- * capture when idle — then press `t` once to stop & generate.
7
+ * Opening `mockifyer-atlas` (SSE `/mockifyer-network-events/stream`) or the live
8
+ * page auto-starts capture when idle — then press `t` once to stop, or use
9
+ * Render docs on the live page without stopping.
8
10
  *
9
11
  * `a` is reserved by Metro for Android (`i` iOS, `r` reload, `d` Dev Menu, `j` DevTools).
10
12
  * Disable Atlas with `atlasKey: false`, dashboard with `dashboardKey: false`.
11
13
  */
12
14
  import * as readline from "readline";
13
15
  import { spawn } from "child_process";
14
- import { logger } from "@sgedda/mockifyer-core";
16
+ import {
17
+ ATLAS_LIVE_STREAM_PATH,
18
+ logger,
19
+ resolveMetroNetworkStreamPort,
20
+ } from "@sgedda/mockifyer-core";
15
21
 
16
22
  /**
17
23
  * Keys already used by @react-native/community-cli-plugin (avoid stealing).
@@ -55,9 +61,9 @@ export interface AttachMetroAtlasKeyHandlerOptions {
55
61
  * Mount prefix from `MOCKIFYER_DASHBOARD_BASE` is appended when set.
56
62
  */
57
63
  dashboardUrl?: string;
58
- /** Called on session start (clear hop buffer, etc.). Required when Atlas key is enabled. */
59
- onSessionStart?: () => void;
60
- /** Called on session stop — generate Atlas HTML. Required when Atlas key is enabled. */
64
+ /** Called on session start. `reason` is `key` (Metro `t`) or `stream` (live page connected). */
65
+ onSessionStart?: (reason: MetroAtlasSessionStartReason) => void;
66
+ /** Called on session stop — end capture (HTML is rendered from the live page). */
61
67
  onSessionStop?: () => void | Promise<void>;
62
68
  /** Override stdin (tests). */
63
69
  stdin?: NodeJS.ReadStream;
@@ -74,6 +80,8 @@ export interface AttachedMetroAtlasKeyHandler {
74
80
  dashboardKey: string | null;
75
81
  /** Resolved dashboard browse URL. */
76
82
  dashboardUrl: string | null;
83
+ /** Live Atlas stream page opened when capture starts via the Atlas key. */
84
+ liveUrl: string | null;
77
85
  /** Detach listener and clear module attach flag. */
78
86
  detach: () => void;
79
87
  }
@@ -82,7 +90,8 @@ interface SessionCallbacks {
82
90
  key: string | null;
83
91
  dashboardKey: string | null;
84
92
  dashboardUrl: string | null;
85
- onSessionStart?: () => void;
93
+ liveUrl: string | null;
94
+ onSessionStart?: (reason: MetroAtlasSessionStartReason) => void;
86
95
  onSessionStop?: () => void | Promise<void>;
87
96
  openUrl: (url: string) => void;
88
97
  }
@@ -155,6 +164,21 @@ export function resolveMetroDashboardUrl(explicit?: string): string {
155
164
  return `${base}${mount.startsWith("/") ? mount : `/${mount}`}`;
156
165
  }
157
166
 
167
+ /**
168
+ * Browser URL for the Metro live Atlas hop stream page.
169
+ * Uses `MOCKIFYER_METRO_URL` when set, otherwise `http://localhost:<METRO_PORT|8081>`.
170
+ */
171
+ export function resolveMetroAtlasLiveUrl(explicitBase?: string): string {
172
+ const fromExplicit = typeof explicitBase === "string" ? explicitBase.trim() : "";
173
+ const fromEnv =
174
+ typeof process !== "undefined" ? process.env.MOCKIFYER_METRO_URL?.trim() : "";
175
+ const base = (fromExplicit || fromEnv || `http://localhost:${resolveMetroNetworkStreamPort()}`).replace(
176
+ /\/+$/,
177
+ "",
178
+ );
179
+ return `${base}${ATLAS_LIVE_STREAM_PATH}`;
180
+ }
181
+
158
182
  /**
159
183
  * Open a URL with the OS default handler (browser / file).
160
184
  */
@@ -226,7 +250,7 @@ export function startMetroAtlasSession(
226
250
  sessionPhase = "capturing";
227
251
  sessionStartedAt = Date.now();
228
252
  try {
229
- onSessionStart();
253
+ onSessionStart(reason);
230
254
  } catch (err) {
231
255
  sessionPhase = "idle";
232
256
  sessionStartedAt = null;
@@ -237,19 +261,37 @@ export function startMetroAtlasSession(
237
261
 
238
262
  if (reason === "stream") {
239
263
  console.log(
240
- `[Mockifyer] Atlas capture started (stream connected) — press ${key} to stop & generate HTML.`,
264
+ `[Mockifyer] Atlas capture started (stream connected) — press ${key} to stop, or Render docs on the live page.`,
241
265
  );
242
266
  } else {
243
267
  console.log(
244
- `[Mockifyer] Atlas capture started — press ${key} again to stop & generate HTML.`,
268
+ `[Mockifyer] Atlas capture started — press ${key} again to stop, or Render docs on the live page.`,
245
269
  );
270
+ openMetroAtlasLivePage();
271
+ }
272
+ return true;
273
+ }
274
+
275
+ /** Open the live hop stream page in the browser (Atlas key start). */
276
+ export function openMetroAtlasLivePage(): boolean {
277
+ const url = sessionCallbacks?.liveUrl;
278
+ if (!url || !sessionCallbacks?.openUrl) {
279
+ return false;
280
+ }
281
+ console.log(`[Mockifyer] Opening Atlas live stream → ${url}`);
282
+ try {
283
+ sessionCallbacks.openUrl(url);
284
+ } catch (err) {
285
+ const message = err instanceof Error ? err.message : String(err);
286
+ console.error(`[Mockifyer] Could not open Atlas live stream: ${message}`);
287
+ return false;
246
288
  }
247
289
  return true;
248
290
  }
249
291
 
250
292
  /**
251
- * Stop capture and generate Atlas HTML when capturing.
252
- * @returns true if stop/render was kicked off
293
+ * Stop capture when capturing (does not write Atlas HTML — use live page Render docs).
294
+ * @returns true if stop was kicked off
253
295
  */
254
296
  export function stopMetroAtlasSession(): boolean {
255
297
  if (!sessionCallbacks?.onSessionStop) return false;
@@ -259,14 +301,12 @@ export function stopMetroAtlasSession(): boolean {
259
301
  const startedAt = sessionStartedAt ?? Date.now();
260
302
  const duration = formatSessionDuration(startedAt);
261
303
  sessionPhase = "rendering";
262
- console.log(
263
- `[Mockifyer] Atlas capture stopped (${duration}) — generating HTML…`,
264
- );
304
+ console.log(`[Mockifyer] Atlas capture stopped (${duration}).`);
265
305
  Promise.resolve()
266
306
  .then(() => onSessionStop())
267
307
  .catch((err: unknown) => {
268
308
  const message = err instanceof Error ? err.message : String(err);
269
- console.error(`[Mockifyer] Atlas render failed: ${message}`);
309
+ console.error(`[Mockifyer] Atlas session stop failed: ${message}`);
270
310
  })
271
311
  .finally(() => {
272
312
  sessionPhase = "idle";
@@ -369,6 +409,7 @@ export function attachMetroAtlasKeyHandler(
369
409
  key: null,
370
410
  dashboardKey: null,
371
411
  dashboardUrl: null,
412
+ liveUrl: null,
372
413
  detach: () => undefined,
373
414
  };
374
415
  }
@@ -389,10 +430,13 @@ export function attachMetroAtlasKeyHandler(
389
430
  const effectiveDashboardKey =
390
431
  atlasKey != null && dashboardKey === atlasKey ? null : dashboardKey;
391
432
 
433
+ const liveUrl = atlasKey != null ? resolveMetroAtlasLiveUrl() : null;
434
+
392
435
  sessionCallbacks = {
393
436
  key: atlasKey,
394
437
  dashboardKey: effectiveDashboardKey,
395
438
  dashboardUrl: effectiveDashboardKey != null ? dashboardUrl : null,
439
+ liveUrl,
396
440
  onSessionStart: options.onSessionStart,
397
441
  onSessionStop: options.onSessionStop,
398
442
  openUrl: options.openUrl ?? openMetroBrowseUrl,
@@ -403,6 +447,7 @@ export function attachMetroAtlasKeyHandler(
403
447
  key: atlasKey,
404
448
  dashboardKey: effectiveDashboardKey,
405
449
  dashboardUrl: sessionCallbacks.dashboardUrl,
450
+ liveUrl,
406
451
  detach: detachMetroAtlasKeyHandler,
407
452
  };
408
453
  }
@@ -434,7 +479,7 @@ export function attachMetroAtlasKeyHandler(
434
479
  if (!atlasKey || !matchesAtlasKey(str, keyObj, atlasKey)) return;
435
480
 
436
481
  if (sessionPhase === "rendering") {
437
- console.log("[Mockifyer] Atlas render already in progress…");
482
+ console.log("[Mockifyer] Atlas stop already in progress…");
438
483
  return;
439
484
  }
440
485
 
@@ -481,7 +526,7 @@ export function attachMetroAtlasKeyHandler(
481
526
  const parts: string[] = [];
482
527
  if (atlasKey) {
483
528
  parts.push(
484
- `Press ${atlasKey} to start/stop Atlas capture (stop generates HTML; stream auto-starts)`,
529
+ `Press ${atlasKey} to start/stop Atlas capture (start opens live stream; Render docs on the page writes HTML)`,
485
530
  );
486
531
  }
487
532
  if (effectiveDashboardKey && dashboardUrl) {
@@ -510,6 +555,7 @@ export function attachMetroAtlasKeyHandler(
510
555
  key: atlasKey,
511
556
  dashboardKey: effectiveDashboardKey,
512
557
  dashboardUrl: sessionCallbacks.dashboardUrl,
558
+ liveUrl,
513
559
  detach: detachMetroAtlasKeyHandler,
514
560
  };
515
561
  }
@@ -171,7 +171,7 @@ export interface ConfigureMetroOptions {
171
171
  * syncMiddleware: {
172
172
  * projectRoot: __dirname,
173
173
  * mockDataPath: './mock-data',
174
- * // atlasKey: 't' (default) — Metro terminal: start/stop Atlas capture (stop → HTML). `a` is Android.
174
+ * // atlasKey: 't' (default) — Metro terminal: start/stop Atlas (start opens live stream; stop → HTML). `a` is Android.
175
175
  * // dashboardKey: 'm' (default) — open dashboard in browser
176
176
  * // dashboardUrl: 'http://localhost:3002' — or MOCKIFYER_DASHBOARD_URL
177
177
  * },