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