@sgedda/mockifyer-fetch 1.8.26 → 1.8.33

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/dist/index.js CHANGED
@@ -14,7 +14,10 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.canUseDashboardCentralProxy = exports.canUseDashboardRedisProxy = void 0;
17
18
  exports.setupMockifyer = setupMockifyer;
19
+ exports.initMockifyerForDashboardProxy = initMockifyerForDashboardProxy;
20
+ exports.initMockifyerForLocalFilesystem = initMockifyerForLocalFilesystem;
18
21
  // Fetch-only Mockifyer implementation
19
22
  // Conditionally import fs - will be undefined in React Native
20
23
  let fs;
@@ -34,6 +37,37 @@ const mockifyer_core_1 = require("@sgedda/mockifyer-core");
34
37
  const mockifyer_core_2 = require("@sgedda/mockifyer-core");
35
38
  const fetch_client_1 = require("./clients/fetch-client");
36
39
  class MockifyerClass {
40
+ /** Best-effort dashboard network log (skipped when traffic goes through `proxy.baseUrl`). */
41
+ logNetworkEvent(partial, correlation) {
42
+ if (this.config.proxy?.baseUrl)
43
+ return;
44
+ const scenario = this.config.proxy?.scenario?.trim() ||
45
+ (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath);
46
+ (0, mockifyer_core_1.emitMockifyerNetworkEvent)({
47
+ config: this.config,
48
+ scenario,
49
+ clientId: this.config.clientId,
50
+ event: {
51
+ ...partial,
52
+ transport: partial.transport ?? 'fetch',
53
+ requestId: correlation?.requestId ?? partial.requestId,
54
+ parentRequestId: correlation?.parentRequestId ?? partial.parentRequestId,
55
+ },
56
+ });
57
+ }
58
+ stashRequestCorrelation(config, correlation) {
59
+ config.__mockifyer_requestId =
60
+ correlation.requestId;
61
+ config.__mockifyer_parentRequestId =
62
+ correlation.parentRequestId;
63
+ }
64
+ readRequestCorrelation(config) {
65
+ const requestId = config.__mockifyer_requestId;
66
+ if (!requestId)
67
+ return undefined;
68
+ const parentRequestId = config.__mockifyer_parentRequestId;
69
+ return parentRequestId ? { requestId, parentRequestId } : { requestId };
70
+ }
37
71
  constructor(config) {
38
72
  this.processingRequests = new Set();
39
73
  this.savingResponses = new Set();
@@ -94,10 +128,23 @@ class MockifyerClass {
94
128
  if (launchClientId) {
95
129
  this.config.clientId = launchClientId;
96
130
  }
131
+ else if ((0, mockifyer_core_1.resolveStrictScenarioResolution)(this.config) &&
132
+ Boolean(this.config.proxy?.baseUrl?.trim())) {
133
+ // Strict proxy: no auto lane until explicit clientId / setClientId (devtools show real URLs).
134
+ this.config.clientId = (0, mockifyer_core_1.resolveExplicitClientIdOnly)(this.config);
135
+ }
97
136
  else {
98
137
  this.config.clientId = (0, mockifyer_core_1.resolveClientId)(this.config);
99
138
  }
100
139
  this.activationMode = (0, mockifyer_core_1.resolveActivationMode)(this.config);
140
+ if (this.config.proxy?.baseUrl && this.config.proxy.mirrorRecordedMocksToClient === undefined) {
141
+ const raw = typeof process !== 'undefined'
142
+ ? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
143
+ : '';
144
+ if (raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on') {
145
+ this.config.proxy = { ...this.config.proxy, mirrorRecordedMocksToClient: true };
146
+ }
147
+ }
101
148
  // Initialize test generator if test generation is enabled
102
149
  if (config.generateTests?.enabled) {
103
150
  this.testGenerator = new mockifyer_core_1.TestGenerator();
@@ -134,6 +181,7 @@ class MockifyerClass {
134
181
  clientId: this.config.clientId,
135
182
  getClientId: () => this.config.clientId,
136
183
  getStrictLaneScenario: () => (0, mockifyer_core_1.resolveProxyStrictLaneScenario)(this.config),
184
+ getExplicitProxyScenarioContext: () => (0, mockifyer_core_1.isExplicitProxyScenarioContext)(this.config),
137
185
  deviceId: this.config.deviceId,
138
186
  });
139
187
  if (!config.recordSameEndpoints) {
@@ -160,7 +208,12 @@ class MockifyerClass {
160
208
  generateRequestKey(request) {
161
209
  return (0, mockifyer_core_1.generateRequestKey)(request);
162
210
  }
163
- async findBestMatchingMock(request) {
211
+ /** When set, mock resolution happens on the dashboard `/api/proxy` (Redis/disk), not local `mock-data`. */
212
+ usesDashboardProxy() {
213
+ const baseUrl = this.config.proxy?.baseUrl;
214
+ return typeof baseUrl === 'string' && baseUrl.trim().length > 0;
215
+ }
216
+ async findBestMatchingMock(request, options) {
164
217
  // CRITICAL: Never try to match sync endpoint requests - they should never be mocked
165
218
  const requestUrl = request?.url || '';
166
219
  if (requestUrl.includes('/mockifyer-save') ||
@@ -177,12 +230,12 @@ class MockifyerClass {
177
230
  }
178
231
  // Use database provider if available, otherwise fallback to filesystem
179
232
  if (this.databaseProvider) {
180
- return await this.findBestMatchingMockFromProvider(request);
233
+ return await this.findBestMatchingMockFromProvider(request, options);
181
234
  }
182
235
  // Fallback to Node.js filesystem
183
- return this.findBestMatchingMockFromFiles(request);
236
+ return this.findBestMatchingMockFromFiles(request, options);
184
237
  }
185
- async findBestMatchingMockFromProvider(request) {
238
+ async findBestMatchingMockFromProvider(request, options) {
186
239
  if (!this.databaseProvider) {
187
240
  return undefined;
188
241
  }
@@ -201,7 +254,7 @@ class MockifyerClass {
201
254
  return undefined;
202
255
  }
203
256
  // Try exact match first
204
- const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey);
257
+ const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey, options);
205
258
  if (exactMatch) {
206
259
  return exactMatch;
207
260
  }
@@ -215,7 +268,8 @@ class MockifyerClass {
215
268
  }
216
269
  return undefined;
217
270
  }
218
- findBestMatchingMockFromFiles(request) {
271
+ findBestMatchingMockFromFiles(request, options) {
272
+ const includePassthroughMocks = options?.includePassthroughMocks === true;
219
273
  // Only use fs if available (Node.js environment)
220
274
  // This method should never be called when using a database provider
221
275
  if (!fs || !path) {
@@ -247,7 +301,7 @@ class MockifyerClass {
247
301
  }
248
302
  const mockKey = this.generateRequestKey(mockData.request);
249
303
  if (mockKey === requestKey) {
250
- if (!(0, mockifyer_core_1.mockPassesThroughToRealApi)(mockData)) {
304
+ if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, { includePassthroughMocks })) {
251
305
  exactMatch = { mockData, filename: file, filePath };
252
306
  break;
253
307
  }
@@ -357,6 +411,7 @@ class MockifyerClass {
357
411
  if (!(0, mockifyer_core_1.shouldApplyMockifyer)(this.activationMode, config.headers, {
358
412
  useProxyLane: { proxyBaseUrl: this.config.proxy?.baseUrl, resolvedClientId: this.config.clientId },
359
413
  })) {
414
+ (0, mockifyer_core_1.applyOutboundRequestCorrelation)(config);
360
415
  config.__mockifyer_bypass = true;
361
416
  return config;
362
417
  }
@@ -365,6 +420,8 @@ class MockifyerClass {
365
420
  config.__mockifyer_bypass = true;
366
421
  return config;
367
422
  }
423
+ const correlation = (0, mockifyer_core_1.applyOutboundRequestCorrelation)(config);
424
+ this.stashRequestCorrelation(config, correlation);
368
425
  // Normalize empty params: treat {} the same as undefined for consistent matching
369
426
  const rawParams = config.params || {};
370
427
  const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
@@ -383,31 +440,48 @@ class MockifyerClass {
383
440
  config.__mockifyer_requestKey = requestKey;
384
441
  // Store request start time for duration calculation
385
442
  config.__mockifyer_startTime = Date.now();
443
+ // Dashboard proxy owns mock hits (Redis + server-side disk fallback). Do not short-circuit
444
+ // from local mock-data while proxy.baseUrl is configured — that bypasses /api/proxy entirely.
445
+ if (this.usesDashboardProxy()) {
446
+ return config;
447
+ }
386
448
  const cachedMock = await this.findBestMatchingMock(request);
387
449
  // Return cached mock if found
388
450
  if (cachedMock) {
389
451
  const { mockData, filename, filePath } = cachedMock;
390
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
452
+ if ((0, mockifyer_core_1.mockShouldServeStoredBody)(mockData)) {
453
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
454
+ (filePath ? ` (${filePath})` : ''));
455
+ this.logNetworkEvent({
456
+ method: (request.method || 'GET').toUpperCase(),
457
+ url: request.url,
458
+ source: 'mock-hit',
459
+ status: mockData.response.status,
460
+ requestHash: (0, mockifyer_core_1.networkEventHashFromRequestKey)(requestKey),
461
+ }, correlation);
462
+ const responseHeaders = {
463
+ ...mockData.response.headers,
464
+ 'x-mockifyer': 'true',
465
+ 'x-mockifyer-timestamp': mockData.timestamp,
466
+ 'x-mockifyer-filename': filename,
467
+ 'x-mockifyer-filepath': filePath
468
+ };
469
+ const mockResponse = {
470
+ data: (0, mockifyer_core_1.prepareMockResponseBody)(mockData, mockifyer_core_1.getCurrentDate),
471
+ status: mockData.response.status,
472
+ statusText: 'OK',
473
+ headers: responseHeaders,
474
+ config: config
475
+ };
476
+ return {
477
+ ...config,
478
+ __mockResponse: Promise.resolve(mockResponse),
479
+ __mockifyer_requestKey: requestKey
480
+ };
481
+ }
482
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Live refresh: ${request.method} ${request.url} → ${filename}` +
391
483
  (filePath ? ` (${filePath})` : ''));
392
- const responseHeaders = {
393
- ...mockData.response.headers,
394
- 'x-mockifyer': 'true',
395
- 'x-mockifyer-timestamp': mockData.timestamp,
396
- 'x-mockifyer-filename': filename,
397
- 'x-mockifyer-filepath': filePath
398
- };
399
- const mockResponse = {
400
- data: (0, mockifyer_core_1.prepareMockResponseBody)(mockData, mockifyer_core_1.getCurrentDate),
401
- status: mockData.response.status,
402
- statusText: 'OK',
403
- headers: responseHeaders,
404
- config: config
405
- };
406
- return {
407
- ...config,
408
- __mockResponse: Promise.resolve(mockResponse),
409
- __mockifyer_requestKey: requestKey
410
- };
484
+ config.__mockifyer_matchedMock = cachedMock;
411
485
  }
412
486
  // Check request limit BEFORE making real API call (only if no mock found and in record mode)
413
487
  if (this.config.recordMode) {
@@ -519,20 +593,139 @@ class MockifyerClass {
519
593
  if (isMocked || isLimitReached) {
520
594
  return response;
521
595
  }
596
+ if (this.config.proxy?.baseUrl && this.config.proxy?.mirrorRecordedMocksToClient) {
597
+ await this.maybeMirrorProxyRecordingToClient(response);
598
+ }
599
+ const matchedMock = response.config.__mockifyer_matchedMock;
600
+ if (matchedMock) {
601
+ const capturedResponse = {
602
+ status: response.status,
603
+ data: response.data,
604
+ headers: response.headers || {},
605
+ };
606
+ const startTime = response.config.__mockifyer_startTime;
607
+ const durationMs = startTime ? Date.now() - startTime : undefined;
608
+ if ((0, mockifyer_core_1.resolveShouldPersistLiveCapture)(matchedMock.mockData, this.config)) {
609
+ await this.persistMatchedMockAfterLiveCapture(matchedMock, capturedResponse, durationMs);
610
+ }
611
+ const clientResponse = (0, mockifyer_core_1.buildClientResponseFromLiveCapture)(matchedMock.mockData, capturedResponse, mockifyer_core_1.getCurrentDate);
612
+ response.data = clientResponse.data;
613
+ response.status = clientResponse.status;
614
+ delete response.config.__mockifyer_matchedMock;
615
+ const reqUrl = response.config?.url || url;
616
+ const reqMethod = (response.config?.method || 'GET').toUpperCase();
617
+ this.logNetworkEvent({
618
+ method: reqMethod,
619
+ url: reqUrl,
620
+ source: 'upstream',
621
+ status: response.status,
622
+ durationMs,
623
+ }, this.readRequestCorrelation(response.config));
624
+ return response;
625
+ }
522
626
  // Only save locally if recordMode is enabled AND we're not proxying upstream calls.
523
627
  // When proxy is configured, recording should happen on the proxy (e.g. dashboard → Redis).
524
628
  if (this.config.recordMode && !this.config.proxy?.baseUrl) {
525
629
  await this.saveResponse(response);
526
630
  }
631
+ const reqUrl = response.config?.url || url;
632
+ const reqMethod = (response.config?.method || 'GET').toUpperCase();
633
+ this.logNetworkEvent({
634
+ method: reqMethod,
635
+ url: reqUrl,
636
+ source: 'upstream',
637
+ status: response.status,
638
+ durationMs: typeof response.config?.metadata?.durationMs === 'number'
639
+ ? response.config.metadata.durationMs
640
+ : undefined,
641
+ }, this.readRequestCorrelation(response.config));
527
642
  return response;
528
643
  }, async (error) => {
529
644
  const requestKey = error.config?.__mockifyer_requestKey;
530
645
  if (requestKey) {
531
646
  this.processingRequests.delete(requestKey);
532
647
  }
648
+ const reqUrl = error.config?.url || '';
649
+ if (reqUrl) {
650
+ this.logNetworkEvent({
651
+ method: (error.config?.method || 'GET').toUpperCase(),
652
+ url: reqUrl,
653
+ source: 'error',
654
+ status: error.response?.status,
655
+ errorMessage: error?.message ?? String(error),
656
+ }, this.readRequestCorrelation(error.config));
657
+ }
533
658
  throw error;
534
659
  });
535
660
  }
661
+ /**
662
+ * When dashboard proxy records to Redis, optionally persist the same payload next to the client
663
+ * (Node fs, database provider with `SaveMockOptions.scenario`, or Metro /mockifyer-save for strict RN).
664
+ */
665
+ async maybeMirrorProxyRecordingToClient(response) {
666
+ const rec = response.mockifyerProxyRecording;
667
+ if (!rec?.recordedToStore || !rec.storedMock) {
668
+ return;
669
+ }
670
+ const hash = rec.hash?.trim();
671
+ const scenarioName = rec.scenarioName?.trim();
672
+ const mockData = rec.storedMock;
673
+ const providerType = this.config.databaseProvider?.type;
674
+ await (0, mockifyer_core_1.mirrorProxyRecordingToClient)({
675
+ config: this.config,
676
+ mockDataPath: this.config.mockDataPath,
677
+ recording: rec,
678
+ databaseProvider: this.databaseProvider,
679
+ databaseProviderInitPromise: this.databaseProviderInitPromise,
680
+ logPrefix: 'Mockifyer-Fetch',
681
+ });
682
+ if (providerType === 'hybrid' && hash && scenarioName && mockData) {
683
+ await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
684
+ }
685
+ else if (!fs && hash && scenarioName && mockData) {
686
+ await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
687
+ }
688
+ }
689
+ async tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash) {
690
+ const metroPort = process.env.METRO_PORT ? parseInt(process.env.METRO_PORT, 10) : 8081;
691
+ const fetchFn = global.__mockifyer_original_fetch || fetch;
692
+ if (!fetchFn) {
693
+ mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Proxy client mirror: no fetch for Metro save');
694
+ return;
695
+ }
696
+ try {
697
+ const body = JSON.stringify({
698
+ __mockifyerProxyMirror: true,
699
+ mockData,
700
+ scenarioName,
701
+ relativePath: `redis/${hash}.json`,
702
+ });
703
+ const res = await fetchFn(`http://localhost:${metroPort}/mockifyer-save`, {
704
+ method: 'POST',
705
+ headers: { 'Content-Type': 'application/json' },
706
+ body,
707
+ });
708
+ const text = await res.text().catch(() => '');
709
+ if (!res.ok) {
710
+ mockifyer_core_2.logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): HTTP ${res.status} ${text}`);
711
+ return;
712
+ }
713
+ try {
714
+ const parsed = JSON.parse(text);
715
+ if (parsed.success === false) {
716
+ mockifyer_core_2.logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): ${parsed.error || 'save failed'}`);
717
+ return;
718
+ }
719
+ }
720
+ catch {
721
+ // non-JSON response
722
+ }
723
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (Metro): ${scenarioName}/redis/${hash}.json`);
724
+ }
725
+ catch (e) {
726
+ mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Proxy client mirror (Metro) failed:', e);
727
+ }
728
+ }
536
729
  async saveResponse(response) {
537
730
  // CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
538
731
  if (response.config?.__mockifyer_skip_save || response.config?.__mockifyer_bypass) {
@@ -543,10 +736,19 @@ class MockifyerClass {
543
736
  if (this.config.proxy?.baseUrl) {
544
737
  return;
545
738
  }
739
+ if ((0, mockifyer_core_1.shouldBlockLocalMockRecording)(this.config)) {
740
+ mockifyer_core_2.logger.info('[Mockifyer-Fetch] Strict proxy-only mode: skipping local mock save (dashboard proxy unavailable).');
741
+ return;
742
+ }
546
743
  const url = response.config?.url || response.request?.responseURL || response.url || '';
744
+ const recordingExclusions = (0, mockifyer_core_1.resolveRecordingExclusions)(this.config);
547
745
  if (url && (0, mockifyer_core_1.shouldExcludeUrl)(url, this.config.excludedUrls)) {
548
746
  return;
549
747
  }
748
+ if (url &&
749
+ (0, mockifyer_core_1.shouldExcludeRecording)(url, recordingExclusions, this.config.baseUrl)) {
750
+ return;
751
+ }
550
752
  // CRITICAL: Check response data for sync endpoint references and Metro rejection messages
551
753
  // This is a defense-in-depth measure
552
754
  try {
@@ -580,57 +782,68 @@ class MockifyerClass {
580
782
  // Normalize empty params: treat {} the same as undefined for consistent matching
581
783
  const rawParams = response.config.params || {};
582
784
  const normalizedParams = rawParams && Object.keys(rawParams).length > 0 ? rawParams : undefined;
583
- const requestKey = this.generateRequestKey({
785
+ const saveLookupRequest = {
584
786
  method: response.config.method?.toUpperCase() || 'GET',
585
787
  url: response.config.url || '',
586
788
  headers: {},
587
789
  data: response.config.data,
588
- queryParams: normalizedParams
589
- });
790
+ queryParams: normalizedParams,
791
+ };
792
+ const requestKey = this.generateRequestKey(saveLookupRequest);
590
793
  if (this.savingResponses.has(requestKey)) {
591
794
  return;
592
795
  }
796
+ const existingMock = await this.findBestMatchingMock(saveLookupRequest, {
797
+ includePassthroughMocks: true,
798
+ });
799
+ const saveDecision = (0, mockifyer_core_1.resolveMockRecordingSaveDecision)(this.config, existingMock?.mockData);
800
+ if (saveDecision.action === 'skip') {
801
+ if (existingMock && (0, mockifyer_core_1.mockPassesThroughToRealApi)(existingMock.mockData)) {
802
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Passthrough mock exists for ${requestKey}, skipping save (enable refreshPassthroughRecordings to update).`);
803
+ }
804
+ return;
805
+ }
593
806
  this.savingResponses.add(requestKey);
594
807
  try {
595
- // Normalize empty params: treat {} the same as undefined for consistent matching
596
- const rawParams = response.config.params || {};
597
- const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
598
- const normalizedParams = anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
808
+ const rawParamsForSave = response.config.params || {};
809
+ const anonymizedQueryParams = this.anonymizeQueryParams(rawParamsForSave);
810
+ const normalizedParamsForSave = anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
599
811
  ? anonymizedQueryParams
600
812
  : undefined;
601
- // Generate or reuse sessionId
602
813
  const now = Date.now();
603
- if (!this.currentSessionId || (now - this.sessionStartTime) > this.SESSION_TIMEOUT_MS) {
604
- // Generate new session ID
814
+ if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
605
815
  this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
606
816
  this.sessionStartTime = now;
607
817
  }
608
- // Calculate request duration if start time is available
609
818
  const startTime = response.config.__mockifyer_startTime;
610
819
  const duration = startTime ? Date.now() - startTime : undefined;
820
+ const correlation = this.readRequestCorrelation(response.config);
611
821
  const mockData = {
612
822
  request: {
613
823
  method: response.config?.method?.toUpperCase() || 'GET',
614
824
  url: response.config?.url || '',
615
825
  headers: this.anonymizeHeaders(response.config?.headers || {}),
616
826
  data: response.config?.data,
617
- queryParams: normalizedParams
827
+ queryParams: normalizedParamsForSave,
618
828
  },
619
829
  response: {
620
830
  status: response.status,
621
831
  data: response.data,
622
- headers: response.headers || {}
832
+ headers: response.headers || {},
623
833
  },
624
834
  timestamp: new Date().toISOString(),
625
835
  duration,
626
- sessionId: this.currentSessionId
836
+ sessionId: saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
837
+ ? existingMock.mockData.sessionId
838
+ : this.currentSessionId,
839
+ requestId: correlation?.requestId,
840
+ parentRequestId: correlation?.parentRequestId,
841
+ ...((0, mockifyer_core_1.newRecordingUsesAlwaysUseRealApi)() ? { alwaysUseRealApi: true } : {}),
627
842
  };
628
- // Use database provider if available, otherwise fallback to filesystem
843
+ (0, mockifyer_core_1.applyRecordingPassthroughFlag)(mockData, saveDecision.alwaysUseRealApi);
629
844
  if (this.databaseProvider) {
630
845
  try {
631
846
  await this.databaseProvider.save(mockData);
632
- // Generate test if enabled (try to write test files even with database provider)
633
- // Generate test if enabled
634
847
  if (this.config.generateTests?.enabled) {
635
848
  await this.generateTestForMock(mockData);
636
849
  }
@@ -641,26 +854,28 @@ class MockifyerClass {
641
854
  }
642
855
  }
643
856
  else if (fs && path) {
644
- // Fallback to Node.js filesystem (only if fs/path are available)
645
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
646
- const urlParts = (response.config.url || '').replace(/https?:\/\//, '').split('/');
647
- const domain = urlParts[0].replace(/\./g, '_');
648
- const urlPathPart = urlParts.slice(1).join('_') || 'root';
649
- const filename = `${timestamp}_${response.config.method?.toUpperCase() || 'GET'}_${domain}_${urlPathPart}.json`;
650
857
  const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId);
651
858
  const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(this.config.mockDataPath, currentScenario);
652
859
  (0, mockifyer_core_1.ensureScenarioFolder)(this.config.mockDataPath, currentScenario);
653
- // Check request limit before saving (only if limit is set via env var)
654
860
  const limitCheck = (0, mockifyer_core_1.checkRequestLimit)(this.config.mockDataPath);
655
861
  if (limitCheck.limitReached && limitCheck.error) {
656
862
  console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
657
- // Don't throw - just log and return to prevent app crash
658
863
  return;
659
864
  }
660
- const filePath = path.join(scenarioPath, filename);
661
- fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
662
- mockifyer_core_2.logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${filename}`);
663
- // Generate test if enabled
865
+ if (saveDecision.action === 'overwrite' && existingMock?.filePath) {
866
+ fs.writeFileSync(existingMock.filePath, JSON.stringify(mockData, null, 2));
867
+ mockifyer_core_2.logger.info(`[Mockifyer] Refreshed passthrough mock: ${currentScenario}/${existingMock.filename}`);
868
+ }
869
+ else {
870
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
871
+ const urlParts = (response.config.url || '').replace(/https?:\/\//, '').split('/');
872
+ const domain = urlParts[0].replace(/\./g, '_');
873
+ const urlPathPart = urlParts.slice(1).join('_') || 'root';
874
+ const filename = `${timestamp}_${response.config.method?.toUpperCase() || 'GET'}_${domain}_${urlPathPart}.json`;
875
+ const filePath = path.join(scenarioPath, filename);
876
+ fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
877
+ mockifyer_core_2.logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${filename}`);
878
+ }
664
879
  if (this.config.generateTests?.enabled && this.testGenerator) {
665
880
  await this.generateTestForMock(mockData);
666
881
  }
@@ -673,6 +888,17 @@ class MockifyerClass {
673
888
  this.savingResponses.delete(requestKey);
674
889
  }
675
890
  }
891
+ async persistMatchedMockAfterLiveCapture(cachedMock, capturedResponse, durationMs) {
892
+ const updated = (0, mockifyer_core_1.buildMockDataAfterLiveCapture)(cachedMock.mockData, capturedResponse, durationMs);
893
+ if (this.databaseProvider) {
894
+ await this.databaseProvider.save(updated);
895
+ return;
896
+ }
897
+ if (fs && cachedMock.filePath) {
898
+ fs.writeFileSync(cachedMock.filePath, JSON.stringify(updated, null, 2));
899
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Refreshed mock from live API: ${cachedMock.filename}`);
900
+ }
901
+ }
676
902
  /**
677
903
  * Simple path resolution fallback for React Native (when path module is stubbed)
678
904
  */
@@ -884,8 +1110,13 @@ class MockifyerClass {
884
1110
  }
885
1111
  }
886
1112
  function setupMockifyer(config) {
1113
+ // Node-only inbound capture; safe on RN (no-op when not on Node).
1114
+ if (typeof mockifyer_core_1.installNodeInboundRequestCorrelationCapture === 'function') {
1115
+ (0, mockifyer_core_1.installNodeInboundRequestCorrelationCapture)();
1116
+ }
1117
+ const resolvedConfig = (0, mockifyer_core_1.applyProxyRecordOnMissEnv)(config);
887
1118
  // Initialize logger with config level (default to 'info' if not specified)
888
- (0, mockifyer_core_2.setLogLevel)(config.logging || 'info');
1119
+ (0, mockifyer_core_2.setLogLevel)(resolvedConfig.logging || 'info');
889
1120
  // Set environment variables for Metro middleware to read test generation config
890
1121
  // This allows Metro middleware (which runs in Node.js) to generate tests
891
1122
  // when Hybrid Provider saves mocks via Metro endpoint
@@ -910,9 +1141,9 @@ function setupMockifyer(config) {
910
1141
  process.env.MOCKIFYER_UNIQUE_TESTS_PER_ENDPOINT = 'true';
911
1142
  }
912
1143
  }
913
- (0, mockifyer_core_1.initializeDateManipulation)(config);
914
- (0, mockifyer_core_1.initializeScenario)(config);
915
- const mockifyer = new MockifyerClass(config);
1144
+ (0, mockifyer_core_1.initializeDateManipulation)(resolvedConfig);
1145
+ (0, mockifyer_core_1.initializeScenario)(resolvedConfig);
1146
+ const mockifyer = new MockifyerClass(resolvedConfig);
916
1147
  const httpClient = mockifyer.getHTTPClient();
917
1148
  // Always store original fetch (even if not patching global)
918
1149
  let originalFetch;
@@ -928,7 +1159,7 @@ function setupMockifyer(config) {
928
1159
  fetchClient._originalFetch = originalFetch;
929
1160
  }
930
1161
  // Patch global fetch if useGlobalFetch is true
931
- if (config.useGlobalFetch) {
1162
+ if (resolvedConfig.useGlobalFetch) {
932
1163
  const mockifyerInstance = mockifyer;
933
1164
  const originalFetchForPatched = global.__mockifyer_original_fetch || originalFetch;
934
1165
  global.fetch = async function (input, init) {
@@ -1028,7 +1259,24 @@ function setupMockifyer(config) {
1028
1259
  (0, mockifyer_core_1.registerMockifyerInstance)(extendedClient);
1029
1260
  return extendedClient;
1030
1261
  }
1262
+ /**
1263
+ * Preset: dashboard central store proxy when health check passes; otherwise filesystem mocks.
1264
+ * For full control, use {@link setupMockifyer} directly.
1265
+ */
1266
+ async function initMockifyerForDashboardProxy(options) {
1267
+ return (0, mockifyer_core_1.initMockifyerForDashboardProxy)({ ...options, useGlobalFetch: options.useGlobalFetch ?? options.config?.useGlobalFetch ?? true }, setupMockifyer);
1268
+ }
1269
+ /**
1270
+ * Preset: local filesystem mocks. No dashboard proxy.
1271
+ */
1272
+ function initMockifyerForLocalFilesystem(options = {}) {
1273
+ return (0, mockifyer_core_1.initMockifyerForLocalFilesystem)({ ...options, useGlobalFetch: options.useGlobalFetch ?? options.config?.useGlobalFetch ?? true }, setupMockifyer);
1274
+ }
1275
+ /** Shared with {@link setupMockifyerForReactNative} strict-proxy branching. */
1276
+ var dashboard_redis_health_1 = require("./utils/dashboard-redis-health");
1277
+ Object.defineProperty(exports, "canUseDashboardRedisProxy", { enumerable: true, get: function () { return dashboard_redis_health_1.canUseDashboardRedisProxy; } });
1278
+ Object.defineProperty(exports, "canUseDashboardCentralProxy", { enumerable: true, get: function () { return dashboard_redis_health_1.canUseDashboardCentralProxy; } });
1031
1279
  // Re-export types from core
1032
1280
  __exportStar(require("@sgedda/mockifyer-core"), exports);
1033
- // Export React Native helpers
1034
- __exportStar(require("./react-native"), exports);
1281
+ // React Native helpers: import `@sgedda/mockifyer-fetch/react-native` (not this entry — avoids
1282
+ // pulling optional `react-native-launch-arguments` into Node/Next webpack bundles).
@@ -52,10 +52,29 @@ const mockifyer_core_1 = require("@sgedda/mockifyer-core");
52
52
  * Node.js built-in modules that need to be stubbed for React Native
53
53
  * Includes modules used by Mockifyer packages and their dependencies:
54
54
  * - fs, path: Used by FilesystemProvider
55
- * - assert: Used by @sinonjs/fake-timers
56
- * - util: Used by @sinonjs/fake-timers
55
+ * - assert, util: Used by @sinonjs/fake-timers
56
+ * - http, https, async_hooks: request-correlation (Node inbound capture; stubbed on RN)
57
+ * - crypto: crypto-digest optional Node fast path (pure JS fallback on RN)
57
58
  */
58
- const NODE_BUILTINS = ['fs', 'path', 'assert', 'util'];
59
+ const NODE_BUILTINS = [
60
+ 'fs',
61
+ 'path',
62
+ 'assert',
63
+ 'util',
64
+ 'http',
65
+ 'https',
66
+ 'async_hooks',
67
+ 'crypto',
68
+ ];
69
+ /**
70
+ * Optional React Native peer dependencies — stubbed when not installed so
71
+ * `tryGetClientIdFromLaunchArguments` and similar helpers no-op instead of crashing Metro.
72
+ */
73
+ const OPTIONAL_RN_PEER_MODULES = ['react-native-launch-arguments'];
74
+ function isMockifyerStubbedModule(moduleName) {
75
+ return (NODE_BUILTINS.includes(moduleName) ||
76
+ OPTIONAL_RN_PEER_MODULES.includes(moduleName));
77
+ }
59
78
  /**
60
79
  * Configure Metro bundler for Mockifyer
61
80
  *
@@ -125,8 +144,8 @@ function configureMetroForMockifyer(config, options) {
125
144
  const existingResolveRequest = existingResolver.resolveRequest;
126
145
  // Create new resolveRequest function that handles Node.js built-ins
127
146
  const newResolveRequest = (context, moduleName, platform) => {
128
- // Handle Node.js built-in modules - return empty module stub
129
- if (NODE_BUILTINS.includes(moduleName)) {
147
+ // Handle Node built-ins and optional RN peers - return empty module stub
148
+ if (isMockifyerStubbedModule(moduleName)) {
130
149
  return {
131
150
  filePath: emptyModulePath,
132
151
  type: 'sourceFile',