@sgedda/mockifyer-fetch 1.8.106 → 1.8.108

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.
@@ -0,0 +1,1830 @@
1
+ /**
2
+ * Core MockifyerClass - browser and Node compatible via dependency injection.
3
+ * Only imports browser-safe utilities from @sgedda/mockifyer-core.
4
+ */
5
+
6
+ import { NodeCapabilities } from './node-capabilities';
7
+
8
+ // Browser-safe imports from core
9
+ import {
10
+ MockifyerConfig,
11
+ MockData,
12
+ StoredRequest,
13
+ StoredResponse,
14
+ HTTPClient,
15
+ HTTPResponse,
16
+ generateRequestKey as generateRequestKeyUtil,
17
+ CachedMockData,
18
+ DatabaseProvider,
19
+ MemoryProvider,
20
+ createProvider,
21
+ logger,
22
+ setLogLevel,
23
+ TestGenerator,
24
+ type TestGenerationOptions,
25
+ prepareMockResponseBody,
26
+ createServeTimeClock,
27
+ createServeTimePoolResponseLoader,
28
+ collectPoolRefIds,
29
+ arePoolRefsEnabled,
30
+ containsPoolRefs,
31
+ isUsableNodeLikePoolFs,
32
+ type PoolResponseItem,
33
+ shouldBypassMockifyerForUrl,
34
+ containsMockifyerSyncEndpointMarker,
35
+ isMockifyerDashboardPlumbingApiUrl,
36
+ resolveRecordingExclusions,
37
+ shouldExcludeRecording,
38
+ mockPassesThroughToRealApi,
39
+ mockShouldServeStoredBody,
40
+ mockShouldBeIncludedInRequestMatch,
41
+ buildClientResponseFromLiveCapture,
42
+ buildMockDataAfterLiveCapture,
43
+ resolveShouldPersistLiveCapture,
44
+ resolveMockRecordingSaveDecision,
45
+ applyRecordingPassthroughFlag,
46
+ resolveClientId,
47
+ resolveExplicitClientIdOnly,
48
+ resolveProxyStrictLaneScenario,
49
+ resolveActivationMode,
50
+ shouldApplyMockifyer,
51
+ isScenarioLaunchFromNativeArguments,
52
+ getCurrentScenario,
53
+ tryGetClientIdFromLaunchArguments,
54
+ MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
55
+ checkRequestLimit,
56
+ ensureOverrideGroupRuntimeForScenarioPath,
57
+ configureFlightRecorder,
58
+ resolveFlightRecorderConfig,
59
+ configureAtlas,
60
+ logMockifyerInitSummary,
61
+ resolveProxyUpstreamTlsInsecure,
62
+ unwrapAndMergeInlineTraceEnvelope,
63
+ unwrapInlineTraceEnvelopeEmittingNetworkEvents,
64
+ applyOutboundRequestCorrelation,
65
+ resolveNetworkLogIncludeTraceOptionsAsync,
66
+ emitMockifyerNetworkEvent,
67
+ stripMockifyerTraceFromBody,
68
+ resolveActiveMockifyerSessionId,
69
+ setFlightRecorderRuntimeContext,
70
+ getInlineTraceEnvelopeBusinessBody,
71
+ recordInlineTraceHopFromExchange,
72
+ outboundHeadersToRecord,
73
+ isExplicitProxyScenarioContext,
74
+ newRecordingUsesAlwaysUseRealApi,
75
+ shouldBlockLocalMockRecording,
76
+ resolveStrictScenarioResolution,
77
+ type MockifyerActivationMode,
78
+ resolveRecordResponses,
79
+ resolveLocalRecordResponses,
80
+ resolveLocalRecordResponsesForUrl,
81
+ buildLocalRecordingMockData,
82
+ adoptStoredOutboundRequestId,
83
+ resolvePersistedHopIds,
84
+ applyPersistedHopIds,
85
+ type RequestCorrelationContext,
86
+ DomainPathRulesSession,
87
+ resolveInitialRuntimeEnabled,
88
+ resolveRuntimeEnabledStorage,
89
+ savePersistedRuntimeEnabled,
90
+ type MockifyerRuntimeEnabledStorage,
91
+ appendParamsToUrl,
92
+ getMockFilePath,
93
+ formatDateStr,
94
+ getCurrentDate,
95
+ isMockRecordingSidecarDir,
96
+ } from '@sgedda/mockifyer-core';
97
+
98
+ import { mirrorProxyRecordingToClient } from './core-proxy';
99
+
100
+ // Local imports
101
+ import { FetchHTTPClient } from './clients/fetch-client';
102
+
103
+ // Lazy-load Node.js built-ins (static literal requires, bundler-safe)
104
+ function getFs(): typeof import('fs') | null {
105
+ // Only works in Node.js
106
+ if (typeof process === 'undefined' || !process.versions?.node) {
107
+ return null;
108
+ }
109
+ try {
110
+ // Static require with literal path - bundlers can stub this
111
+ return require('fs');
112
+ } catch {
113
+ return null;
114
+ }
115
+ }
116
+
117
+ function getPath(): typeof import('path') | null {
118
+ if (typeof process === 'undefined' || !process.versions?.node) {
119
+ return null;
120
+ }
121
+ try {
122
+ return require('path');
123
+ } catch {
124
+ return null;
125
+ }
126
+ }
127
+
128
+ export class MockifyerClass {
129
+ private config: MockifyerConfig;
130
+ private httpClient: HTTPClient;
131
+ private capabilities: NodeCapabilities;
132
+ private processingRequests: Set<string> = new Set();
133
+ private savingResponses: Set<string> = new Set();
134
+ private databaseProvider?: DatabaseProvider;
135
+ /** Resolves when async databaseProvider.initialize() completes (expo/hybrid). */
136
+ private databaseProviderInitPromise: Promise<void> = Promise.resolve();
137
+ private currentSessionId: string | null = null;
138
+ private sessionStartTime: number = 0;
139
+ private readonly SESSION_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
140
+ private testGenerator?: TestGenerator;
141
+ private readonly activationMode: MockifyerActivationMode;
142
+ /**
143
+ * Promoted pool responses for serve-time `$pool` resolve when Node `fs` is
144
+ * unavailable (React Native / Metro stubs). Seeded via {@link warmPoolResponseCache}.
145
+ */
146
+ private readonly poolResponseCache = new Map<string, PoolResponseItem>();
147
+ private readonly domainPathRules: DomainPathRulesSession;
148
+ /** Runtime toggle: when false, all Mockifyer logic is bypassed (no dashboard, Redis, proxy, or mock lookup). */
149
+ private runtimeEnabled: boolean;
150
+ /** Optional storage for persisting enable/disable across restarts. */
151
+ private readonly runtimeEnabledStorage?: MockifyerRuntimeEnabledStorage;
152
+ /**
153
+ * Runtime override for whether local/proxy recordings include response bodies.
154
+ * `undefined` = follow env / defaults ({@link resolveLocalRecordResponses} / {@link resolveRecordResponses}).
155
+ */
156
+ private recordResponsesOverride: boolean | undefined = undefined;
157
+
158
+ /** Session id for timeline hops — per-screen id from {@link setFlightRecorderRuntimeContext} when set. */
159
+ private getRuntimeSessionId(): string {
160
+ return resolveActiveMockifyerSessionId(() => {
161
+ const now = Date.now();
162
+ if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
163
+ this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
164
+ this.sessionStartTime = now;
165
+ setFlightRecorderRuntimeContext({ sessionId: this.currentSessionId });
166
+ }
167
+ return this.currentSessionId;
168
+ });
169
+ }
170
+
171
+ private unwrapResponseInlineTrace(response: {
172
+ data?: unknown;
173
+ config?: unknown;
174
+ }): void {
175
+ const correlation = this.readRequestCorrelation(response.config);
176
+ const parentRequestId = correlation?.requestId?.trim();
177
+ if (!parentRequestId) {
178
+ response.data = unwrapAndMergeInlineTraceEnvelope(response.data);
179
+ return;
180
+ }
181
+ const scenario =
182
+ this.config.proxy?.scenario?.trim() ||
183
+ this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId);
184
+ response.data = unwrapInlineTraceEnvelopeEmittingNetworkEvents(response.data, {
185
+ parentRequestId,
186
+ config: this.config,
187
+ scenario,
188
+ clientId: this.config.clientId,
189
+ sessionId: this.getRuntimeSessionId(),
190
+ transport: this.usesDashboardProxy() ? 'proxy' : 'fetch',
191
+ });
192
+ }
193
+
194
+ private async applyOutboundCorrelation(config: unknown): Promise<RequestCorrelationContext> {
195
+ return applyOutboundRequestCorrelation(
196
+ config as { headers?: unknown; url?: unknown; method?: unknown },
197
+ await resolveNetworkLogIncludeTraceOptionsAsync(this.config)
198
+ );
199
+ }
200
+
201
+ /**
202
+ * Full outbound URL including `params` — hop logs / Atlas curl / include-trace
203
+ * must not drop the query string (fetch splits search into `config.params`).
204
+ */
205
+ private resolveLoggedRequestUrl(
206
+ config?: { url?: string; params?: Record<string, unknown> } | null,
207
+ fallbackUrl?: string,
208
+ ): string {
209
+ const raw = (fallbackUrl || config?.url || '').trim();
210
+ if (!raw) return '';
211
+ return appendParamsToUrl(raw, config?.params);
212
+ }
213
+
214
+ /** Best-effort dashboard network log. */
215
+ private logNetworkEvent(
216
+ partial: Parameters<typeof emitMockifyerNetworkEvent>[0]['event'] & {
217
+ transport?: 'fetch' | 'proxy';
218
+ /** Raw bodies for inline-trace / network-log previews (stripped before emit). */
219
+ requestBody?: unknown;
220
+ responseBody?: unknown;
221
+ },
222
+ correlation?: RequestCorrelationContext,
223
+ /** Final outbound header bag (after auth interceptors). */
224
+ requestHeadersSource?: unknown
225
+ ): void {
226
+ const scenario =
227
+ this.config.proxy?.scenario?.trim() ||
228
+ this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId);
229
+
230
+ const { requestBody, responseBody, ...eventPartial } = partial;
231
+ const businessResponseBody = getInlineTraceEnvelopeBusinessBody(responseBody);
232
+ const requestHeaders =
233
+ eventPartial.requestHeaders ?? outboundHeadersToRecord(requestHeadersSource);
234
+
235
+ if (!this.config.proxy?.baseUrl) {
236
+ recordInlineTraceHopFromExchange({
237
+ method: eventPartial.method,
238
+ url: eventPartial.url,
239
+ status: eventPartial.status,
240
+ source: eventPartial.source,
241
+ transport: eventPartial.transport ?? 'fetch',
242
+ requestId: correlation?.requestId ?? eventPartial.requestId ?? null,
243
+ parentRequestId: correlation?.parentRequestId ?? eventPartial.parentRequestId ?? null,
244
+ durationMs: eventPartial.durationMs,
245
+ clientId: this.config.clientId ?? eventPartial.clientId ?? null,
246
+ errorMessage: eventPartial.errorMessage,
247
+ requestHeaders,
248
+ requestBody,
249
+ responseBody,
250
+ });
251
+ }
252
+
253
+ emitMockifyerNetworkEvent({
254
+ config: this.config,
255
+ scenario,
256
+ clientId: this.config.clientId,
257
+ sessionId: this.getRuntimeSessionId(),
258
+ requestBody,
259
+ responseBody: businessResponseBody,
260
+ event: {
261
+ ...eventPartial,
262
+ transport: eventPartial.transport ?? 'fetch',
263
+ requestId: correlation?.requestId ?? eventPartial.requestId,
264
+ parentRequestId: correlation?.parentRequestId ?? eventPartial.parentRequestId,
265
+ requestHeaders,
266
+ requestBodyPreview: eventPartial.requestBodyPreview,
267
+ responseBodyPreview: eventPartial.responseBodyPreview,
268
+ },
269
+ });
270
+ }
271
+
272
+ private stashRequestCorrelation(config: unknown, correlation: RequestCorrelationContext): void {
273
+ (config as { __mockifyer_requestId?: string; __mockifyer_parentRequestId?: string }).__mockifyer_requestId =
274
+ correlation.requestId;
275
+ (config as { __mockifyer_parentRequestId?: string }).__mockifyer_parentRequestId =
276
+ correlation.parentRequestId;
277
+ }
278
+
279
+ private bindStoredHopId(
280
+ config: unknown,
281
+ mockData: { requestId?: string } | undefined,
282
+ fallback?: RequestCorrelationContext
283
+ ): RequestCorrelationContext | undefined {
284
+ const adopted = adoptStoredOutboundRequestId(
285
+ config as { headers?: unknown },
286
+ mockData?.requestId
287
+ );
288
+ if (adopted) {
289
+ this.stashRequestCorrelation(config, adopted);
290
+ return adopted;
291
+ }
292
+ return fallback;
293
+ }
294
+
295
+ private readRequestCorrelation(config: unknown): RequestCorrelationContext | undefined {
296
+ const requestId = (config as { __mockifyer_requestId?: string }).__mockifyer_requestId;
297
+ if (!requestId) return undefined;
298
+ const parentRequestId = (config as { __mockifyer_parentRequestId?: string }).__mockifyer_parentRequestId;
299
+ return parentRequestId ? { requestId, parentRequestId } : { requestId };
300
+ }
301
+
302
+ /** Attach dashboard lookup id onto thrown fetch/client errors. */
303
+ private throwWithMockifyerRequestId(error: unknown): never {
304
+ const err = error as { config?: unknown; response?: { headers?: unknown }; mockifyerRequestId?: string };
305
+ const hopRequestId = (err?.config as { __mockifyer_requestId?: string } | undefined)?.__mockifyer_requestId;
306
+ if (hopRequestId) {
307
+ err.mockifyerRequestId = hopRequestId;
308
+ }
309
+ throw error;
310
+ }
311
+
312
+ /**
313
+ * Serve stored mock body with optional `$pool` resolution from the local fixture pool.
314
+ * Always passes `loadPoolResponse` — including React Native where Node `fs`/`path` are
315
+ * missing or Metro-stubbed — so `$pool` refs resolve via disk and/or {@link poolResponseCache}.
316
+ */
317
+ private prepareStoredResponseBody(mockData: MockData, filename?: string, scenarioPath?: string): unknown {
318
+ const fs = getFs();
319
+ const path = getPath();
320
+ const joinPath =
321
+ path && typeof path.join === 'function' ? path.join.bind(path) : null;
322
+ return prepareMockResponseBody(mockData, createServeTimeClock(this.config), {
323
+ loadPoolResponse: createServeTimePoolResponseLoader({
324
+ mockDataPath: this.config.mockDataPath,
325
+ nodeFs: isUsableNodeLikePoolFs(fs) ? fs : null,
326
+ joinPath,
327
+ cache: this.poolResponseCache,
328
+ }),
329
+ filename,
330
+ scenarioPath,
331
+ });
332
+ }
333
+
334
+ /**
335
+ * Ensure `$pool` fixtures are available in {@link poolResponseCache} when Node fs
336
+ * cannot load them (React Native). Tries database provider, then Metro.
337
+ */
338
+ private async warmPoolResponseCache(mockData: MockData): Promise<void> {
339
+ if (!arePoolRefsEnabled() || !containsPoolRefs(mockData.response?.data)) {
340
+ return;
341
+ }
342
+ const fs = getFs();
343
+ if (isUsableNodeLikePoolFs(fs)) {
344
+ return;
345
+ }
346
+
347
+ const ids = collectPoolRefIds(mockData.response.data);
348
+ for (const id of ids) {
349
+ if (this.poolResponseCache.has(id)) {
350
+ continue;
351
+ }
352
+ const fromProvider = await this.loadPoolResponseFromProvider(id);
353
+ if (fromProvider) {
354
+ this.poolResponseCache.set(id, fromProvider);
355
+ continue;
356
+ }
357
+ const fromMetro = await this.loadPoolResponseFromMetro(id);
358
+ if (fromMetro) {
359
+ this.poolResponseCache.set(id, fromMetro);
360
+ }
361
+ }
362
+ }
363
+
364
+ private async loadPoolResponseFromProvider(
365
+ id: string
366
+ ): Promise<PoolResponseItem | undefined> {
367
+ const provider = this.databaseProvider as
368
+ | { loadPoolResponseItem?: (poolId: string) => Promise<PoolResponseItem | undefined> | PoolResponseItem | undefined }
369
+ | undefined;
370
+ if (!provider || typeof provider.loadPoolResponseItem !== 'function') {
371
+ return undefined;
372
+ }
373
+ try {
374
+ return (await provider.loadPoolResponseItem(id)) ?? undefined;
375
+ } catch (error) {
376
+ logger.warn(`[Mockifyer-Fetch] Failed to load pool response "${id}" from provider:`, error);
377
+ return undefined;
378
+ }
379
+ }
380
+
381
+ private async loadPoolResponseFromMetro(
382
+ id: string
383
+ ): Promise<PoolResponseItem | undefined> {
384
+ const metroPort = this.config.databaseProvider?.options?.metroPort ?? 8081;
385
+ const originalFetch =
386
+ (global as { __mockifyer_original_fetch?: typeof fetch }).__mockifyer_original_fetch ||
387
+ (typeof fetch !== 'undefined' ? fetch : undefined);
388
+ if (!originalFetch) {
389
+ return undefined;
390
+ }
391
+ try {
392
+ const url = `http://localhost:${metroPort}/mockifyer-pool-response?id=${encodeURIComponent(id)}`;
393
+ const response = await originalFetch(url);
394
+ if (!response.ok) {
395
+ return undefined;
396
+ }
397
+ const payload = (await response.json()) as {
398
+ success?: boolean;
399
+ item?: PoolResponseItem;
400
+ };
401
+ if (payload.success && payload.item?.responseItemId && payload.item.response) {
402
+ return payload.item;
403
+ }
404
+ return undefined;
405
+ } catch (error) {
406
+ logger.warn(`[Mockifyer-Fetch] Failed to load pool response "${id}" from Metro:`, error);
407
+ return undefined;
408
+ }
409
+ }
410
+
411
+ constructor(config: MockifyerConfig, capabilities?: NodeCapabilities) {
412
+ // Import Node capabilities (static require, bundler handles via package.json exports)
413
+ if (!capabilities) {
414
+ // Static require with literal path - package.json browser field maps to .browser.ts
415
+ if (typeof require !== 'undefined') {
416
+ try {
417
+ const nodeModule = require('./node-capabilities.node');
418
+ this.capabilities = nodeModule.nodeCapabilities;
419
+ } catch (error) {
420
+ throw new Error(
421
+ '[Mockifyer] Failed to load node capabilities. ' +
422
+ 'In browser builds, pass capabilities explicitly or use the browser entry point. ' +
423
+ `Error: ${error}`
424
+ );
425
+ }
426
+ } else {
427
+ throw new Error(
428
+ '[Mockifyer] No capabilities provided and require() not available. ' +
429
+ 'In browser builds, pass capabilities explicitly or use the browser entry point.'
430
+ );
431
+ }
432
+ } else {
433
+ this.capabilities = capabilities;
434
+ }
435
+
436
+ // Validate database provider - filesystem, expo-filesystem, hybrid, and memory are supported
437
+ if (config.databaseProvider && config.databaseProvider.type) {
438
+ const supportedTypes = ['filesystem', 'expo-filesystem', 'hybrid', 'memory', 'redis', 'sqlite'];
439
+ if (!supportedTypes.includes(config.databaseProvider.type)) {
440
+ throw new Error(
441
+ `Database provider type '${config.databaseProvider.type}' is not yet available for use. ` +
442
+ `Supported types: ${supportedTypes.join(', ')}. ` +
443
+ `Please use one of the supported provider types.`
444
+ );
445
+ }
446
+ }
447
+
448
+ // Validate and normalize conflicting settings
449
+ if (config.recordMode && config.failOnMissingMock) {
450
+ logger.warn(
451
+ '[Mockifyer] Warning: recordMode is true but failOnMissingMock is also set to true. ' +
452
+ 'failOnMissingMock is ignored in record mode (real API calls are made to record responses). ' +
453
+ 'Setting failOnMissingMock to false.'
454
+ );
455
+ config.failOnMissingMock = false;
456
+ }
457
+
458
+ // Validate conflicting similar match settings
459
+ if (config.similarMatchIgnoreAllQueryParams &&
460
+ config.similarMatchRequiredParams &&
461
+ config.similarMatchRequiredParams.length > 0) {
462
+ logger.warn(
463
+ '[Mockifyer-Fetch] Warning: Both similarMatchIgnoreAllQueryParams and similarMatchRequiredParams are set. ' +
464
+ 'similarMatchIgnoreAllQueryParams takes precedence and all query parameters will be ignored. ' +
465
+ 'similarMatchRequiredParams will be ignored.'
466
+ );
467
+ // Clear similarMatchRequiredParams to avoid confusion
468
+ config.similarMatchRequiredParams = undefined;
469
+ }
470
+
471
+ // Auto-enable useSimilarMatch if similarMatchRequiredParams is set (and not ignored)
472
+ if (config.similarMatchRequiredParams && config.similarMatchRequiredParams.length > 0) {
473
+ if (config.useSimilarMatch === undefined || config.useSimilarMatch === false) {
474
+ config.useSimilarMatch = true;
475
+ }
476
+ }
477
+
478
+ // Auto-enable useSimilarMatch if similarMatchIgnoreAllQueryParams is set
479
+ if (config.similarMatchIgnoreAllQueryParams) {
480
+ if (config.useSimilarMatch === undefined || config.useSimilarMatch === false) {
481
+ config.useSimilarMatch = true;
482
+ }
483
+ }
484
+
485
+ let launchClientId: string | undefined;
486
+ if (config.useLaunchArgumentsClientId) {
487
+ const key = config.launchArgumentClientIdKey ?? MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY;
488
+ launchClientId = tryGetClientIdFromLaunchArguments(key);
489
+ if (launchClientId) {
490
+ logger.info(`[Mockifyer-Fetch] clientId from launch arguments (${key}): ${launchClientId}`);
491
+ }
492
+ }
493
+
494
+ // Store config BEFORE any modifications
495
+ this.config = { ...config }; // Create a copy to avoid mutations
496
+
497
+ // Launch arg wins over MOCKIFYER_CLIENT_ID / config.clientId when present (E2E).
498
+ // Strict proxy: no auto lane until explicit clientId / setClientId (devtools show real URLs).
499
+ if (launchClientId) {
500
+ this.config.clientId = launchClientId;
501
+ } else if (
502
+ resolveStrictScenarioResolution(this.config) &&
503
+ Boolean(this.config.proxy?.baseUrl?.trim())
504
+ ) {
505
+ this.config.clientId = resolveExplicitClientIdOnly(this.config);
506
+ } else {
507
+ this.config.clientId = resolveClientId(this.config);
508
+ }
509
+ this.activationMode = resolveActivationMode(this.config);
510
+ this.domainPathRules = new DomainPathRulesSession({
511
+ config: this.config,
512
+ getRecordMode: () => this.config.recordMode === true,
513
+ });
514
+
515
+ this.runtimeEnabledStorage = resolveRuntimeEnabledStorage(config.persistRuntimeEnabled);
516
+ if (config.persistRuntimeEnabled === true && !this.runtimeEnabledStorage) {
517
+ logger.warn(
518
+ '[Mockifyer-Fetch] persistRuntimeEnabled: true but no storage found. ' +
519
+ 'Install @react-native-async-storage/async-storage (RN) or use a custom { getItem, setItem }.'
520
+ );
521
+ }
522
+ this.runtimeEnabled = resolveInitialRuntimeEnabled({
523
+ initialRuntimeEnabled: config.initialRuntimeEnabled,
524
+ startDisabled: config.startDisabled,
525
+ runtimeMode: config.runtimeMode,
526
+ launchScenarioPresent: isScenarioLaunchFromNativeArguments(),
527
+ });
528
+
529
+ if (!this.runtimeEnabled) {
530
+ const reason =
531
+ typeof config.initialRuntimeEnabled === 'boolean'
532
+ ? 'persisted / initialRuntimeEnabled: false'
533
+ : config.runtimeMode === 'manual'
534
+ ? 'runtimeMode: "manual"'
535
+ : 'startDisabled: true';
536
+ logger.info(
537
+ `[Mockifyer-Fetch] Starting with Mockifyer DISABLED (${reason}). Call enableMockifyer() to activate.`
538
+ );
539
+ } else if (isScenarioLaunchFromNativeArguments()) {
540
+ logger.info(
541
+ '[Mockifyer-Fetch] Starting with Mockifyer ENABLED (native launch scenario argument).'
542
+ );
543
+ } else if (typeof config.initialRuntimeEnabled === 'boolean' && config.initialRuntimeEnabled) {
544
+ logger.info(
545
+ '[Mockifyer-Fetch] Starting with Mockifyer ENABLED (restored from persisted preference).'
546
+ );
547
+ }
548
+
549
+ configureFlightRecorder(resolveFlightRecorderConfig(this.config));
550
+ configureAtlas(this.config, {
551
+ scenario: this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId),
552
+ clientId: this.config.clientId ?? null,
553
+ });
554
+ setFlightRecorderRuntimeContext({
555
+ clientId: this.config.clientId,
556
+ scenario: this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId),
557
+ });
558
+
559
+ if (this.config.proxy?.baseUrl && this.config.proxy.mirrorRecordedMocksToClient === undefined) {
560
+ const raw =
561
+ typeof process !== 'undefined'
562
+ ? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
563
+ : '';
564
+ if (raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on') {
565
+ this.config.proxy = { ...this.config.proxy, mirrorRecordedMocksToClient: true };
566
+ }
567
+ }
568
+
569
+ // Initialize test generator if test generation is enabled
570
+ if (config.generateTests?.enabled) {
571
+ this.testGenerator = new TestGenerator();
572
+ }
573
+
574
+ // Initialize database provider if specified
575
+ if (config.databaseProvider && config.databaseProvider.type) {
576
+ const providerConfig = {
577
+ ...config.databaseProvider,
578
+ options: {
579
+ ...config.databaseProvider.options,
580
+ mockDataPath:
581
+ config.databaseProvider.options?.mockDataPath ?? config.mockDataPath,
582
+ clientId: this.config.clientId,
583
+ getClientId: () => this.config.clientId,
584
+ },
585
+ };
586
+ this.databaseProvider = createProvider(config.databaseProvider.type, providerConfig);
587
+ const initResult = this.databaseProvider.initialize();
588
+ // Handle async initialization (expo-filesystem / hybrid providers)
589
+ if (initResult instanceof Promise) {
590
+ this.databaseProviderInitPromise = initResult.catch((error) => {
591
+ logger.error('[Mockifyer-Fetch] Error initializing database provider:', error);
592
+ });
593
+ }
594
+ } else {
595
+ // Fallback to Node.js filesystem
596
+ this.ensureMockDataDirectory();
597
+ }
598
+
599
+ // Create fetch HTTP client
600
+ this.httpClient = new FetchHTTPClient({
601
+ baseUrl: config.baseUrl,
602
+ defaultHeaders: config.defaultHeaders,
603
+ proxy: config.proxy,
604
+ clientId: this.config.clientId,
605
+ getClientId: () => this.config.clientId,
606
+ getStrictLaneScenario: () => resolveProxyStrictLaneScenario(this.config),
607
+ getUpstreamTlsInsecure: () => resolveProxyUpstreamTlsInsecure(this.config),
608
+ getExplicitProxyScenarioContext: () => isExplicitProxyScenarioContext(this.config),
609
+ getShouldRecordStreams: () =>
610
+ this.config.recordMode === true && !this.config.proxy?.baseUrl,
611
+ getStreamRecordCaps: () => ({
612
+ maxBytes: this.config.streamRecordMaxBytes,
613
+ maxDurationMs: this.config.streamRecordMaxDurationMs,
614
+ }),
615
+ deviceId: (this.config as any).deviceId,
616
+ });
617
+
618
+ if(!config.recordSameEndpoints) {
619
+ this.loadMockData();
620
+ }
621
+ // Always set up mock response interceptor (to use existing mocks)
622
+ this.setupMockResponses();
623
+
624
+ // Set up response interceptor to save responses when recordMode is enabled
625
+ this.setupResponseInterceptor();
626
+
627
+ logMockifyerInitSummary(this.config, {
628
+ runtimeMode: this.config.runtimeMode,
629
+ headline: this.config.initLog?.headline,
630
+ });
631
+ }
632
+
633
+ private ensureMockDataDirectory(): void {
634
+ const fs = getFs();
635
+ // Only use fs if available (Node.js environment) and no database provider is set
636
+ if (!fs || this.databaseProvider) {
637
+ return;
638
+ }
639
+ if (!fs.existsSync(this.config.mockDataPath)) {
640
+ fs.mkdirSync(this.config.mockDataPath, { recursive: true });
641
+ }
642
+ }
643
+
644
+ private generateRequestKey(request: StoredRequest): string {
645
+ return generateRequestKeyUtil(request);
646
+ }
647
+
648
+ /** When set, mock resolution happens on the dashboard `/api/proxy` (Redis/disk), not local `mock-data`. */
649
+ private usesDashboardProxy(): boolean {
650
+ const baseUrl = this.config.proxy?.baseUrl;
651
+ return typeof baseUrl === 'string' && baseUrl.trim().length > 0;
652
+ }
653
+
654
+ private async findBestMatchingMock(
655
+ request: StoredRequest,
656
+ options?: { includePassthroughMocks?: boolean }
657
+ ): Promise<CachedMockData | undefined> {
658
+ // CRITICAL: Never try to match sync endpoint requests - they should never be mocked
659
+ const requestUrl = request?.url || '';
660
+ if (containsMockifyerSyncEndpointMarker(requestUrl)) {
661
+ return undefined;
662
+ }
663
+
664
+ const requestKey = this.generateRequestKey(request);
665
+
666
+ // CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
667
+ if (containsMockifyerSyncEndpointMarker(requestKey)) {
668
+ return undefined;
669
+ }
670
+
671
+ // Use database provider if available, otherwise fallback to filesystem
672
+ if (this.databaseProvider) {
673
+ return await this.findBestMatchingMockFromProvider(request, options);
674
+ }
675
+ // Fallback to Node.js filesystem
676
+ return this.findBestMatchingMockFromFiles(request, options);
677
+ }
678
+
679
+ private async findBestMatchingMockFromProvider(
680
+ request: StoredRequest,
681
+ options?: { includePassthroughMocks?: boolean }
682
+ ): Promise<CachedMockData | undefined> {
683
+ if (!this.databaseProvider) {
684
+ return undefined;
685
+ }
686
+
687
+ // CRITICAL: Never try to match sync endpoint requests - they should never be mocked
688
+ const requestUrl = request?.url || '';
689
+ if (containsMockifyerSyncEndpointMarker(requestUrl)) {
690
+ return undefined;
691
+ }
692
+
693
+ const requestKey = this.generateRequestKey(request);
694
+
695
+ // CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
696
+ if (containsMockifyerSyncEndpointMarker(requestKey)) {
697
+ return undefined;
698
+ }
699
+
700
+ // Try exact match first
701
+ const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey, options);
702
+ if (exactMatch) {
703
+ return exactMatch;
704
+ }
705
+
706
+ // Try similar match if enabled
707
+ if (this.config.useSimilarMatch) {
708
+ const similarMatches = await this.databaseProvider.findAllForSimilarMatch(request);
709
+ if (similarMatches && similarMatches.length > 0) {
710
+ // Return first similar match
711
+ return similarMatches[0];
712
+ }
713
+ }
714
+
715
+ return undefined;
716
+ }
717
+
718
+ private getAllJsonFiles(dir: string): string[] {
719
+ const fs = getFs();
720
+ const path = getPath();
721
+ if (!fs || !path || !fs.existsSync(dir)) return [];
722
+ const results: string[] = [];
723
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
724
+ const fullPath = path.join(dir, entry.name);
725
+ if (entry.isDirectory()) {
726
+ if (isMockRecordingSidecarDir(entry.name)) {
727
+ continue;
728
+ }
729
+ results.push(...this.getAllJsonFiles(fullPath));
730
+ } else if (entry.name.endsWith('.json')) {
731
+ results.push(fullPath);
732
+ }
733
+ }
734
+ return results;
735
+ }
736
+
737
+ private findBestMatchingMockFromFiles(
738
+ request: StoredRequest,
739
+ options?: { includePassthroughMocks?: boolean }
740
+ ): CachedMockData | undefined {
741
+ const fs = getFs();
742
+ const path = getPath();
743
+ const includePassthroughMocks = options?.includePassthroughMocks === true;
744
+ // Only use fs if available (Node.js environment)
745
+ // This method should never be called when using a database provider
746
+ if (!fs || !path) {
747
+ return undefined;
748
+ }
749
+ const resolvedMockDataPath = path.resolve(this.config.mockDataPath);
750
+
751
+ if (!fs.existsSync(resolvedMockDataPath)) {
752
+ console.warn('[Mockifyer-Fetch] ⚠️ Mock data path does not exist:', resolvedMockDataPath);
753
+ return undefined;
754
+ }
755
+
756
+ const currentScenario = this.capabilities.getCurrentScenario(resolvedMockDataPath, this.config.clientId);
757
+ const scenarioPath = this.capabilities.getScenarioFolderPath(resolvedMockDataPath, currentScenario);
758
+ ensureOverrideGroupRuntimeForScenarioPath(scenarioPath, { clientId: this.config.clientId });
759
+
760
+ if (!fs.existsSync(scenarioPath)) {
761
+ logger.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
762
+ return undefined;
763
+ }
764
+
765
+ const files = this.getAllJsonFiles(scenarioPath);
766
+
767
+ const requestKey = this.generateRequestKey(request);
768
+ let exactMatch: CachedMockData | undefined;
769
+ let similarMatch: CachedMockData | undefined;
770
+
771
+ for (const filePath of files) {
772
+ try {
773
+ const fileContent = fs.readFileSync(filePath, 'utf-8');
774
+ const mockData: MockData = JSON.parse(fileContent);
775
+
776
+ if (!mockData || !mockData.request || typeof mockData.request !== 'object') {
777
+ continue;
778
+ }
779
+
780
+ const mockKey = this.generateRequestKey(mockData.request);
781
+ const filename = path.relative(scenarioPath, filePath);
782
+
783
+ if (mockKey === requestKey) {
784
+ if (
785
+ mockShouldBeIncludedInRequestMatch(mockData, {
786
+ includePassthroughMocks,
787
+ filename,
788
+ scenarioPath,
789
+ })
790
+ ) {
791
+ exactMatch = { mockData, filename, filePath };
792
+ break;
793
+ }
794
+ continue;
795
+ }
796
+
797
+ if (!exactMatch && this.config.useSimilarMatch && !similarMatch) {
798
+ // Check if it's a GraphQL request - skip similar matching for GraphQL
799
+ const isGraphQL = ['POST', 'PUT', 'PATCH'].includes((request.method || 'GET').toUpperCase()) &&
800
+ request.data &&
801
+ (() => {
802
+ try {
803
+ let bodyData = request.data;
804
+ if (typeof request.data === 'string') {
805
+ bodyData = JSON.parse(request.data);
806
+ }
807
+ return typeof bodyData === 'object' && bodyData !== null && typeof bodyData.query === 'string';
808
+ } catch {
809
+ return false;
810
+ }
811
+ })();
812
+
813
+ if (!isGraphQL) {
814
+ try {
815
+ const requestUrl = new URL(request.url);
816
+ const mockUrl = new URL(mockData.request.url);
817
+
818
+ // Check if pathnames match (exact or pattern-based)
819
+ const requestPathname = requestUrl.pathname;
820
+ const mockPathname = mockUrl.pathname;
821
+ const methodMatch = (mockData.request.method || 'GET').toUpperCase() === (request.method || 'GET').toUpperCase();
822
+
823
+ // Check for exact pathname match
824
+ const exactPathnameMatch = mockPathname === requestPathname;
825
+
826
+ // Check for pattern-based match
827
+ let patternMatch = false;
828
+ if (this.config.similarMatchIgnoreAllQueryParams && !exactPathnameMatch && methodMatch) {
829
+ const requestSegments = requestPathname.split('/').filter(s => s);
830
+ const mockSegments = mockPathname.split('/').filter(s => s);
831
+
832
+ if (requestSegments.length === mockSegments.length && requestSegments.length > 0) {
833
+ const requestBase = requestSegments.slice(0, -1);
834
+ const mockBase = mockSegments.slice(0, -1);
835
+ patternMatch = requestBase.join('/') === mockBase.join('/');
836
+ }
837
+ }
838
+
839
+ const pathnameMatch = exactPathnameMatch || patternMatch;
840
+
841
+ if (pathnameMatch && methodMatch) {
842
+
843
+ // If ignoreAllQueryParams is set, skip query param checking entirely
844
+ if (this.config.similarMatchIgnoreAllQueryParams) {
845
+ // Ignore all query params, match on path and method only
846
+ } else if (this.config.similarMatchRequiredParams && this.config.similarMatchRequiredParams.length > 0) {
847
+ // Check if required parameters match (if configured)
848
+ const requestParams = request.queryParams || {};
849
+ const mockParams = mockData.request.queryParams || {};
850
+
851
+ const allRequiredMatch = this.config.similarMatchRequiredParams.every((paramName: string) => {
852
+ const requestValue = requestParams[paramName];
853
+ const mockValue = mockParams[paramName];
854
+ return requestValue === undefined && mockValue === undefined
855
+ ? true
856
+ : String(requestValue || '') === String(mockValue || '');
857
+ });
858
+
859
+ if (!allRequiredMatch) {
860
+ continue; // Required parameter differs, skip this mock
861
+ }
862
+ }
863
+
864
+ if (
865
+ mockShouldBeIncludedInRequestMatch(mockData, {
866
+ includePassthroughMocks,
867
+ filename,
868
+ scenarioPath,
869
+ })
870
+ ) {
871
+ similarMatch = { mockData, filename, filePath };
872
+ }
873
+ }
874
+ } catch (e) {
875
+ continue;
876
+ }
877
+ }
878
+ }
879
+ } catch (error) {
880
+ logger.warn(`[Mockifyer] Failed to load mock file ${filePath}:`, error);
881
+ }
882
+ }
883
+
884
+ return exactMatch || similarMatch;
885
+ }
886
+
887
+ private loadMockData(): void {
888
+ const fs = getFs();
889
+ // Skip if using database provider or fs not available
890
+ if (this.databaseProvider || !fs) {
891
+ return;
892
+ }
893
+ if (fs.existsSync(this.config.mockDataPath)) {
894
+ fs.readdirSync(this.config.mockDataPath)
895
+ .filter(file => file.endsWith('.json'));
896
+ }
897
+ }
898
+
899
+ private setupMockResponses(): void {
900
+ this.httpClient.interceptors.request.use(async (config: any) => {
901
+ // CRITICAL: Runtime toggle — if disabled, bypass all Mockifyer logic
902
+ if (!this.runtimeEnabled) {
903
+ (config as any).__mockifyer_bypass = true;
904
+ return config;
905
+ }
906
+
907
+ // CRITICAL: Completely bypass Mockifyer interception for sync endpoints
908
+ const url = config.url || '';
909
+ if (containsMockifyerSyncEndpointMarker(url)) {
910
+ (config as any).__mockifyer_skip_save = true;
911
+ (config as any).__mockifyer_bypass = true;
912
+ return config;
913
+ }
914
+
915
+ if (shouldBypassMockifyerForUrl(url, this.config.excludedUrls, this.config.baseUrl)) {
916
+ (config as any).__mockifyer_bypass = true;
917
+ return config;
918
+ }
919
+
920
+ if (!shouldApplyMockifyer(this.activationMode, config.headers)) {
921
+ (config as any).__mockifyer_bypass = true;
922
+ return config;
923
+ }
924
+
925
+ if (!isExplicitProxyScenarioContext(this.config)) {
926
+ logger.warn(
927
+ '[Mockifyer-Fetch] Strict proxy scenario: set clientId (lane) or proxy.scenario; passthrough HTTP for this request'
928
+ );
929
+ (config as any).__mockifyer_bypass = true;
930
+ return config;
931
+ }
932
+
933
+ let correlation = await this.applyOutboundCorrelation(config);
934
+ this.stashRequestCorrelation(config, correlation);
935
+
936
+ // Normalize empty params: treat {} the same as undefined for consistent matching
937
+ const rawParams = config.params || {};
938
+ const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
939
+ const normalizedParams = anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
940
+ ? anonymizedQueryParams
941
+ : undefined;
942
+
943
+ const request: StoredRequest = {
944
+ method: config.method || 'GET',
945
+ url: config.url || '',
946
+ headers: config.headers || {},
947
+ data: config.data,
948
+ queryParams: normalizedParams
949
+ };
950
+
951
+ const requestKey = this.generateRequestKey(request);
952
+
953
+ // Store request key for response interceptor
954
+ (config as any).__mockifyer_requestKey = requestKey;
955
+ // Store request start time for duration calculation
956
+ (config as any).__mockifyer_startTime = Date.now();
957
+
958
+ // Dashboard proxy owns mock hits (Redis + server-side disk fallback). Do not short-circuit
959
+ // from local mock-data while proxy.baseUrl is configured — that bypasses /api/proxy entirely.
960
+ if (this.usesDashboardProxy()) {
961
+ return config;
962
+ }
963
+
964
+ this.domainPathRules.discover(request.url, this.config.baseUrl);
965
+ const trafficGate = this.domainPathRules.getTrafficGate(request.url, this.config.baseUrl);
966
+ (config as any).__mockifyer_domain_path_may_record = trafficGate.mayRecord;
967
+ if (!trafficGate.mayReplay) {
968
+ logger.debug(
969
+ `[Mockifyer-Fetch] Domain path rules: replay denied for ${request.method} ${request.url}` +
970
+ (trafficGate.matchedDomainPath ? ` (rule: ${trafficGate.matchedDomainPath})` : ' (allowlist unmatched)')
971
+ );
972
+ return config;
973
+ }
974
+
975
+ const cachedMock = await this.findBestMatchingMock(request);
976
+
977
+ // Return cached mock if found
978
+
979
+ if (cachedMock) {
980
+ const { mockData, filename, filePath } = cachedMock;
981
+ correlation = this.bindStoredHopId(config, mockData, correlation) ?? correlation;
982
+ if (mockShouldServeStoredBody(mockData)) {
983
+ logger.info(
984
+ `[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
985
+ (filePath ? ` (${filePath})` : '')
986
+ );
987
+ const path = getPath();
988
+ const hitScenarioPath = path
989
+ ? this.capabilities.getScenarioFolderPath(
990
+ path.resolve(this.config.mockDataPath),
991
+ this.capabilities.getCurrentScenario(path.resolve(this.config.mockDataPath), this.config.clientId)
992
+ )
993
+ : undefined;
994
+ if (hitScenarioPath) {
995
+ ensureOverrideGroupRuntimeForScenarioPath(hitScenarioPath, { clientId: this.config.clientId });
996
+ }
997
+
998
+ if (mockData.responseDelayMs && mockData.responseDelayMs > 0) {
999
+ await new Promise(resolve => setTimeout(resolve, mockData.responseDelayMs));
1000
+ }
1001
+
1002
+ const mockResponseBody = this.prepareStoredResponseBody(mockData, filename, hitScenarioPath);
1003
+ const effectiveStatus = mockData.statusOverride ?? mockData.response.status;
1004
+ this.logNetworkEvent(
1005
+ {
1006
+ method: (request.method || 'GET').toUpperCase(),
1007
+ url: this.resolveLoggedRequestUrl(config, request.url),
1008
+ source: 'mock-hit',
1009
+ status: effectiveStatus,
1010
+ requestBody: request.data,
1011
+ responseBody: mockResponseBody,
1012
+ },
1013
+ correlation,
1014
+ request.headers ?? config.headers
1015
+ );
1016
+ const responseHeaders = {
1017
+ ...mockData.response.headers,
1018
+ 'x-mockifyer': 'true',
1019
+ 'x-mockifyer-timestamp': mockData.timestamp,
1020
+ 'x-mockifyer-filename': filename,
1021
+ 'x-mockifyer-filepath': filePath
1022
+ };
1023
+
1024
+ await this.warmPoolResponseCache(mockData);
1025
+
1026
+ const mockResponse: HTTPResponse = {
1027
+ data: mockResponseBody,
1028
+ status: effectiveStatus,
1029
+ statusText: 'OK',
1030
+ headers: responseHeaders,
1031
+ config: config as any,
1032
+ ...(mockData.response.stream
1033
+ ? { mockifyerStoredStream: mockData.response.stream }
1034
+ : {}),
1035
+ };
1036
+
1037
+ return {
1038
+ ...config,
1039
+ __mockResponse: Promise.resolve(mockResponse),
1040
+ __mockifyer_requestKey: requestKey
1041
+ } as any;
1042
+ }
1043
+
1044
+ logger.info(
1045
+ `[Mockifyer-Fetch] Live refresh: ${request.method} ${request.url} → ${filename}` +
1046
+ (filePath ? ` (${filePath})` : '')
1047
+ );
1048
+ (config as any).__mockifyer_matchedMock = cachedMock;
1049
+ }
1050
+
1051
+ // Check request limit BEFORE making real API call (only if no mock found and in record mode)
1052
+ if (this.config.recordMode) {
1053
+ const limitCheck = checkRequestLimit(this.config.mockDataPath);
1054
+ if (limitCheck.limitReached && limitCheck.error) {
1055
+ console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
1056
+
1057
+ const responseHeaders = {
1058
+ 'x-mockifyer': 'true',
1059
+ 'x-mockifyer-limit-reached': 'true',
1060
+ 'content-type': 'application/json'
1061
+ };
1062
+
1063
+ const mockErrorResponse = {
1064
+ data: {
1065
+ error: limitCheck.error.message,
1066
+ message: limitCheck.error.message,
1067
+ limitReached: true,
1068
+ maxRequests: limitCheck.error.maxRequests,
1069
+ currentScenario: limitCheck.error.currentScenario
1070
+ },
1071
+ status: 429,
1072
+ statusText: 'Too Many Requests',
1073
+ headers: responseHeaders,
1074
+ config: config as any
1075
+ };
1076
+
1077
+ return {
1078
+ ...config,
1079
+ __mockResponse: Promise.resolve(mockErrorResponse),
1080
+ __mockifyer_requestKey: requestKey,
1081
+ __mockifyer_limit_reached: true
1082
+ } as any;
1083
+ }
1084
+ }
1085
+
1086
+ if (this.config.failOnMissingMock) {
1087
+ const scenario = this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId);
1088
+ const requestKey = this.generateRequestKey(request);
1089
+ throw new Error(
1090
+ `No mock data found for request: ${requestKey}\n` +
1091
+ `\n` +
1092
+ `Scenario: ${scenario}\n` +
1093
+ `Request key: ${requestKey}\n` +
1094
+ `\n` +
1095
+ `In replay mode with failOnMissingMock=true, all requests must have recorded mocks.\n` +
1096
+ `To fix:\n` +
1097
+ ` 1. Record this request: set recordMode: true\n` +
1098
+ ` 2. Or preload fixture: databaseProvider: { type: 'memory', options: { fixtures: [...] } }\n` +
1099
+ ` 3. Or allow passthrough: set failOnMissingMock: false`
1100
+ );
1101
+ }
1102
+
1103
+ return config;
1104
+ });
1105
+ }
1106
+
1107
+ private setupResponseInterceptor(): void {
1108
+ this.httpClient.interceptors.response.use(
1109
+ async (response: any) => {
1110
+ // CRITICAL: Check for skip flag FIRST
1111
+ if ((response.config as any).__mockifyer_skip_save || (response.config as any).__mockifyer_bypass) {
1112
+ return response;
1113
+ }
1114
+
1115
+ // Clean up processing requests tracking
1116
+ const requestKey = (response.config as any).__mockifyer_requestKey;
1117
+ if (requestKey) {
1118
+ this.processingRequests.delete(requestKey);
1119
+ }
1120
+
1121
+ const isMocked = response.headers && (response.headers as any)['x-mockifyer'] === 'true';
1122
+ const isLimitReached = response.headers && (response.headers as any)['x-mockifyer-limit-reached'] === 'true';
1123
+ if (isMocked || isLimitReached) {
1124
+ const shouldLogMockOrLimit =
1125
+ isLimitReached || (isMocked && this.usesDashboardProxy());
1126
+ if (shouldLogMockOrLimit) {
1127
+ const url = response.config?.url || (response as any).request?.responseURL || (response as any).url || '';
1128
+ const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
1129
+ const reqMethod = (response.config?.method || 'GET').toUpperCase();
1130
+ const startTime = (response.config as any).__mockifyer_startTime;
1131
+ const durationMs = startTime ? Date.now() - startTime : undefined;
1132
+ this.logNetworkEvent(
1133
+ {
1134
+ method: reqMethod,
1135
+ url: reqUrl,
1136
+ source: isLimitReached ? 'error' : 'mock-hit',
1137
+ status: response.status,
1138
+ durationMs,
1139
+ transport: this.usesDashboardProxy() ? 'proxy' : 'fetch',
1140
+ requestBody: response.config?.data,
1141
+ responseBody: response.data,
1142
+ ...(isLimitReached
1143
+ ? {
1144
+ errorMessage:
1145
+ typeof response.data === 'object' &&
1146
+ response.data !== null &&
1147
+ 'message' in response.data
1148
+ ? String((response.data as { message?: unknown }).message)
1149
+ : 'Request limit reached',
1150
+ }
1151
+ : {}),
1152
+ },
1153
+ this.readRequestCorrelation(response.config),
1154
+ response.config?.headers
1155
+ );
1156
+ }
1157
+ // Mock hits return before the upstream path
1158
+ this.unwrapResponseInlineTrace(response);
1159
+ return response;
1160
+ }
1161
+
1162
+ if (this.config.proxy?.baseUrl && this.config.proxy?.mirrorRecordedMocksToClient) {
1163
+ await this.maybeMirrorProxyRecordingToClient(response);
1164
+ }
1165
+
1166
+ const matchedMock = (response.config as any).__mockifyer_matchedMock as CachedMockData | undefined;
1167
+ if (matchedMock) {
1168
+ const startTime = (response.config as any).__mockifyer_startTime;
1169
+ const durationMs = startTime ? Date.now() - startTime : undefined;
1170
+
1171
+ const url = response.config?.url || (response as any).request?.responseURL || (response as any).url || '';
1172
+ const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
1173
+ const reqMethod = (response.config?.method || 'GET').toUpperCase();
1174
+ this.logNetworkEvent(
1175
+ {
1176
+ method: reqMethod,
1177
+ url: reqUrl,
1178
+ source: 'upstream',
1179
+ status: response.status,
1180
+ durationMs,
1181
+ requestBody: response.config?.data,
1182
+ responseBody: response.data,
1183
+ },
1184
+ this.readRequestCorrelation(response.config),
1185
+ response.config?.headers
1186
+ );
1187
+ this.unwrapResponseInlineTrace(response);
1188
+
1189
+ const capturedResponse: StoredResponse = {
1190
+ status: response.status,
1191
+ data: stripMockifyerTraceFromBody(response.data),
1192
+ headers: (response.headers as Record<string, string>) || {},
1193
+ };
1194
+
1195
+ if (resolveShouldPersistLiveCapture(matchedMock.mockData, this.config)) {
1196
+ await this.persistMatchedMockAfterLiveCapture(
1197
+ matchedMock,
1198
+ capturedResponse,
1199
+ durationMs,
1200
+ this.readRequestCorrelation(response.config)
1201
+ );
1202
+ }
1203
+
1204
+ const path = getPath();
1205
+ const liveScenarioPath = path
1206
+ ? this.capabilities.getScenarioFolderPath(
1207
+ path.resolve(this.config.mockDataPath),
1208
+ this.capabilities.getCurrentScenario(path.resolve(this.config.mockDataPath), this.config.clientId)
1209
+ )
1210
+ : undefined;
1211
+ if (liveScenarioPath) {
1212
+ ensureOverrideGroupRuntimeForScenarioPath(liveScenarioPath, { clientId: this.config.clientId });
1213
+ }
1214
+ const clientResponse = buildClientResponseFromLiveCapture(
1215
+ matchedMock.mockData,
1216
+ capturedResponse,
1217
+ createServeTimeClock(this.config),
1218
+ { filename: matchedMock.filename, scenarioPath: liveScenarioPath }
1219
+ );
1220
+ response.data = clientResponse.data;
1221
+ response.status = clientResponse.status;
1222
+ delete (response.config as any).__mockifyer_matchedMock;
1223
+
1224
+ return response;
1225
+ }
1226
+
1227
+ const url = response.config?.url || (response as any).request?.responseURL || (response as any).url || '';
1228
+ const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
1229
+ const reqMethod = (response.config?.method || 'GET').toUpperCase();
1230
+ this.logNetworkEvent(
1231
+ {
1232
+ method: reqMethod,
1233
+ url: reqUrl,
1234
+ source: 'upstream',
1235
+ status: response.status,
1236
+ durationMs:
1237
+ typeof response.config?.metadata?.durationMs === 'number'
1238
+ ? response.config.metadata.durationMs
1239
+ : undefined,
1240
+ requestBody: response.config?.data,
1241
+ responseBody:
1242
+ typeof ReadableStream !== 'undefined' && response.data instanceof ReadableStream
1243
+ ? '[stream]'
1244
+ : response.data,
1245
+ },
1246
+ this.readRequestCorrelation(response.config),
1247
+ response.config?.headers
1248
+ );
1249
+ this.unwrapResponseInlineTrace(response);
1250
+
1251
+ // Only save locally if recordMode is enabled AND we're not proxying upstream calls.
1252
+ if (this.config.recordMode && !this.config.proxy?.baseUrl) {
1253
+ if (response.mockifyerStreamRecording) {
1254
+ // Do not await recording — the caller already has the live stream.
1255
+ // Persist once the recording branch finishes (caps / EOF).
1256
+ void this.saveStreamRecording(response).catch((err) => {
1257
+ logger.error('[Mockifyer-Fetch] Failed to save stream recording:', err);
1258
+ });
1259
+ } else {
1260
+ await this.saveResponse(response);
1261
+ }
1262
+ }
1263
+
1264
+ return response;
1265
+ },
1266
+ async (error: any) => {
1267
+ const requestKey = (error.config as any)?.__mockifyer_requestKey;
1268
+ if (requestKey) {
1269
+ this.processingRequests.delete(requestKey);
1270
+ }
1271
+ const reqUrl = this.resolveLoggedRequestUrl(error.config);
1272
+ if (reqUrl) {
1273
+ this.logNetworkEvent(
1274
+ {
1275
+ method: (error.config?.method || 'GET').toUpperCase(),
1276
+ url: reqUrl,
1277
+ source: 'error',
1278
+ status: error.response?.status,
1279
+ errorMessage: error?.message ?? String(error),
1280
+ requestBody: error.config?.data,
1281
+ responseBody: error.response?.data,
1282
+ },
1283
+ this.readRequestCorrelation(error.config),
1284
+ error.config?.headers
1285
+ );
1286
+ }
1287
+ this.throwWithMockifyerRequestId(error);
1288
+ }
1289
+ );
1290
+ }
1291
+
1292
+ private async maybeMirrorProxyRecordingToClient(response: HTTPResponse): Promise<void> {
1293
+ const rec = response.mockifyerProxyRecording;
1294
+ if (!rec?.recordedToStore || !rec.storedMock) {
1295
+ return;
1296
+ }
1297
+ const hash = rec.hash?.trim();
1298
+ const scenarioName = rec.scenarioName?.trim();
1299
+ const mockData = rec.storedMock as MockData;
1300
+ const providerType = this.config.databaseProvider?.type;
1301
+
1302
+ await mirrorProxyRecordingToClient({
1303
+ config: this.config,
1304
+ mockDataPath: this.config.mockDataPath,
1305
+ recording: rec,
1306
+ databaseProvider: this.databaseProvider,
1307
+ databaseProviderInitPromise: this.databaseProviderInitPromise,
1308
+ logPrefix: 'Mockifyer-Fetch',
1309
+ });
1310
+
1311
+ const fs = getFs();
1312
+ if (providerType === 'hybrid' && hash && scenarioName && mockData) {
1313
+ await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
1314
+ } else if (!fs && hash && scenarioName && mockData) {
1315
+ await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
1316
+ }
1317
+ }
1318
+
1319
+ private async tryMirrorProxyRecordingViaMetro(
1320
+ mockData: MockData,
1321
+ scenarioName: string,
1322
+ hash: string
1323
+ ): Promise<void> {
1324
+ const metroPort = process.env.METRO_PORT ? parseInt(process.env.METRO_PORT, 10) : 8081;
1325
+ const fetchFn = (global as any).__mockifyer_original_fetch || fetch;
1326
+ if (!fetchFn) {
1327
+ logger.warn('[Mockifyer-Fetch] Proxy client mirror: no fetch for Metro save');
1328
+ return;
1329
+ }
1330
+ try {
1331
+ const body = JSON.stringify({
1332
+ __mockifyerProxyMirror: true,
1333
+ mockData,
1334
+ scenarioName,
1335
+ relativePath: `redis/${hash}.json`,
1336
+ });
1337
+ const res = await fetchFn(`http://localhost:${metroPort}/mockifyer-save`, {
1338
+ method: 'POST',
1339
+ headers: { 'Content-Type': 'application/json' },
1340
+ body,
1341
+ });
1342
+ const text = await res.text().catch(() => '');
1343
+ if (!res.ok) {
1344
+ logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): HTTP ${res.status} ${text}`);
1345
+ return;
1346
+ }
1347
+ try {
1348
+ const parsed = JSON.parse(text) as { success?: boolean; error?: string };
1349
+ if (parsed.success === false) {
1350
+ logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): ${parsed.error || 'save failed'}`);
1351
+ return;
1352
+ }
1353
+ } catch {
1354
+ // non-JSON response
1355
+ }
1356
+ logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (Metro): ${scenarioName}/redis/${hash}.json`);
1357
+ } catch (e) {
1358
+ logger.warn('[Mockifyer-Fetch] Proxy client mirror (Metro) failed:', e);
1359
+ }
1360
+ }
1361
+
1362
+ /**
1363
+ * Await background stream capture, then persist concatenated body + stream timeline.
1364
+ * Called without blocking the caller's live ReadableStream.
1365
+ */
1366
+ private async saveStreamRecording(response: HTTPResponse): Promise<void> {
1367
+ const recording = response.mockifyerStreamRecording;
1368
+ if (!recording) {
1369
+ await this.saveResponse(response);
1370
+ return;
1371
+ }
1372
+ const captured = await recording;
1373
+ const withBody: HTTPResponse = {
1374
+ ...response,
1375
+ data: captured.concatenated,
1376
+ mockifyerStoredStream: captured.stream,
1377
+ mockifyerStreamRecording: undefined,
1378
+ };
1379
+ await this.saveResponse(withBody);
1380
+ }
1381
+
1382
+ private async saveResponse(response: HTTPResponse): Promise<void> {
1383
+ // CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
1384
+ if ((response.config as any)?.__mockifyer_skip_save || (response.config as any)?.__mockifyer_bypass) {
1385
+ return;
1386
+ }
1387
+
1388
+ // If using a proxy for upstream calls, do not save locally.
1389
+ if (this.config.proxy?.baseUrl) {
1390
+ return;
1391
+ }
1392
+
1393
+ if (shouldBlockLocalMockRecording(this.config)) {
1394
+ logger.info(
1395
+ '[Mockifyer-Fetch] Strict proxy-only mode: skipping local mock save (dashboard proxy unavailable).'
1396
+ );
1397
+ return;
1398
+ }
1399
+
1400
+ const url = response.config?.url || (response as any).request?.responseURL || (response as any).url || '';
1401
+ if (url && shouldBypassMockifyerForUrl(url, this.config.excludedUrls, this.config.baseUrl)) {
1402
+ return;
1403
+ }
1404
+ const recordingExclusions = resolveRecordingExclusions(this.config);
1405
+ if (
1406
+ url &&
1407
+ shouldExcludeRecording(url, recordingExclusions, this.config.baseUrl)
1408
+ ) {
1409
+ return;
1410
+ }
1411
+
1412
+ const mayRecordFlag = (response.config as any)?.__mockifyer_domain_path_may_record;
1413
+ if (mayRecordFlag === false) {
1414
+ return;
1415
+ }
1416
+ if (mayRecordFlag !== true) {
1417
+ this.domainPathRules.discover(url, this.config.baseUrl);
1418
+ const gate = this.domainPathRules.getTrafficGate(url, this.config.baseUrl);
1419
+ if (!gate.mayRecord) {
1420
+ return;
1421
+ }
1422
+ }
1423
+
1424
+ // Normalize empty params: treat {} the same as undefined for consistent matching
1425
+ const rawParams = response.config.params || {};
1426
+ const normalizedParams = rawParams && Object.keys(rawParams).length > 0 ? rawParams : undefined;
1427
+
1428
+ const saveLookupRequest: StoredRequest = {
1429
+ method: response.config.method?.toUpperCase() || 'GET',
1430
+ url: response.config.url || '',
1431
+ headers: {},
1432
+ data: response.config.data,
1433
+ queryParams: normalizedParams,
1434
+ };
1435
+
1436
+ const requestKey = this.generateRequestKey(saveLookupRequest);
1437
+
1438
+ if (this.savingResponses.has(requestKey)) {
1439
+ return;
1440
+ }
1441
+
1442
+ const existingMock = await this.findBestMatchingMock(saveLookupRequest, {
1443
+ includePassthroughMocks: true,
1444
+ });
1445
+
1446
+ const saveDecision = resolveMockRecordingSaveDecision(
1447
+ this.config,
1448
+ existingMock?.mockData
1449
+ );
1450
+
1451
+ if (saveDecision.action === 'skip') {
1452
+ if (existingMock && mockPassesThroughToRealApi(existingMock.mockData)) {
1453
+ logger.info(
1454
+ `[Mockifyer-Fetch] Passthrough mock exists for ${requestKey}, skipping save (enable refreshPassthroughRecordings to update).`
1455
+ );
1456
+ }
1457
+ return;
1458
+ }
1459
+
1460
+ this.savingResponses.add(requestKey);
1461
+
1462
+ try {
1463
+ const rawParamsForSave = response.config.params || {};
1464
+ const anonymizedQueryParams = this.anonymizeQueryParams(rawParamsForSave);
1465
+ const normalizedParamsForSave =
1466
+ anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
1467
+ ? anonymizedQueryParams
1468
+ : undefined;
1469
+
1470
+ const now = Date.now();
1471
+ if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
1472
+ this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
1473
+ this.sessionStartTime = now;
1474
+ }
1475
+
1476
+ const startTime = (response.config as any).__mockifyer_startTime;
1477
+ const duration = startTime ? Date.now() - startTime : undefined;
1478
+
1479
+ const correlation = this.readRequestCorrelation(response.config);
1480
+ const hopIds = resolvePersistedHopIds(
1481
+ saveDecision.action === 'overwrite' ? existingMock?.mockData : undefined,
1482
+ correlation
1483
+ );
1484
+
1485
+ const storedRequest: StoredRequest = {
1486
+ method: response.config?.method?.toUpperCase() || 'GET',
1487
+ url: response.config?.url || '',
1488
+ headers: this.anonymizeHeaders(response.config?.headers || {}),
1489
+ data: response.config?.data,
1490
+ queryParams: normalizedParamsForSave,
1491
+ };
1492
+ // Prefer explicit override / config; else request-only default (same as proxy).
1493
+ // Use URL-aware resolution for selective recording.
1494
+ const configValue =
1495
+ this.recordResponsesOverride ??
1496
+ this.config.proxy?.recordResponses ??
1497
+ this.config.recordResponses;
1498
+ const recordBodies = resolveLocalRecordResponsesForUrl(storedRequest.url, configValue, this.config.baseUrl);
1499
+ const storedStream = response.mockifyerStoredStream;
1500
+ const responseDataForSave =
1501
+ typeof ReadableStream !== 'undefined' && response.data instanceof ReadableStream
1502
+ ? ''
1503
+ : response.data;
1504
+ const mockData = buildLocalRecordingMockData({
1505
+ request: storedRequest,
1506
+ response: {
1507
+ status: response.status,
1508
+ data: responseDataForSave,
1509
+ headers: response.headers || {},
1510
+ ...(storedStream && recordBodies ? { stream: storedStream } : {}),
1511
+ },
1512
+ recordResponses: recordBodies,
1513
+ meta: {
1514
+ timestamp: new Date().toISOString(),
1515
+ duration,
1516
+ sessionId:
1517
+ saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
1518
+ ? existingMock.mockData.sessionId
1519
+ : this.currentSessionId,
1520
+ requestId: hopIds.requestId,
1521
+ parentRequestId: hopIds.parentRequestId,
1522
+ parentRequestIds: hopIds.parentRequestIds,
1523
+ // Allowlisted URLs (recordBodies=true) should NOT have alwaysUseRealApi
1524
+ // so they replay immediately. Request-only stubs need alwaysUseRealApi.
1525
+ ...(!recordBodies
1526
+ ? { alwaysUseRealApi: true as const }
1527
+ : {}),
1528
+ },
1529
+ });
1530
+
1531
+ applyRecordingPassthroughFlag(mockData, saveDecision.alwaysUseRealApi);
1532
+
1533
+ if (this.databaseProvider) {
1534
+ try {
1535
+ await this.databaseProvider.save(mockData);
1536
+
1537
+ if (this.config.generateTests?.enabled) {
1538
+ await this.generateTestForMock(mockData);
1539
+ }
1540
+ } catch (error) {
1541
+ console.error(
1542
+ `[Mockifyer-Fetch] ❌ Error saving mock using ${this.config.databaseProvider?.type} provider:`,
1543
+ error
1544
+ );
1545
+ throw error;
1546
+ }
1547
+ } else {
1548
+ const fs = getFs();
1549
+ const path = getPath();
1550
+ if (fs && path) {
1551
+ const currentScenario = this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId);
1552
+ const scenarioPath = this.capabilities.getScenarioFolderPath(this.config.mockDataPath, currentScenario);
1553
+ this.capabilities.ensureScenarioFolder(this.config.mockDataPath, currentScenario);
1554
+
1555
+ const limitCheck = checkRequestLimit(this.config.mockDataPath);
1556
+ if (limitCheck.limitReached && limitCheck.error) {
1557
+ console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
1558
+ return;
1559
+ }
1560
+
1561
+ if (saveDecision.action === 'overwrite' && existingMock?.filePath) {
1562
+ fs.writeFileSync(existingMock.filePath, JSON.stringify(mockData, null, 2));
1563
+ logger.info(
1564
+ `[Mockifyer] Refreshed passthrough mock: ${currentScenario}/${existingMock.filename}`
1565
+ );
1566
+ } else {
1567
+ const { dir, filename } = getMockFilePath(mockData, formatDateStr(getCurrentDate()));
1568
+ const filePath = path.join(scenarioPath, dir, filename);
1569
+ fs.mkdirSync(path.join(scenarioPath, dir), { recursive: true });
1570
+ fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
1571
+ logger.info(
1572
+ `[Mockifyer] Saved new mock to file: ${currentScenario}/${dir ? `${dir}/` : ''}${filename}`
1573
+ );
1574
+ }
1575
+
1576
+ if (this.config.generateTests?.enabled && this.testGenerator) {
1577
+ await this.generateTestForMock(mockData);
1578
+ }
1579
+ } else {
1580
+ console.warn('[Mockifyer] Cannot save mock: no database provider and fs/path not available');
1581
+ }
1582
+ }
1583
+
1584
+ // Update domain path rule to allow replay for allowlisted responses
1585
+ if (recordBodies) {
1586
+ this.domainPathRules.enableAutoMockForUrl(storedRequest.url, this.config.baseUrl);
1587
+ }
1588
+ } finally {
1589
+ this.savingResponses.delete(requestKey);
1590
+ }
1591
+ }
1592
+
1593
+ private async persistMatchedMockAfterLiveCapture(
1594
+ cachedMock: CachedMockData,
1595
+ capturedResponse: StoredResponse,
1596
+ durationMs?: number,
1597
+ liveCorrelation?: RequestCorrelationContext
1598
+ ): Promise<void> {
1599
+ const updated = buildMockDataAfterLiveCapture(cachedMock.mockData, capturedResponse, durationMs);
1600
+ applyPersistedHopIds(updated, resolvePersistedHopIds(cachedMock.mockData, liveCorrelation));
1601
+
1602
+ if (this.databaseProvider) {
1603
+ await this.databaseProvider.save(updated);
1604
+ return;
1605
+ }
1606
+
1607
+ const fs = getFs();
1608
+ if (fs && cachedMock.filePath) {
1609
+ fs.writeFileSync(cachedMock.filePath, JSON.stringify(updated, null, 2));
1610
+ logger.info(`[Mockifyer-Fetch] Refreshed mock from live API: ${cachedMock.filename}`);
1611
+ }
1612
+ }
1613
+
1614
+ /**
1615
+ * Generates test file for a mock
1616
+ */
1617
+ private async generateTestForMock(mockData: MockData): Promise<void> {
1618
+ if (!this.testGenerator) {
1619
+ return;
1620
+ }
1621
+
1622
+ // Browser: skip test generation (needs fs)
1623
+ return;
1624
+ }
1625
+
1626
+ private anonymizeHeaders(headers: Record<string, any>): Record<string, any> {
1627
+ const defaultHeadersToAnonymize = [
1628
+ 'x-rapidapi-key', 'x-api-key', 'authorization', 'api-key', 'apikey',
1629
+ 'x-auth-token', 'x-access-token', 'bearer'
1630
+ ];
1631
+
1632
+ const headersToAnonymize = this.config.anonymizeHeaders !== undefined
1633
+ ? this.config.anonymizeHeaders
1634
+ : defaultHeadersToAnonymize;
1635
+
1636
+ if (headersToAnonymize.length === 0) {
1637
+ return headers;
1638
+ }
1639
+
1640
+ const anonymized = { ...headers };
1641
+ const lowerCaseHeadersToAnonymize = headersToAnonymize.map((h: string) => h.toLowerCase());
1642
+
1643
+ Object.keys(anonymized).forEach(key => {
1644
+ if (lowerCaseHeadersToAnonymize.includes(key.toLowerCase())) {
1645
+ anonymized[key] = '***';
1646
+ }
1647
+ });
1648
+
1649
+ return anonymized;
1650
+ }
1651
+
1652
+ private anonymizeQueryParams(params: Record<string, any>): Record<string, any> {
1653
+ const defaultParamsToAnonymize = ['key', 'api_key', 'apikey', 'token', 'access_token'];
1654
+
1655
+ const paramsToAnonymize = this.config.anonymizeQueryParams !== undefined
1656
+ ? this.config.anonymizeQueryParams
1657
+ : defaultParamsToAnonymize;
1658
+
1659
+ if (paramsToAnonymize.length === 0) {
1660
+ return params;
1661
+ }
1662
+
1663
+ const anonymized = { ...params };
1664
+ const lowerCaseParamsToAnonymize = paramsToAnonymize.map((p: string) => p.toLowerCase());
1665
+
1666
+ Object.keys(anonymized).forEach(key => {
1667
+ if (lowerCaseParamsToAnonymize.includes(key.toLowerCase())) {
1668
+ anonymized[key] = '***';
1669
+ }
1670
+ });
1671
+
1672
+ return anonymized;
1673
+ }
1674
+
1675
+ /**
1676
+ * Updates the logical client lane for subsequent requests (headers, proxy envelope, scenario paths, Redis).
1677
+ * Does not re-read native launch arguments or environment variables.
1678
+ */
1679
+ setClientId(lane: string): void {
1680
+ const t = String(lane).trim();
1681
+ if (!t) {
1682
+ throw new Error('[Mockifyer-Fetch] setClientId requires a non-empty string');
1683
+ }
1684
+ this.config.clientId = t;
1685
+ logger.info(`[Mockifyer-Fetch] clientId set to: ${t}`);
1686
+ }
1687
+
1688
+ /** Current logical lane id (same value used for isolation). */
1689
+ getClientId(): string | undefined {
1690
+ return this.config.clientId;
1691
+ }
1692
+
1693
+ /**
1694
+ * Turn record mode on/off at runtime (dev menus, tests).
1695
+ */
1696
+ setRecordMode(enabled: boolean): void {
1697
+ const next = Boolean(enabled);
1698
+ this.config.recordMode = next;
1699
+ if (next) {
1700
+ this.config.failOnMissingMock = false;
1701
+ this.domainPathRules.enableRecordResponsesForAllRules();
1702
+ }
1703
+ if (this.config.proxy?.baseUrl) {
1704
+ this.config.proxy = {
1705
+ ...this.config.proxy,
1706
+ recordOnMiss: next,
1707
+ };
1708
+ const client = this.httpClient as FetchHTTPClient & {
1709
+ setProxyRecordOnMiss?: (value: boolean | undefined) => void;
1710
+ };
1711
+ client.setProxyRecordOnMiss?.(next);
1712
+ }
1713
+ logger.info(`[Mockifyer-Fetch] recordMode set to: ${next}`);
1714
+ }
1715
+
1716
+ /** Whether newly unmatched requests can be recorded (local or proxy record-on-miss). */
1717
+ isRecordMode(): boolean {
1718
+ return this.config.recordMode === true;
1719
+ }
1720
+
1721
+ /**
1722
+ * Whether new recordings store full response bodies (true) or request-only stubs (false, default).
1723
+ */
1724
+ setRecordResponses(enabled: boolean): void {
1725
+ const next = Boolean(enabled);
1726
+ this.recordResponsesOverride = next;
1727
+ this.config.recordResponses = next;
1728
+ if (this.config.proxy) {
1729
+ this.config.proxy = {
1730
+ ...this.config.proxy,
1731
+ recordResponses: next,
1732
+ };
1733
+ }
1734
+ const client = this.httpClient as FetchHTTPClient & {
1735
+ setProxyRecordResponses?: (value: boolean) => void;
1736
+ };
1737
+ client.setProxyRecordResponses?.(next);
1738
+ logger.info(`[Mockifyer-Fetch] recordResponses (store bodies) set to: ${next}`);
1739
+ }
1740
+
1741
+ /** True when new recordings include response bodies (not request-only stubs). */
1742
+ isRecordResponses(): boolean {
1743
+ const configValue = this.recordResponsesOverride ??
1744
+ (this.config.proxy?.baseUrl ? this.config.proxy.recordResponses : this.config.recordResponses);
1745
+
1746
+ // Check env override first (applies to both boolean and array configs)
1747
+ const { envRecordResponsesOverride } = require('@sgedda/mockifyer-core');
1748
+ const envOverride = envRecordResponsesOverride();
1749
+ if (envOverride !== undefined) {
1750
+ return envOverride;
1751
+ }
1752
+
1753
+ // If config is an array, return true if non-empty (at least some URLs will record)
1754
+ if (Array.isArray(configValue)) {
1755
+ return configValue.length > 0;
1756
+ }
1757
+
1758
+ // For boolean configs, use the old resolvers
1759
+ if (this.config.proxy?.baseUrl) {
1760
+ return resolveRecordResponses(configValue);
1761
+ }
1762
+ return resolveLocalRecordResponses(configValue);
1763
+ }
1764
+
1765
+ /**
1766
+ * Enable Mockifyer at runtime.
1767
+ */
1768
+ enableMockifyer(): void {
1769
+ this.runtimeEnabled = true;
1770
+ logger.info('[Mockifyer-Fetch] Mockifyer enabled at runtime');
1771
+ void this.persistRuntimeEnabledState(true);
1772
+ }
1773
+
1774
+ /**
1775
+ * Disable Mockifyer at runtime.
1776
+ */
1777
+ disableMockifyer(): void {
1778
+ this.runtimeEnabled = false;
1779
+ logger.info('[Mockifyer-Fetch] Mockifyer disabled at runtime - all requests will bypass');
1780
+ void this.persistRuntimeEnabledState(false);
1781
+ }
1782
+
1783
+ /**
1784
+ * Check if Mockifyer is currently enabled at runtime.
1785
+ */
1786
+ isMockifyerEnabled(): boolean {
1787
+ return this.runtimeEnabled;
1788
+ }
1789
+
1790
+ private async persistRuntimeEnabledState(enabled: boolean): Promise<void> {
1791
+ if (!this.runtimeEnabledStorage) {
1792
+ return;
1793
+ }
1794
+ await savePersistedRuntimeEnabled(this.runtimeEnabledStorage, enabled);
1795
+ }
1796
+
1797
+ getHTTPClient(): HTTPClient {
1798
+ return this.httpClient;
1799
+ }
1800
+
1801
+ async reloadMockData(syncFromProject: boolean = true): Promise<void> {
1802
+ await this.databaseProviderInitPromise;
1803
+ this.poolResponseCache.clear();
1804
+ if (this.databaseProvider && typeof (this.databaseProvider as any).reload === 'function') {
1805
+ if (syncFromProject && typeof (this.databaseProvider as any).reload === 'function') {
1806
+ await (this.databaseProvider as any).reload(syncFromProject);
1807
+ } else {
1808
+ await (this.databaseProvider as any).reload();
1809
+ }
1810
+ } else {
1811
+ if (typeof (this as any).loadMockData === 'function') {
1812
+ (this as any).loadMockData();
1813
+ }
1814
+ }
1815
+ this.domainPathRules.invalidateCache();
1816
+ await this.domainPathRules.hydrate();
1817
+ }
1818
+
1819
+ clearStaleCacheEntries(): number {
1820
+ return 0; // No cache in fetch implementation
1821
+ }
1822
+
1823
+ async clearAllMocks(): Promise<void> {
1824
+ if (this.databaseProvider && typeof this.databaseProvider.clearAll === 'function') {
1825
+ await this.databaseProvider.clearAll();
1826
+ } else {
1827
+ logger.warn('[Mockifyer-Fetch] Provider does not support clearAll()');
1828
+ }
1829
+ }
1830
+ }