@sgedda/mockifyer-fetch 1.8.47 → 1.8.71

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.47",
3
+ "version": "1.8.71",
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.31"
52
+ "@sgedda/mockifyer-core": "^1.10.142"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@types/node": "^20.11.24",
@@ -8,6 +8,7 @@ import {
8
8
  getOutboundMockifyerDeviceIdHeader,
9
9
  MOCKIFYER_CLIENT_ID_HEADER,
10
10
  MOCKIFYER_DEVICE_ID_HEADER,
11
+ resolveMockifyerTraceFromHeaders,
11
12
  } from '@sgedda/mockifyer-core';
12
13
  import { performDashboardProxyRequest } from '../core-proxy';
13
14
 
@@ -188,12 +189,15 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
188
189
  responseHeaders[key] = value;
189
190
  });
190
191
 
192
+ const mockifyerTrace = resolveMockifyerTraceFromHeaders(responseHeaders);
193
+
191
194
  return {
192
195
  data,
193
196
  status: response.status,
194
197
  statusText: response.statusText,
195
198
  headers: responseHeaders,
196
199
  config,
200
+ ...(mockifyerTrace ? { mockifyerTrace } : {}),
197
201
  };
198
202
  }
199
203
 
package/src/index.ts CHANGED
@@ -43,7 +43,7 @@ import {
43
43
  type PoolResponseItem,
44
44
  shouldBypassMockifyerForUrl,
45
45
  containsMockifyerSyncEndpointMarker,
46
- isMockifyerDashboardProxyApiUrl,
46
+ isMockifyerDashboardPlumbingApiUrl,
47
47
  resolveRecordingExclusions,
48
48
  shouldExcludeRecording,
49
49
  mockPassesThroughToRealApi,
@@ -58,6 +58,7 @@ import {
58
58
  resolveExplicitClientIdOnly,
59
59
  resolveProxyStrictLaneScenario,
60
60
  registerMockifyerInstance,
61
+ ensureOverrideGroupRuntimeForScenarioPath,
61
62
  logMockifyerInitSummary,
62
63
  tryGetClientIdFromLaunchArguments,
63
64
  MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
@@ -76,11 +77,19 @@ import {
76
77
  getInlineTraceEnvelopeBusinessBody,
77
78
  resolveRecordResponses,
78
79
  applyOutboundRequestCorrelation,
80
+ adoptStoredOutboundRequestId,
81
+ resolvePersistedHopIds,
79
82
  attachMockifyerRequestIdToError,
80
83
  resolveMockifyerRequestIdForError,
84
+ configureFlightRecorder,
85
+ resolveFlightRecorderConfig,
86
+ setFlightRecorderRuntimeContext,
87
+ configureAtlas,
88
+ resolveActiveMockifyerSessionId,
81
89
  type RequestCorrelationContext,
82
90
  DomainPathRulesSession,
83
91
  installNodeInboundRequestCorrelationCapture,
92
+ stripMockifyerTraceFromBody,
84
93
  } from '@sgedda/mockifyer-core';
85
94
  import { logger, setLogLevel } from '@sgedda/mockifyer-core';
86
95
  import {
@@ -122,19 +131,29 @@ class MockifyerClass {
122
131
  private readonly poolResponseCache = new Map<string, PoolResponseItem>();
123
132
  private readonly domainPathRules: DomainPathRulesSession;
124
133
 
125
- /** Best-effort dashboard network log (skipped when traffic goes through `proxy.baseUrl`). */
134
+ /** Session id for timeline hops — per-screen id from {@link setFlightRecorderRuntimeContext} when set. */
135
+ private getRuntimeSessionId(): string {
136
+ return resolveActiveMockifyerSessionId(() => {
137
+ const now = Date.now();
138
+ if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
139
+ this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
140
+ this.sessionStartTime = now;
141
+ setFlightRecorderRuntimeContext({ sessionId: this.currentSessionId });
142
+ }
143
+ return this.currentSessionId;
144
+ });
145
+ }
146
+
147
+ /** Best-effort dashboard network log. */
126
148
  private logNetworkEvent(
127
149
  partial: Parameters<typeof emitMockifyerNetworkEvent>[0]['event'] & {
128
- transport?: 'fetch';
150
+ transport?: 'fetch' | 'proxy';
129
151
  /** Raw bodies for inline-trace / network-log previews (stripped before emit). */
130
152
  requestBody?: unknown;
131
153
  responseBody?: unknown;
132
154
  },
133
155
  correlation?: RequestCorrelationContext
134
156
  ): void {
135
- // Dashboard proxy hops are recorded in performDashboardProxyRequest (shared axios/fetch path).
136
- if (this.config.proxy?.baseUrl) return;
137
-
138
157
  const scenario =
139
158
  this.config.proxy?.scenario?.trim() ||
140
159
  getCurrentScenario(this.config.mockDataPath);
@@ -142,25 +161,30 @@ class MockifyerClass {
142
161
  const { requestBody, responseBody, ...eventPartial } = partial;
143
162
  const businessResponseBody = getInlineTraceEnvelopeBusinessBody(responseBody);
144
163
 
145
- recordInlineTraceHopFromExchange({
146
- method: eventPartial.method,
147
- url: eventPartial.url,
148
- status: eventPartial.status,
149
- source: eventPartial.source,
150
- transport: eventPartial.transport ?? 'fetch',
151
- requestId: correlation?.requestId ?? eventPartial.requestId ?? null,
152
- parentRequestId: correlation?.parentRequestId ?? eventPartial.parentRequestId ?? null,
153
- durationMs: eventPartial.durationMs,
154
- clientId: this.config.clientId ?? eventPartial.clientId ?? null,
155
- errorMessage: eventPartial.errorMessage,
156
- requestBody,
157
- responseBody,
158
- });
164
+ if (!this.config.proxy?.baseUrl) {
165
+ recordInlineTraceHopFromExchange({
166
+ method: eventPartial.method,
167
+ url: eventPartial.url,
168
+ status: eventPartial.status,
169
+ source: eventPartial.source,
170
+ transport: eventPartial.transport ?? 'fetch',
171
+ requestId: correlation?.requestId ?? eventPartial.requestId ?? null,
172
+ parentRequestId: correlation?.parentRequestId ?? eventPartial.parentRequestId ?? null,
173
+ durationMs: eventPartial.durationMs,
174
+ clientId: this.config.clientId ?? eventPartial.clientId ?? null,
175
+ errorMessage: eventPartial.errorMessage,
176
+ requestBody,
177
+ responseBody,
178
+ });
179
+ }
159
180
 
160
181
  emitMockifyerNetworkEvent({
161
182
  config: this.config,
162
183
  scenario,
163
184
  clientId: this.config.clientId,
185
+ sessionId: this.getRuntimeSessionId(),
186
+ requestBody,
187
+ responseBody: businessResponseBody,
164
188
  event: {
165
189
  ...eventPartial,
166
190
  transport: eventPartial.transport ?? 'fetch',
@@ -183,6 +207,22 @@ class MockifyerClass {
183
207
  correlation.parentRequestId;
184
208
  }
185
209
 
210
+ private bindStoredHopId(
211
+ config: unknown,
212
+ mockData: { requestId?: string } | undefined,
213
+ fallback?: RequestCorrelationContext
214
+ ): RequestCorrelationContext | undefined {
215
+ const adopted = adoptStoredOutboundRequestId(
216
+ config as { headers?: unknown },
217
+ mockData?.requestId
218
+ );
219
+ if (adopted) {
220
+ this.stashRequestCorrelation(config, adopted);
221
+ return adopted;
222
+ }
223
+ return fallback;
224
+ }
225
+
186
226
  private readRequestCorrelation(config: unknown): RequestCorrelationContext | undefined {
187
227
  const requestId = (config as { __mockifyer_requestId?: string }).__mockifyer_requestId;
188
228
  if (!requestId) return undefined;
@@ -206,7 +246,7 @@ class MockifyerClass {
206
246
  * Always passes `loadPoolResponse` — including React Native where Node `fs`/`path` are
207
247
  * missing or Metro-stubbed — so `$pool` refs resolve via disk and/or {@link poolResponseCache}.
208
248
  */
209
- private prepareStoredResponseBody(mockData: MockData): unknown {
249
+ private prepareStoredResponseBody(mockData: MockData, filename?: string, scenarioPath?: string): unknown {
210
250
  const joinPath =
211
251
  path && typeof path.join === 'function' ? path.join.bind(path) : null;
212
252
  return prepareMockResponseBody(mockData, getCurrentDate, {
@@ -216,6 +256,8 @@ class MockifyerClass {
216
256
  joinPath,
217
257
  cache: this.poolResponseCache,
218
258
  }),
259
+ filename,
260
+ scenarioPath,
219
261
  });
220
262
  }
221
263
 
@@ -371,6 +413,15 @@ class MockifyerClass {
371
413
  }
372
414
  this.activationMode = resolveActivationMode(this.config);
373
415
  this.domainPathRules = new DomainPathRulesSession({ config: this.config });
416
+ configureFlightRecorder(resolveFlightRecorderConfig(this.config));
417
+ configureAtlas(this.config, {
418
+ scenario: getCurrentScenario(this.config.mockDataPath, this.config.clientId),
419
+ clientId: this.config.clientId ?? null,
420
+ });
421
+ setFlightRecorderRuntimeContext({
422
+ clientId: this.config.clientId,
423
+ scenario: getCurrentScenario(this.config.mockDataPath, this.config.clientId),
424
+ });
374
425
 
375
426
  if (this.config.proxy?.baseUrl && this.config.proxy.mirrorRecordedMocksToClient === undefined) {
376
427
  const raw =
@@ -543,6 +594,7 @@ class MockifyerClass {
543
594
 
544
595
  const currentScenario = getCurrentScenario(resolvedMockDataPath, this.config.clientId);
545
596
  const scenarioPath = getScenarioFolderPath(resolvedMockDataPath, currentScenario);
597
+ ensureOverrideGroupRuntimeForScenarioPath(scenarioPath, { clientId: this.config.clientId });
546
598
 
547
599
  if (!fs.existsSync(scenarioPath)) {
548
600
  logger.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
@@ -569,7 +621,13 @@ class MockifyerClass {
569
621
  const mockKey = this.generateRequestKey(mockData.request);
570
622
 
571
623
  if (mockKey === requestKey) {
572
- if (mockShouldBeIncludedInRequestMatch(mockData, { includePassthroughMocks })) {
624
+ if (
625
+ mockShouldBeIncludedInRequestMatch(mockData, {
626
+ includePassthroughMocks,
627
+ filename: file,
628
+ scenarioPath,
629
+ })
630
+ ) {
573
631
  exactMatch = { mockData, filename: file, filePath };
574
632
  break;
575
633
  }
@@ -649,7 +707,13 @@ class MockifyerClass {
649
707
  }
650
708
  }
651
709
 
652
- if (!mockPassesThroughToRealApi(mockData)) {
710
+ if (
711
+ mockShouldBeIncludedInRequestMatch(mockData, {
712
+ includePassthroughMocks,
713
+ filename: file,
714
+ scenarioPath,
715
+ })
716
+ ) {
653
717
  similarMatch = { mockData, filename: file, filePath };
654
718
  }
655
719
  }
@@ -712,7 +776,7 @@ class MockifyerClass {
712
776
  return config;
713
777
  }
714
778
 
715
- const correlation = applyOutboundRequestCorrelation(config);
779
+ let correlation = applyOutboundRequestCorrelation(config);
716
780
  this.stashRequestCorrelation(config, correlation);
717
781
 
718
782
  // Normalize empty params: treat {} the same as undefined for consistent matching
@@ -760,12 +824,22 @@ class MockifyerClass {
760
824
 
761
825
  if (cachedMock) {
762
826
  const { mockData, filename, filePath } = cachedMock;
827
+ correlation = this.bindStoredHopId(config, mockData, correlation) ?? correlation;
763
828
  if (mockShouldServeStoredBody(mockData)) {
764
829
  logger.info(
765
830
  `[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
766
831
  (filePath ? ` (${filePath})` : '')
767
832
  );
768
- const mockResponseBody = this.prepareStoredResponseBody(mockData);
833
+ const hitScenarioPath = path
834
+ ? getScenarioFolderPath(
835
+ path.resolve(this.config.mockDataPath),
836
+ getCurrentScenario(path.resolve(this.config.mockDataPath), this.config.clientId)
837
+ )
838
+ : undefined;
839
+ if (hitScenarioPath) {
840
+ ensureOverrideGroupRuntimeForScenarioPath(hitScenarioPath, { clientId: this.config.clientId });
841
+ }
842
+ const mockResponseBody = this.prepareStoredResponseBody(mockData, filename, hitScenarioPath);
769
843
  this.logNetworkEvent(
770
844
  {
771
845
  method: (request.method || 'GET').toUpperCase(),
@@ -933,6 +1007,39 @@ class MockifyerClass {
933
1007
  const isMocked = response.headers && (response.headers as any)['x-mockifyer'] === 'true';
934
1008
  const isLimitReached = response.headers && (response.headers as any)['x-mockifyer-limit-reached'] === 'true';
935
1009
  if (isMocked || isLimitReached) {
1010
+ // Local mock hits are logged in the request interceptor; proxy mock hits must
1011
+ // be recorded here before early return (otherwise flight recorder stays empty).
1012
+ const shouldLogMockOrLimit =
1013
+ isLimitReached || (isMocked && this.usesDashboardProxy());
1014
+ if (shouldLogMockOrLimit) {
1015
+ const reqUrl = response.config?.url || url;
1016
+ const reqMethod = (response.config?.method || 'GET').toUpperCase();
1017
+ const startTime = (response.config as any).__mockifyer_startTime;
1018
+ const durationMs = startTime ? Date.now() - startTime : undefined;
1019
+ this.logNetworkEvent(
1020
+ {
1021
+ method: reqMethod,
1022
+ url: reqUrl,
1023
+ source: isLimitReached ? 'error' : 'mock-hit',
1024
+ status: response.status,
1025
+ durationMs,
1026
+ transport: this.usesDashboardProxy() ? 'proxy' : 'fetch',
1027
+ requestBody: response.config?.data,
1028
+ responseBody: response.data,
1029
+ ...(isLimitReached
1030
+ ? {
1031
+ errorMessage:
1032
+ typeof response.data === 'object' &&
1033
+ response.data !== null &&
1034
+ 'message' in response.data
1035
+ ? String((response.data as { message?: unknown }).message)
1036
+ : 'Request limit reached',
1037
+ }
1038
+ : {}),
1039
+ },
1040
+ this.readRequestCorrelation(response.config)
1041
+ );
1042
+ }
936
1043
  return response;
937
1044
  }
938
1045
 
@@ -964,18 +1071,33 @@ class MockifyerClass {
964
1071
 
965
1072
  const capturedResponse: StoredResponse = {
966
1073
  status: response.status,
967
- data: response.data,
1074
+ data: stripMockifyerTraceFromBody(response.data),
968
1075
  headers: (response.headers as Record<string, string>) || {},
969
1076
  };
970
1077
 
971
1078
  if (resolveShouldPersistLiveCapture(matchedMock.mockData, this.config)) {
972
- await this.persistMatchedMockAfterLiveCapture(matchedMock, capturedResponse, durationMs);
1079
+ await this.persistMatchedMockAfterLiveCapture(
1080
+ matchedMock,
1081
+ capturedResponse,
1082
+ durationMs,
1083
+ this.readRequestCorrelation(response.config)
1084
+ );
973
1085
  }
974
1086
 
1087
+ const liveScenarioPath = path
1088
+ ? getScenarioFolderPath(
1089
+ path.resolve(this.config.mockDataPath),
1090
+ getCurrentScenario(path.resolve(this.config.mockDataPath), this.config.clientId)
1091
+ )
1092
+ : undefined;
1093
+ if (liveScenarioPath) {
1094
+ ensureOverrideGroupRuntimeForScenarioPath(liveScenarioPath, { clientId: this.config.clientId });
1095
+ }
975
1096
  const clientResponse = buildClientResponseFromLiveCapture(
976
1097
  matchedMock.mockData,
977
1098
  capturedResponse,
978
- getCurrentDate
1099
+ getCurrentDate,
1100
+ { filename: matchedMock.filename, scenarioPath: liveScenarioPath }
979
1101
  );
980
1102
  response.data = clientResponse.data;
981
1103
  response.status = clientResponse.status;
@@ -1236,6 +1358,10 @@ class MockifyerClass {
1236
1358
  const duration = startTime ? Date.now() - startTime : undefined;
1237
1359
 
1238
1360
  const correlation = this.readRequestCorrelation(response.config);
1361
+ const hopIds = resolvePersistedHopIds(
1362
+ saveDecision.action === 'overwrite' ? existingMock?.mockData : undefined,
1363
+ correlation
1364
+ );
1239
1365
 
1240
1366
  const mockData: MockData = {
1241
1367
  request: {
@@ -1247,7 +1373,7 @@ class MockifyerClass {
1247
1373
  },
1248
1374
  response: {
1249
1375
  status: response.status,
1250
- data: response.data,
1376
+ data: stripMockifyerTraceFromBody(response.data),
1251
1377
  headers: response.headers || {},
1252
1378
  },
1253
1379
  timestamp: new Date().toISOString(),
@@ -1256,8 +1382,8 @@ class MockifyerClass {
1256
1382
  saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
1257
1383
  ? existingMock.mockData.sessionId
1258
1384
  : this.currentSessionId,
1259
- requestId: correlation?.requestId,
1260
- parentRequestId: correlation?.parentRequestId,
1385
+ requestId: hopIds.requestId,
1386
+ parentRequestId: hopIds.parentRequestId,
1261
1387
  ...(newRecordingUsesAlwaysUseRealApi() ? { alwaysUseRealApi: true as const } : {}),
1262
1388
  };
1263
1389
 
@@ -1318,9 +1444,19 @@ class MockifyerClass {
1318
1444
  private async persistMatchedMockAfterLiveCapture(
1319
1445
  cachedMock: CachedMockData,
1320
1446
  capturedResponse: StoredResponse,
1321
- durationMs?: number
1447
+ durationMs?: number,
1448
+ liveCorrelation?: RequestCorrelationContext
1322
1449
  ): Promise<void> {
1323
1450
  const updated = buildMockDataAfterLiveCapture(cachedMock.mockData, capturedResponse, durationMs);
1451
+ const hopIds = resolvePersistedHopIds(cachedMock.mockData, liveCorrelation);
1452
+ if (hopIds.requestId) {
1453
+ updated.requestId = hopIds.requestId;
1454
+ }
1455
+ if (hopIds.parentRequestId) {
1456
+ updated.parentRequestId = hopIds.parentRequestId;
1457
+ } else {
1458
+ delete updated.parentRequestId;
1459
+ }
1324
1460
 
1325
1461
  if (this.databaseProvider) {
1326
1462
  await this.databaseProvider.save(updated);
@@ -1655,11 +1791,11 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
1655
1791
  const headers = init?.headers || {};
1656
1792
  const body = init?.body;
1657
1793
 
1658
- // Skip Mockifyer sync endpoints, dashboard `/api/proxy` plumbing, and Resend API
1794
+ // Skip Mockifyer sync endpoints, dashboard plumbing, and Resend API
1659
1795
  if (
1660
1796
  containsMockifyerSyncEndpointMarker(url) ||
1661
1797
  url.includes('api.resend.com') ||
1662
- isMockifyerDashboardProxyApiUrl(url)
1798
+ isMockifyerDashboardPlumbingApiUrl(url)
1663
1799
  ) {
1664
1800
  return await originalFetchForPatched(input, init);
1665
1801
  }
@@ -1696,7 +1832,7 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
1696
1832
  headersObj[key] = value;
1697
1833
  });
1698
1834
  } else {
1699
- headersObj = headers as Record<string, string>;
1835
+ headersObj = { ...(headers as Record<string, string>) };
1700
1836
  }
1701
1837
 
1702
1838
  try {