@sgedda/mockifyer-fetch 1.8.47 → 1.8.72

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