@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.
@@ -133,12 +133,14 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
133
133
  response.headers.forEach((value, key) => {
134
134
  responseHeaders[key] = value;
135
135
  });
136
+ const mockifyerTrace = (0, mockifyer_core_1.resolveMockifyerTraceFromHeaders)(responseHeaders);
136
137
  return {
137
138
  data,
138
139
  status: response.status,
139
140
  statusText: response.statusText,
140
141
  headers: responseHeaders,
141
142
  config,
143
+ ...(mockifyerTrace ? { mockifyerTrace } : {}),
142
144
  };
143
145
  }
144
146
  getDefaultHeaders() {
package/dist/index.js CHANGED
@@ -40,33 +40,47 @@ const proxy_upstream_tls_insecure_1 = require("@sgedda/mockifyer-core/utils/prox
40
40
  const fetch_client_1 = require("./clients/fetch-client");
41
41
  const fetch_response_body_1 = require("./utils/fetch-response-body");
42
42
  class MockifyerClass {
43
- /** Best-effort dashboard network log (skipped when traffic goes through `proxy.baseUrl`). */
43
+ /** Session id for timeline hops — per-screen id from {@link setFlightRecorderRuntimeContext} when set. */
44
+ getRuntimeSessionId() {
45
+ return (0, mockifyer_core_1.resolveActiveMockifyerSessionId)(() => {
46
+ const now = Date.now();
47
+ if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
48
+ this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
49
+ this.sessionStartTime = now;
50
+ (0, mockifyer_core_1.setFlightRecorderRuntimeContext)({ sessionId: this.currentSessionId });
51
+ }
52
+ return this.currentSessionId;
53
+ });
54
+ }
55
+ /** Best-effort dashboard network log. */
44
56
  logNetworkEvent(partial, correlation) {
45
- // Dashboard proxy hops are recorded in performDashboardProxyRequest (shared axios/fetch path).
46
- if (this.config.proxy?.baseUrl)
47
- return;
48
57
  const scenario = this.config.proxy?.scenario?.trim() ||
49
58
  (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath);
50
59
  const { requestBody, responseBody, ...eventPartial } = partial;
51
60
  const businessResponseBody = (0, mockifyer_core_1.getInlineTraceEnvelopeBusinessBody)(responseBody);
52
- (0, mockifyer_core_1.recordInlineTraceHopFromExchange)({
53
- method: eventPartial.method,
54
- url: eventPartial.url,
55
- status: eventPartial.status,
56
- source: eventPartial.source,
57
- transport: eventPartial.transport ?? 'fetch',
58
- requestId: correlation?.requestId ?? eventPartial.requestId ?? null,
59
- parentRequestId: correlation?.parentRequestId ?? eventPartial.parentRequestId ?? null,
60
- durationMs: eventPartial.durationMs,
61
- clientId: this.config.clientId ?? eventPartial.clientId ?? null,
62
- errorMessage: eventPartial.errorMessage,
63
- requestBody,
64
- responseBody,
65
- });
61
+ if (!this.config.proxy?.baseUrl) {
62
+ (0, mockifyer_core_1.recordInlineTraceHopFromExchange)({
63
+ method: eventPartial.method,
64
+ url: eventPartial.url,
65
+ status: eventPartial.status,
66
+ source: eventPartial.source,
67
+ transport: eventPartial.transport ?? 'fetch',
68
+ requestId: correlation?.requestId ?? eventPartial.requestId ?? null,
69
+ parentRequestId: correlation?.parentRequestId ?? eventPartial.parentRequestId ?? null,
70
+ durationMs: eventPartial.durationMs,
71
+ clientId: this.config.clientId ?? eventPartial.clientId ?? null,
72
+ errorMessage: eventPartial.errorMessage,
73
+ requestBody,
74
+ responseBody,
75
+ });
76
+ }
66
77
  (0, mockifyer_core_1.emitMockifyerNetworkEvent)({
67
78
  config: this.config,
68
79
  scenario,
69
80
  clientId: this.config.clientId,
81
+ sessionId: this.getRuntimeSessionId(),
82
+ requestBody,
83
+ responseBody: businessResponseBody,
70
84
  event: {
71
85
  ...eventPartial,
72
86
  transport: eventPartial.transport ?? 'fetch',
@@ -85,6 +99,14 @@ class MockifyerClass {
85
99
  config.__mockifyer_parentRequestId =
86
100
  correlation.parentRequestId;
87
101
  }
102
+ bindStoredHopId(config, mockData, fallback) {
103
+ const adopted = (0, mockifyer_core_1.adoptStoredOutboundRequestId)(config, mockData?.requestId);
104
+ if (adopted) {
105
+ this.stashRequestCorrelation(config, adopted);
106
+ return adopted;
107
+ }
108
+ return fallback;
109
+ }
88
110
  readRequestCorrelation(config) {
89
111
  const requestId = config.__mockifyer_requestId;
90
112
  if (!requestId)
@@ -107,7 +129,7 @@ class MockifyerClass {
107
129
  * Always passes `loadPoolResponse` — including React Native where Node `fs`/`path` are
108
130
  * missing or Metro-stubbed — so `$pool` refs resolve via disk and/or {@link poolResponseCache}.
109
131
  */
110
- prepareStoredResponseBody(mockData) {
132
+ prepareStoredResponseBody(mockData, filename, scenarioPath) {
111
133
  const joinPath = path && typeof path.join === 'function' ? path.join.bind(path) : null;
112
134
  return (0, mockifyer_core_1.prepareMockResponseBody)(mockData, mockifyer_core_1.getCurrentDate, {
113
135
  loadPoolResponse: (0, mockifyer_core_1.createServeTimePoolResponseLoader)({
@@ -116,6 +138,8 @@ class MockifyerClass {
116
138
  joinPath,
117
139
  cache: this.poolResponseCache,
118
140
  }),
141
+ filename,
142
+ scenarioPath,
119
143
  });
120
144
  }
121
145
  /**
@@ -257,6 +281,15 @@ class MockifyerClass {
257
281
  }
258
282
  this.activationMode = (0, mockifyer_core_1.resolveActivationMode)(this.config);
259
283
  this.domainPathRules = new mockifyer_core_1.DomainPathRulesSession({ config: this.config });
284
+ (0, mockifyer_core_1.configureFlightRecorder)((0, mockifyer_core_1.resolveFlightRecorderConfig)(this.config));
285
+ (0, mockifyer_core_1.configureAtlas)(this.config, {
286
+ scenario: (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId),
287
+ clientId: this.config.clientId ?? null,
288
+ });
289
+ (0, mockifyer_core_1.setFlightRecorderRuntimeContext)({
290
+ clientId: this.config.clientId,
291
+ scenario: (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId),
292
+ });
260
293
  if (this.config.proxy?.baseUrl && this.config.proxy.mirrorRecordedMocksToClient === undefined) {
261
294
  const raw = typeof process !== 'undefined'
262
295
  ? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
@@ -395,6 +428,7 @@ class MockifyerClass {
395
428
  }
396
429
  const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(resolvedMockDataPath, this.config.clientId);
397
430
  const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(resolvedMockDataPath, currentScenario);
431
+ (0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(scenarioPath, { clientId: this.config.clientId });
398
432
  if (!fs.existsSync(scenarioPath)) {
399
433
  mockifyer_core_2.logger.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
400
434
  return undefined;
@@ -414,7 +448,11 @@ class MockifyerClass {
414
448
  }
415
449
  const mockKey = this.generateRequestKey(mockData.request);
416
450
  if (mockKey === requestKey) {
417
- if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, { includePassthroughMocks })) {
451
+ if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, {
452
+ includePassthroughMocks,
453
+ filename: file,
454
+ scenarioPath,
455
+ })) {
418
456
  exactMatch = { mockData, filename: file, filePath };
419
457
  break;
420
458
  }
@@ -483,7 +521,11 @@ class MockifyerClass {
483
521
  continue; // Required parameter differs, skip this mock
484
522
  }
485
523
  }
486
- if (!(0, mockifyer_core_1.mockPassesThroughToRealApi)(mockData)) {
524
+ if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, {
525
+ includePassthroughMocks,
526
+ filename: file,
527
+ scenarioPath,
528
+ })) {
487
529
  similarMatch = { mockData, filename: file, filePath };
488
530
  }
489
531
  }
@@ -537,7 +579,7 @@ class MockifyerClass {
537
579
  config.__mockifyer_bypass = true;
538
580
  return config;
539
581
  }
540
- const correlation = (0, mockifyer_core_1.applyOutboundRequestCorrelation)(config);
582
+ let correlation = (0, mockifyer_core_1.applyOutboundRequestCorrelation)(config);
541
583
  this.stashRequestCorrelation(config, correlation);
542
584
  // Normalize empty params: treat {} the same as undefined for consistent matching
543
585
  const rawParams = config.params || {};
@@ -574,10 +616,17 @@ class MockifyerClass {
574
616
  // Return cached mock if found
575
617
  if (cachedMock) {
576
618
  const { mockData, filename, filePath } = cachedMock;
619
+ correlation = this.bindStoredHopId(config, mockData, correlation) ?? correlation;
577
620
  if ((0, mockifyer_core_1.mockShouldServeStoredBody)(mockData)) {
578
621
  mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
579
622
  (filePath ? ` (${filePath})` : ''));
580
- const mockResponseBody = this.prepareStoredResponseBody(mockData);
623
+ const hitScenarioPath = path
624
+ ? (0, mockifyer_core_1.getScenarioFolderPath)(path.resolve(this.config.mockDataPath), (0, mockifyer_core_1.getCurrentScenario)(path.resolve(this.config.mockDataPath), this.config.clientId))
625
+ : undefined;
626
+ if (hitScenarioPath) {
627
+ (0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(hitScenarioPath, { clientId: this.config.clientId });
628
+ }
629
+ const mockResponseBody = this.prepareStoredResponseBody(mockData, filename, hitScenarioPath);
581
630
  this.logNetworkEvent({
582
631
  method: (request.method || 'GET').toUpperCase(),
583
632
  url: request.url,
@@ -718,6 +767,34 @@ class MockifyerClass {
718
767
  const isMocked = response.headers && response.headers['x-mockifyer'] === 'true';
719
768
  const isLimitReached = response.headers && response.headers['x-mockifyer-limit-reached'] === 'true';
720
769
  if (isMocked || isLimitReached) {
770
+ // Local mock hits are logged in the request interceptor; proxy mock hits must
771
+ // be recorded here before early return (otherwise flight recorder stays empty).
772
+ const shouldLogMockOrLimit = isLimitReached || (isMocked && this.usesDashboardProxy());
773
+ if (shouldLogMockOrLimit) {
774
+ const reqUrl = response.config?.url || url;
775
+ const reqMethod = (response.config?.method || 'GET').toUpperCase();
776
+ const startTime = response.config.__mockifyer_startTime;
777
+ const durationMs = startTime ? Date.now() - startTime : undefined;
778
+ this.logNetworkEvent({
779
+ method: reqMethod,
780
+ url: reqUrl,
781
+ source: isLimitReached ? 'error' : 'mock-hit',
782
+ status: response.status,
783
+ durationMs,
784
+ transport: this.usesDashboardProxy() ? 'proxy' : 'fetch',
785
+ requestBody: response.config?.data,
786
+ responseBody: response.data,
787
+ ...(isLimitReached
788
+ ? {
789
+ errorMessage: typeof response.data === 'object' &&
790
+ response.data !== null &&
791
+ 'message' in response.data
792
+ ? String(response.data.message)
793
+ : 'Request limit reached',
794
+ }
795
+ : {}),
796
+ }, this.readRequestCorrelation(response.config));
797
+ }
721
798
  return response;
722
799
  }
723
800
  if (this.config.proxy?.baseUrl && this.config.proxy?.mirrorRecordedMocksToClient) {
@@ -742,13 +819,19 @@ class MockifyerClass {
742
819
  response.data = (0, mockifyer_core_1.unwrapAndMergeInlineTraceEnvelope)(response.data);
743
820
  const capturedResponse = {
744
821
  status: response.status,
745
- data: response.data,
822
+ data: (0, mockifyer_core_1.stripMockifyerTraceFromBody)(response.data),
746
823
  headers: response.headers || {},
747
824
  };
748
825
  if ((0, mockifyer_core_1.resolveShouldPersistLiveCapture)(matchedMock.mockData, this.config)) {
749
- await this.persistMatchedMockAfterLiveCapture(matchedMock, capturedResponse, durationMs);
826
+ await this.persistMatchedMockAfterLiveCapture(matchedMock, capturedResponse, durationMs, this.readRequestCorrelation(response.config));
750
827
  }
751
- const clientResponse = (0, mockifyer_core_1.buildClientResponseFromLiveCapture)(matchedMock.mockData, capturedResponse, mockifyer_core_1.getCurrentDate);
828
+ const liveScenarioPath = path
829
+ ? (0, mockifyer_core_1.getScenarioFolderPath)(path.resolve(this.config.mockDataPath), (0, mockifyer_core_1.getCurrentScenario)(path.resolve(this.config.mockDataPath), this.config.clientId))
830
+ : undefined;
831
+ if (liveScenarioPath) {
832
+ (0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(liveScenarioPath, { clientId: this.config.clientId });
833
+ }
834
+ const clientResponse = (0, mockifyer_core_1.buildClientResponseFromLiveCapture)(matchedMock.mockData, capturedResponse, mockifyer_core_1.getCurrentDate, { filename: matchedMock.filename, scenarioPath: liveScenarioPath });
752
835
  response.data = clientResponse.data;
753
836
  response.status = clientResponse.status;
754
837
  delete response.config.__mockifyer_matchedMock;
@@ -963,6 +1046,7 @@ class MockifyerClass {
963
1046
  const startTime = response.config.__mockifyer_startTime;
964
1047
  const duration = startTime ? Date.now() - startTime : undefined;
965
1048
  const correlation = this.readRequestCorrelation(response.config);
1049
+ const hopIds = (0, mockifyer_core_1.resolvePersistedHopIds)(saveDecision.action === 'overwrite' ? existingMock?.mockData : undefined, correlation);
966
1050
  const mockData = {
967
1051
  request: {
968
1052
  method: response.config?.method?.toUpperCase() || 'GET',
@@ -973,7 +1057,7 @@ class MockifyerClass {
973
1057
  },
974
1058
  response: {
975
1059
  status: response.status,
976
- data: response.data,
1060
+ data: (0, mockifyer_core_1.stripMockifyerTraceFromBody)(response.data),
977
1061
  headers: response.headers || {},
978
1062
  },
979
1063
  timestamp: new Date().toISOString(),
@@ -981,8 +1065,8 @@ class MockifyerClass {
981
1065
  sessionId: saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
982
1066
  ? existingMock.mockData.sessionId
983
1067
  : this.currentSessionId,
984
- requestId: correlation?.requestId,
985
- parentRequestId: correlation?.parentRequestId,
1068
+ requestId: hopIds.requestId,
1069
+ parentRequestId: hopIds.parentRequestId,
986
1070
  ...((0, mockifyer_core_1.newRecordingUsesAlwaysUseRealApi)() ? { alwaysUseRealApi: true } : {}),
987
1071
  };
988
1072
  (0, mockifyer_core_1.applyRecordingPassthroughFlag)(mockData, saveDecision.alwaysUseRealApi);
@@ -1033,8 +1117,18 @@ class MockifyerClass {
1033
1117
  this.savingResponses.delete(requestKey);
1034
1118
  }
1035
1119
  }
1036
- async persistMatchedMockAfterLiveCapture(cachedMock, capturedResponse, durationMs) {
1120
+ async persistMatchedMockAfterLiveCapture(cachedMock, capturedResponse, durationMs, liveCorrelation) {
1037
1121
  const updated = (0, mockifyer_core_1.buildMockDataAfterLiveCapture)(cachedMock.mockData, capturedResponse, durationMs);
1122
+ const hopIds = (0, mockifyer_core_1.resolvePersistedHopIds)(cachedMock.mockData, liveCorrelation);
1123
+ if (hopIds.requestId) {
1124
+ updated.requestId = hopIds.requestId;
1125
+ }
1126
+ if (hopIds.parentRequestId) {
1127
+ updated.parentRequestId = hopIds.parentRequestId;
1128
+ }
1129
+ else {
1130
+ delete updated.parentRequestId;
1131
+ }
1038
1132
  if (this.databaseProvider) {
1039
1133
  await this.databaseProvider.save(updated);
1040
1134
  return;
@@ -1292,6 +1386,7 @@ function setupMockifyer(config) {
1292
1386
  }
1293
1387
  (0, mockifyer_core_1.initializeDateManipulation)(resolvedConfig);
1294
1388
  (0, mockifyer_core_1.initializeScenario)(resolvedConfig);
1389
+ (0, mockifyer_core_1.scheduleRuntimeDateSyncFromConfig)(resolvedConfig);
1295
1390
  const mockifyer = new MockifyerClass(resolvedConfig);
1296
1391
  const httpClient = mockifyer.getHTTPClient();
1297
1392
  // Always store original fetch (even if not patching global)
@@ -1316,10 +1411,10 @@ function setupMockifyer(config) {
1316
1411
  const method = init?.method || 'GET';
1317
1412
  const headers = init?.headers || {};
1318
1413
  const body = init?.body;
1319
- // Skip Mockifyer sync endpoints, dashboard `/api/proxy` plumbing, and Resend API
1414
+ // Skip Mockifyer sync endpoints, dashboard plumbing, and Resend API
1320
1415
  if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(url) ||
1321
1416
  url.includes('api.resend.com') ||
1322
- (0, mockifyer_core_1.isMockifyerDashboardProxyApiUrl)(url)) {
1417
+ (0, mockifyer_core_1.isMockifyerDashboardPlumbingApiUrl)(url)) {
1323
1418
  return await originalFetchForPatched(input, init);
1324
1419
  }
1325
1420
  const simpleRequestKey = `${method}:${url}`;
@@ -1355,7 +1450,7 @@ function setupMockifyer(config) {
1355
1450
  });
1356
1451
  }
1357
1452
  else {
1358
- headersObj = headers;
1453
+ headersObj = { ...headers };
1359
1454
  }
1360
1455
  try {
1361
1456
  const requestConfig = {
@@ -8,6 +8,17 @@
8
8
  * 4. GET /mockifyer-sync-to-device - Legacy: all files in one response (may fail on large scenarios)
9
9
  * 5. GET /mockifyer-pool-response?id= - Load a promoted pool response for RN `$pool` resolve
10
10
  * 6. GET /mockifyer-sync - Legacy: iOS simulator mock-data → project folder
11
+ * 7. POST /mockifyer-atlas-html — write crash-scoped trace HTML to mock-data/atlas-html/incidents/
12
+ * 8. GET /atlas-html[/…] (legacy: /mockifyer-atlas-html[/…]) — serve atlas-html static files (index.html, pages, incidents, screenshots)
13
+ * 9. POST /mockifyer-atlas-screenshot — write screen image (png/jpg/webp) under mock-data/atlas-html/screenshots/
14
+ * 10. POST /mockifyer-atlas-render — write full interactive Atlas HTML under mock-data/atlas-html/
15
+ * 11. POST /mockifyer-atlas-body-spill — write full hop body text under mock-data/atlas-html/bodies/
16
+ * 12. POST/GET /mockifyer-network-events — live hop ring buffer for `mockifyer-atlas` CLI
17
+ * 13. GET /mockifyer-network-events/stream — SSE hop stream
18
+ * 14. GET /mockifyer-network-events/analyze — hop summary JSON
19
+ * 15. POST /mockifyer-network-events/snapshot — write hops JSON/NDJSON under atlas-html/
20
+ * 16. POST /mockifyer-network-events/render — render Atlas HTML from buffer hops
21
+ * 17. POST /mockifyer-network-events/clear — clear ring buffer
11
22
  *
12
23
  * The Hybrid Provider (recommended) uses POST /mockifyer-save for instant file sync.
13
24
  * Legacy polling-based sync is still available for backward compatibility.
@@ -24,7 +35,7 @@ export interface MetroSyncMiddlewareOptions {
24
35
  /** Enable automatic test generation when mocks are saved */
25
36
  enabled?: boolean;
26
37
  /** Test framework to use: 'jest' (default), 'vitest', or 'mocha' */
27
- framework?: 'jest' | 'vitest' | 'mocha';
38
+ framework?: "jest" | "vitest" | "mocha";
28
39
  /** Output path for generated tests (default: './tests/generated') */
29
40
  outputPath?: string;
30
41
  /** Test file naming pattern with placeholders: {endpoint}, {method}, {scenario} (default: '{endpoint}.test.ts') */
@@ -32,7 +43,7 @@ export interface MetroSyncMiddlewareOptions {
32
43
  /** Include setup code in generated tests (default: true) */
33
44
  includeSetup?: boolean;
34
45
  /** Group tests by: 'endpoint', 'scenario', or 'file' (default: 'endpoint') */
35
- groupBy?: 'endpoint' | 'scenario' | 'file';
46
+ groupBy?: "endpoint" | "scenario" | "file";
36
47
  /** If true, only generate one test per endpoint (method + pathname), ignoring query parameters (default: false) */
37
48
  uniqueTestsPerEndpoint?: boolean;
38
49
  };