@sgedda/mockifyer-fetch 1.8.104 → 1.8.107

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,9 @@
1
1
  "use strict";
2
+ // Fetch-only Mockifyer implementation
3
+ // fs and path are lazy-loaded via dynamic require to avoid breaking browser bundles
4
+ //
5
+ // DO NOT change this to static require() or import - bundlers will fail on browser builds.
6
+ // The dynamic require is hidden inside functions to prevent bundle-time resolution.
2
7
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
8
  if (k2 === undefined) k2 = k;
4
9
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -14,1556 +19,43 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
19
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
20
  };
16
21
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.canUseDashboardCentralProxy = exports.canUseDashboardRedisProxy = void 0;
22
+ exports.MockifyerClass = exports.canUseDashboardCentralProxy = exports.canUseDashboardRedisProxy = void 0;
18
23
  exports.setupMockifyer = setupMockifyer;
19
24
  exports.initMockifyerForDashboardProxy = initMockifyerForDashboardProxy;
20
25
  exports.initMockifyerForLocalFilesystem = initMockifyerForLocalFilesystem;
21
- // Fetch-only Mockifyer implementation
22
- // Conditionally import fs - will be undefined in React Native
23
- let fs;
24
- let path;
25
- try {
26
- // Try to require fs and path - will fail in React Native where they're stubbed
27
- fs = require('fs');
28
- path = require('path');
26
+ // Lazy-load Node.js built-ins (static literal requires, bundler-safe)
27
+ function getFs() {
28
+ // Only works in Node.js
29
+ if (typeof process === 'undefined' || !process.versions?.node) {
30
+ return null;
31
+ }
32
+ try {
33
+ // Static require with literal path - bundlers can stub this
34
+ return require('fs');
35
+ }
36
+ catch {
37
+ return null;
38
+ }
29
39
  }
30
- catch (e) {
31
- // fs/path not available (React Native environment)
32
- fs = undefined;
33
- path = undefined;
40
+ function getPath() {
41
+ if (typeof process === 'undefined' || !process.versions?.node) {
42
+ return null;
43
+ }
44
+ try {
45
+ return require('path');
46
+ }
47
+ catch {
48
+ return null;
49
+ }
34
50
  }
35
51
  // Import from core package
36
52
  const mockifyer_core_1 = require("@sgedda/mockifyer-core");
37
53
  const mockifyer_core_2 = require("@sgedda/mockifyer-core");
38
54
  const core_proxy_1 = require("./core-proxy");
39
- const proxy_upstream_tls_insecure_1 = require("@sgedda/mockifyer-core/utils/proxy-upstream-tls-insecure");
40
- const fetch_client_1 = require("./clients/fetch-client");
41
55
  const fetch_response_body_1 = require("./utils/fetch-response-body");
42
56
  const resolve_patched_fetch_request_1 = require("./utils/resolve-patched-fetch-request");
43
- class MockifyerClass {
44
- /** Session id for timeline hops — per-screen id from {@link setFlightRecorderRuntimeContext} when set. */
45
- getRuntimeSessionId() {
46
- return (0, mockifyer_core_1.resolveActiveMockifyerSessionId)(() => {
47
- const now = Date.now();
48
- if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
49
- this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
50
- this.sessionStartTime = now;
51
- (0, mockifyer_core_1.setFlightRecorderRuntimeContext)({ sessionId: this.currentSessionId });
52
- }
53
- return this.currentSessionId;
54
- });
55
- }
56
- unwrapResponseInlineTrace(response) {
57
- const correlation = this.readRequestCorrelation(response.config);
58
- const parentRequestId = correlation?.requestId?.trim();
59
- if (!parentRequestId) {
60
- response.data = (0, mockifyer_core_1.unwrapAndMergeInlineTraceEnvelope)(response.data);
61
- return;
62
- }
63
- const scenario = this.config.proxy?.scenario?.trim() ||
64
- (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath);
65
- response.data = (0, mockifyer_core_1.unwrapInlineTraceEnvelopeEmittingNetworkEvents)(response.data, {
66
- parentRequestId,
67
- config: this.config,
68
- scenario,
69
- clientId: this.config.clientId,
70
- sessionId: this.getRuntimeSessionId(),
71
- transport: this.usesDashboardProxy() ? 'proxy' : 'fetch',
72
- });
73
- }
74
- async applyOutboundCorrelation(config) {
75
- return (0, mockifyer_core_1.applyOutboundRequestCorrelation)(config, await (0, mockifyer_core_1.resolveNetworkLogIncludeTraceOptionsAsync)(this.config));
76
- }
77
- /**
78
- * Full outbound URL including `params` — hop logs / Atlas curl / include-trace
79
- * must not drop the query string (fetch splits search into `config.params`).
80
- */
81
- resolveLoggedRequestUrl(config, fallbackUrl) {
82
- const raw = (fallbackUrl || config?.url || '').trim();
83
- if (!raw)
84
- return '';
85
- return (0, mockifyer_core_1.appendParamsToUrl)(raw, config?.params);
86
- }
87
- /** Best-effort dashboard network log. */
88
- logNetworkEvent(partial, correlation,
89
- /** Final outbound header bag (after auth interceptors). */
90
- requestHeadersSource) {
91
- const scenario = this.config.proxy?.scenario?.trim() ||
92
- (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath);
93
- const { requestBody, responseBody, ...eventPartial } = partial;
94
- const businessResponseBody = (0, mockifyer_core_1.getInlineTraceEnvelopeBusinessBody)(responseBody);
95
- const requestHeaders = eventPartial.requestHeaders ?? (0, mockifyer_core_1.outboundHeadersToRecord)(requestHeadersSource);
96
- if (!this.config.proxy?.baseUrl) {
97
- (0, mockifyer_core_1.recordInlineTraceHopFromExchange)({
98
- method: eventPartial.method,
99
- url: eventPartial.url,
100
- status: eventPartial.status,
101
- source: eventPartial.source,
102
- transport: eventPartial.transport ?? 'fetch',
103
- requestId: correlation?.requestId ?? eventPartial.requestId ?? null,
104
- parentRequestId: correlation?.parentRequestId ?? eventPartial.parentRequestId ?? null,
105
- durationMs: eventPartial.durationMs,
106
- clientId: this.config.clientId ?? eventPartial.clientId ?? null,
107
- errorMessage: eventPartial.errorMessage,
108
- requestHeaders,
109
- requestBody,
110
- responseBody,
111
- });
112
- }
113
- (0, mockifyer_core_1.emitMockifyerNetworkEvent)({
114
- config: this.config,
115
- scenario,
116
- clientId: this.config.clientId,
117
- sessionId: this.getRuntimeSessionId(),
118
- requestBody,
119
- responseBody: businessResponseBody,
120
- event: {
121
- ...eventPartial,
122
- transport: eventPartial.transport ?? 'fetch',
123
- requestId: correlation?.requestId ?? eventPartial.requestId,
124
- parentRequestId: correlation?.parentRequestId ?? eventPartial.parentRequestId,
125
- requestHeaders,
126
- requestBodyPreview: eventPartial.requestBodyPreview,
127
- responseBodyPreview: eventPartial.responseBodyPreview,
128
- },
129
- });
130
- }
131
- stashRequestCorrelation(config, correlation) {
132
- config.__mockifyer_requestId =
133
- correlation.requestId;
134
- config.__mockifyer_parentRequestId =
135
- correlation.parentRequestId;
136
- }
137
- bindStoredHopId(config, mockData, fallback) {
138
- const adopted = (0, mockifyer_core_1.adoptStoredOutboundRequestId)(config, mockData?.requestId);
139
- if (adopted) {
140
- this.stashRequestCorrelation(config, adopted);
141
- return adopted;
142
- }
143
- return fallback;
144
- }
145
- readRequestCorrelation(config) {
146
- const requestId = config.__mockifyer_requestId;
147
- if (!requestId)
148
- return undefined;
149
- const parentRequestId = config.__mockifyer_parentRequestId;
150
- return parentRequestId ? { requestId, parentRequestId } : { requestId };
151
- }
152
- /** Attach dashboard lookup id onto thrown fetch/client errors. */
153
- throwWithMockifyerRequestId(error) {
154
- const err = error;
155
- const hopRequestId = err?.config?.__mockifyer_requestId;
156
- const requestId = (0, mockifyer_core_1.resolveMockifyerRequestIdForError)({
157
- hopRequestId,
158
- responseHeaders: err?.response?.headers,
159
- });
160
- throw (0, mockifyer_core_1.attachMockifyerRequestIdToError)(error, requestId);
161
- }
162
- /**
163
- * Serve stored mock body with optional `$pool` resolution from the local fixture pool.
164
- * Always passes `loadPoolResponse` — including React Native where Node `fs`/`path` are
165
- * missing or Metro-stubbed — so `$pool` refs resolve via disk and/or {@link poolResponseCache}.
166
- */
167
- prepareStoredResponseBody(mockData, filename, scenarioPath) {
168
- const joinPath = path && typeof path.join === 'function' ? path.join.bind(path) : null;
169
- return (0, mockifyer_core_1.prepareMockResponseBody)(mockData, (0, mockifyer_core_1.createServeTimeClock)(this.config), {
170
- loadPoolResponse: (0, mockifyer_core_1.createServeTimePoolResponseLoader)({
171
- mockDataPath: this.config.mockDataPath,
172
- nodeFs: (0, mockifyer_core_1.isUsableNodeLikePoolFs)(fs) ? fs : null,
173
- joinPath,
174
- cache: this.poolResponseCache,
175
- }),
176
- filename,
177
- scenarioPath,
178
- });
179
- }
180
- /**
181
- * Ensure `$pool` fixtures are available in {@link poolResponseCache} when Node fs
182
- * cannot load them (React Native). Tries database provider, then Metro.
183
- */
184
- async warmPoolResponseCache(mockData) {
185
- if (!(0, mockifyer_core_1.arePoolRefsEnabled)() || !(0, mockifyer_core_1.containsPoolRefs)(mockData.response?.data)) {
186
- return;
187
- }
188
- if ((0, mockifyer_core_1.isUsableNodeLikePoolFs)(fs)) {
189
- return;
190
- }
191
- const ids = (0, mockifyer_core_1.collectPoolRefIds)(mockData.response.data);
192
- for (const id of ids) {
193
- if (this.poolResponseCache.has(id)) {
194
- continue;
195
- }
196
- const fromProvider = await this.loadPoolResponseFromProvider(id);
197
- if (fromProvider) {
198
- this.poolResponseCache.set(id, fromProvider);
199
- continue;
200
- }
201
- const fromMetro = await this.loadPoolResponseFromMetro(id);
202
- if (fromMetro) {
203
- this.poolResponseCache.set(id, fromMetro);
204
- }
205
- }
206
- }
207
- async loadPoolResponseFromProvider(id) {
208
- const provider = this.databaseProvider;
209
- if (!provider || typeof provider.loadPoolResponseItem !== 'function') {
210
- return undefined;
211
- }
212
- try {
213
- return (await provider.loadPoolResponseItem(id)) ?? undefined;
214
- }
215
- catch (error) {
216
- mockifyer_core_2.logger.warn(`[Mockifyer-Fetch] Failed to load pool response "${id}" from provider:`, error);
217
- return undefined;
218
- }
219
- }
220
- async loadPoolResponseFromMetro(id) {
221
- const metroPort = this.config.databaseProvider?.options?.metroPort ?? 8081;
222
- const originalFetch = global.__mockifyer_original_fetch ||
223
- (typeof fetch !== 'undefined' ? fetch : undefined);
224
- if (!originalFetch) {
225
- return undefined;
226
- }
227
- try {
228
- const url = `http://localhost:${metroPort}/mockifyer-pool-response?id=${encodeURIComponent(id)}`;
229
- const response = await originalFetch(url);
230
- if (!response.ok) {
231
- return undefined;
232
- }
233
- const payload = (await response.json());
234
- if (payload.success && payload.item?.responseItemId && payload.item.response) {
235
- return payload.item;
236
- }
237
- return undefined;
238
- }
239
- catch (error) {
240
- mockifyer_core_2.logger.warn(`[Mockifyer-Fetch] Failed to load pool response "${id}" from Metro:`, error);
241
- return undefined;
242
- }
243
- }
244
- constructor(config) {
245
- this.processingRequests = new Set();
246
- this.savingResponses = new Set();
247
- /** Resolves when async databaseProvider.initialize() completes (expo/hybrid). */
248
- this.databaseProviderInitPromise = Promise.resolve();
249
- this.currentSessionId = null;
250
- this.sessionStartTime = 0;
251
- this.SESSION_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
252
- /**
253
- * Promoted pool responses for serve-time `$pool` resolve when Node `fs` is
254
- * unavailable (React Native / Metro stubs). Seeded via {@link warmPoolResponseCache}.
255
- */
256
- this.poolResponseCache = new Map();
257
- /**
258
- * Runtime override for whether local/proxy recordings include response bodies.
259
- * `undefined` = follow env / defaults ({@link resolveLocalRecordResponses} / {@link resolveRecordResponses}).
260
- */
261
- this.recordResponsesOverride = undefined;
262
- // Validate database provider - filesystem, expo-filesystem, hybrid, and memory are supported
263
- if (config.databaseProvider && config.databaseProvider.type) {
264
- const supportedTypes = ['filesystem', 'expo-filesystem', 'hybrid', 'memory', 'redis', 'sqlite'];
265
- if (!supportedTypes.includes(config.databaseProvider.type)) {
266
- throw new Error(`Database provider type '${config.databaseProvider.type}' is not yet available for use. ` +
267
- `Supported types: ${supportedTypes.join(', ')}. ` +
268
- `Please use one of the supported provider types.`);
269
- }
270
- }
271
- // Validate and normalize conflicting settings
272
- if (config.recordMode && config.failOnMissingMock) {
273
- mockifyer_core_2.logger.warn('[Mockifyer] Warning: recordMode is true but failOnMissingMock is also set to true. ' +
274
- 'failOnMissingMock is ignored in record mode (real API calls are made to record responses). ' +
275
- 'Setting failOnMissingMock to false.');
276
- config.failOnMissingMock = false;
277
- }
278
- // Validate conflicting similar match settings
279
- if (config.similarMatchIgnoreAllQueryParams &&
280
- config.similarMatchRequiredParams &&
281
- config.similarMatchRequiredParams.length > 0) {
282
- mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Warning: Both similarMatchIgnoreAllQueryParams and similarMatchRequiredParams are set. ' +
283
- 'similarMatchIgnoreAllQueryParams takes precedence and all query parameters will be ignored. ' +
284
- 'similarMatchRequiredParams will be ignored.');
285
- // Clear similarMatchRequiredParams to avoid confusion
286
- config.similarMatchRequiredParams = undefined;
287
- }
288
- // Auto-enable useSimilarMatch if similarMatchRequiredParams is set (and not ignored)
289
- if (config.similarMatchRequiredParams && config.similarMatchRequiredParams.length > 0) {
290
- if (config.useSimilarMatch === undefined || config.useSimilarMatch === false) {
291
- config.useSimilarMatch = true;
292
- }
293
- }
294
- // Auto-enable useSimilarMatch if similarMatchIgnoreAllQueryParams is set
295
- if (config.similarMatchIgnoreAllQueryParams) {
296
- if (config.useSimilarMatch === undefined || config.useSimilarMatch === false) {
297
- config.useSimilarMatch = true;
298
- }
299
- }
300
- let launchClientId;
301
- if (config.useLaunchArgumentsClientId) {
302
- const key = config.launchArgumentClientIdKey ?? mockifyer_core_1.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY;
303
- launchClientId = (0, mockifyer_core_1.tryGetClientIdFromLaunchArguments)(key);
304
- if (launchClientId) {
305
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] clientId from launch arguments (${key}): ${launchClientId}`);
306
- }
307
- }
308
- // Store config BEFORE any modifications
309
- this.config = { ...config }; // Create a copy to avoid mutations
310
- // Launch arg wins over MOCKIFYER_CLIENT_ID / config.clientId when present (E2E).
311
- if (launchClientId) {
312
- this.config.clientId = launchClientId;
313
- }
314
- else if ((0, mockifyer_core_1.resolveStrictScenarioResolution)(this.config) &&
315
- Boolean(this.config.proxy?.baseUrl?.trim())) {
316
- // Strict proxy: no auto lane until explicit clientId / setClientId (devtools show real URLs).
317
- this.config.clientId = (0, mockifyer_core_1.resolveExplicitClientIdOnly)(this.config);
318
- }
319
- else {
320
- this.config.clientId = (0, mockifyer_core_1.resolveClientId)(this.config);
321
- }
322
- this.activationMode = (0, mockifyer_core_1.resolveActivationMode)(this.config);
323
- this.domainPathRules = new mockifyer_core_1.DomainPathRulesSession({
324
- config: this.config,
325
- getRecordMode: () => this.config.recordMode === true,
326
- });
327
- this.runtimeEnabledStorage = (0, mockifyer_core_1.resolveRuntimeEnabledStorage)(config.persistRuntimeEnabled);
328
- if (config.persistRuntimeEnabled === true && !this.runtimeEnabledStorage) {
329
- mockifyer_core_2.logger.warn('[Mockifyer-Fetch] persistRuntimeEnabled: true but no storage found. ' +
330
- 'Install @react-native-async-storage/async-storage (RN) or use a custom { getItem, setItem }.');
331
- }
332
- this.runtimeEnabled = (0, mockifyer_core_1.resolveInitialRuntimeEnabled)({
333
- initialRuntimeEnabled: config.initialRuntimeEnabled,
334
- startDisabled: config.startDisabled,
335
- runtimeMode: config.runtimeMode,
336
- launchScenarioPresent: (0, mockifyer_core_1.isScenarioLaunchFromNativeArguments)(),
337
- });
338
- if (!this.runtimeEnabled) {
339
- const reason = typeof config.initialRuntimeEnabled === 'boolean'
340
- ? 'persisted / initialRuntimeEnabled: false'
341
- : config.runtimeMode === 'manual'
342
- ? 'runtimeMode: "manual"'
343
- : 'startDisabled: true';
344
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Starting with Mockifyer DISABLED (${reason}). Call enableMockifyer() to activate.`);
345
- }
346
- else if ((0, mockifyer_core_1.isScenarioLaunchFromNativeArguments)()) {
347
- mockifyer_core_2.logger.info('[Mockifyer-Fetch] Starting with Mockifyer ENABLED (native launch scenario argument).');
348
- }
349
- else if (typeof config.initialRuntimeEnabled === 'boolean' && config.initialRuntimeEnabled) {
350
- mockifyer_core_2.logger.info('[Mockifyer-Fetch] Starting with Mockifyer ENABLED (restored from persisted preference).');
351
- }
352
- (0, mockifyer_core_1.configureFlightRecorder)((0, mockifyer_core_1.resolveFlightRecorderConfig)(this.config));
353
- (0, mockifyer_core_1.configureAtlas)(this.config, {
354
- scenario: (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId),
355
- clientId: this.config.clientId ?? null,
356
- });
357
- (0, mockifyer_core_1.setFlightRecorderRuntimeContext)({
358
- clientId: this.config.clientId,
359
- scenario: (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId),
360
- });
361
- if (this.config.proxy?.baseUrl && this.config.proxy.mirrorRecordedMocksToClient === undefined) {
362
- const raw = typeof process !== 'undefined'
363
- ? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
364
- : '';
365
- if (raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on') {
366
- this.config.proxy = { ...this.config.proxy, mirrorRecordedMocksToClient: true };
367
- }
368
- }
369
- // Initialize test generator if test generation is enabled
370
- if (config.generateTests?.enabled) {
371
- this.testGenerator = new mockifyer_core_1.TestGenerator();
372
- }
373
- // Initialize database provider if specified
374
- if (config.databaseProvider && config.databaseProvider.type) {
375
- const providerConfig = {
376
- ...config.databaseProvider,
377
- options: {
378
- ...config.databaseProvider.options,
379
- mockDataPath: config.databaseProvider.options?.mockDataPath ?? config.mockDataPath,
380
- clientId: this.config.clientId,
381
- getClientId: () => this.config.clientId,
382
- },
383
- };
384
- this.databaseProvider = (0, mockifyer_core_1.createProvider)(config.databaseProvider.type, providerConfig);
385
- const initResult = this.databaseProvider.initialize();
386
- // Handle async initialization (expo-filesystem / hybrid providers)
387
- if (initResult instanceof Promise) {
388
- this.databaseProviderInitPromise = initResult.catch((error) => {
389
- mockifyer_core_2.logger.error('[Mockifyer-Fetch] Error initializing database provider:', error);
390
- });
391
- }
392
- }
393
- else {
394
- // Fallback to Node.js filesystem
395
- this.ensureMockDataDirectory();
396
- }
397
- // Create fetch HTTP client
398
- this.httpClient = new fetch_client_1.FetchHTTPClient({
399
- baseUrl: config.baseUrl,
400
- defaultHeaders: config.defaultHeaders,
401
- proxy: config.proxy,
402
- clientId: this.config.clientId,
403
- getClientId: () => this.config.clientId,
404
- getStrictLaneScenario: () => (0, mockifyer_core_1.resolveProxyStrictLaneScenario)(this.config),
405
- getUpstreamTlsInsecure: () => (0, proxy_upstream_tls_insecure_1.resolveProxyUpstreamTlsInsecure)(this.config),
406
- getExplicitProxyScenarioContext: () => (0, mockifyer_core_1.isExplicitProxyScenarioContext)(this.config),
407
- deviceId: this.config.deviceId,
408
- });
409
- if (!config.recordSameEndpoints) {
410
- this.loadMockData();
411
- }
412
- // Always set up mock response interceptor (to use existing mocks)
413
- this.setupMockResponses();
414
- // Set up response interceptor to save responses when recordMode is enabled
415
- this.setupResponseInterceptor();
416
- (0, mockifyer_core_1.logMockifyerInitSummary)(this.config, {
417
- runtimeMode: this.config.runtimeMode,
418
- headline: this.config.initLog?.headline,
419
- });
420
- }
421
- ensureMockDataDirectory() {
422
- // Only use fs if available (Node.js environment) and no database provider is set
423
- if (!fs || this.databaseProvider) {
424
- return;
425
- }
426
- if (!fs.existsSync(this.config.mockDataPath)) {
427
- fs.mkdirSync(this.config.mockDataPath, { recursive: true });
428
- }
429
- }
430
- generateRequestKey(request) {
431
- return (0, mockifyer_core_1.generateRequestKey)(request);
432
- }
433
- /** When set, mock resolution happens on the dashboard `/api/proxy` (Redis/disk), not local `mock-data`. */
434
- usesDashboardProxy() {
435
- const baseUrl = this.config.proxy?.baseUrl;
436
- return typeof baseUrl === 'string' && baseUrl.trim().length > 0;
437
- }
438
- async findBestMatchingMock(request, options) {
439
- // CRITICAL: Never try to match sync endpoint requests - they should never be mocked
440
- const requestUrl = request?.url || '';
441
- if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestUrl)) {
442
- return undefined;
443
- }
444
- const requestKey = this.generateRequestKey(request);
445
- // CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
446
- if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestKey)) {
447
- return undefined;
448
- }
449
- // Use database provider if available, otherwise fallback to filesystem
450
- if (this.databaseProvider) {
451
- return await this.findBestMatchingMockFromProvider(request, options);
452
- }
453
- // Fallback to Node.js filesystem
454
- return this.findBestMatchingMockFromFiles(request, options);
455
- }
456
- async findBestMatchingMockFromProvider(request, options) {
457
- if (!this.databaseProvider) {
458
- return undefined;
459
- }
460
- // CRITICAL: Never try to match sync endpoint requests - they should never be mocked
461
- const requestUrl = request?.url || '';
462
- if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestUrl)) {
463
- return undefined;
464
- }
465
- const requestKey = this.generateRequestKey(request);
466
- // CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
467
- if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestKey)) {
468
- return undefined;
469
- }
470
- // Try exact match first
471
- const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey, options);
472
- if (exactMatch) {
473
- return exactMatch;
474
- }
475
- // Try similar match if enabled
476
- if (this.config.useSimilarMatch) {
477
- const similarMatches = await this.databaseProvider.findAllForSimilarMatch(request);
478
- if (similarMatches && similarMatches.length > 0) {
479
- // Return first similar match
480
- return similarMatches[0];
481
- }
482
- }
483
- return undefined;
484
- }
485
- findBestMatchingMockFromFiles(request, options) {
486
- const includePassthroughMocks = options?.includePassthroughMocks === true;
487
- // Only use fs if available (Node.js environment)
488
- // This method should never be called when using a database provider
489
- if (!fs || !path) {
490
- return undefined;
491
- }
492
- const resolvedMockDataPath = path.resolve(this.config.mockDataPath);
493
- if (!fs.existsSync(resolvedMockDataPath)) {
494
- console.warn('[Mockifyer-Fetch] ⚠️ Mock data path does not exist:', resolvedMockDataPath);
495
- return undefined;
496
- }
497
- const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(resolvedMockDataPath, this.config.clientId);
498
- const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(resolvedMockDataPath, currentScenario);
499
- (0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(scenarioPath, { clientId: this.config.clientId });
500
- if (!fs.existsSync(scenarioPath)) {
501
- mockifyer_core_2.logger.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
502
- return undefined;
503
- }
504
- const files = fs.readdirSync(scenarioPath)
505
- .filter(file => file.endsWith('.json'));
506
- const requestKey = this.generateRequestKey(request);
507
- let exactMatch;
508
- let similarMatch;
509
- for (const file of files) {
510
- try {
511
- const filePath = path.join(scenarioPath, file);
512
- const fileContent = fs.readFileSync(filePath, 'utf-8');
513
- const mockData = JSON.parse(fileContent);
514
- if (!mockData || !mockData.request || typeof mockData.request !== 'object') {
515
- continue;
516
- }
517
- const mockKey = this.generateRequestKey(mockData.request);
518
- if (mockKey === requestKey) {
519
- if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, {
520
- includePassthroughMocks,
521
- filename: file,
522
- scenarioPath,
523
- })) {
524
- exactMatch = { mockData, filename: file, filePath };
525
- break;
526
- }
527
- continue;
528
- }
529
- if (!exactMatch && this.config.useSimilarMatch && !similarMatch) {
530
- // Check if it's a GraphQL request - skip similar matching for GraphQL
531
- const isGraphQL = ['POST', 'PUT', 'PATCH'].includes((request.method || 'GET').toUpperCase()) &&
532
- request.data &&
533
- (() => {
534
- try {
535
- let bodyData = request.data;
536
- if (typeof request.data === 'string') {
537
- bodyData = JSON.parse(request.data);
538
- }
539
- return typeof bodyData === 'object' && bodyData !== null && typeof bodyData.query === 'string';
540
- }
541
- catch {
542
- return false;
543
- }
544
- })();
545
- if (!isGraphQL) {
546
- try {
547
- const requestUrl = new URL(request.url);
548
- const mockUrl = new URL(mockData.request.url);
549
- // Check if pathnames match (exact or pattern-based)
550
- const requestPathname = requestUrl.pathname;
551
- const mockPathname = mockUrl.pathname;
552
- const methodMatch = (mockData.request.method || 'GET').toUpperCase() === (request.method || 'GET').toUpperCase();
553
- // Check for exact pathname match
554
- const exactPathnameMatch = mockPathname === requestPathname;
555
- // Check for pattern-based match (e.g., /posts/71 matches /posts/17 when similarMatchIgnoreAllQueryParams is true)
556
- // This allows matching paths with different IDs when we're ignoring query params
557
- let patternMatch = false;
558
- if (this.config.similarMatchIgnoreAllQueryParams && !exactPathnameMatch && methodMatch) {
559
- // Extract base path by removing the last segment (ID)
560
- // /posts/71 -> /posts, /users/2/todos -> /users/2
561
- const requestSegments = requestPathname.split('/').filter(s => s);
562
- const mockSegments = mockPathname.split('/').filter(s => s);
563
- // Match if base paths are the same (same number of segments, all but last match)
564
- if (requestSegments.length === mockSegments.length && requestSegments.length > 0) {
565
- const requestBase = requestSegments.slice(0, -1);
566
- const mockBase = mockSegments.slice(0, -1);
567
- patternMatch = requestBase.join('/') === mockBase.join('/');
568
- }
569
- }
570
- const pathnameMatch = exactPathnameMatch || patternMatch;
571
- // Check similar match
572
- if (pathnameMatch && methodMatch) {
573
- // If ignoreAllQueryParams is set, skip query param checking entirely
574
- if (this.config.similarMatchIgnoreAllQueryParams) {
575
- // Ignore all query params, match on path and method only
576
- }
577
- else if (this.config.similarMatchRequiredParams && this.config.similarMatchRequiredParams.length > 0) {
578
- // Check if required parameters match (if configured)
579
- const requestParams = request.queryParams || {};
580
- const mockParams = mockData.request.queryParams || {};
581
- const allRequiredMatch = this.config.similarMatchRequiredParams.every((paramName) => {
582
- const requestValue = requestParams[paramName];
583
- const mockValue = mockParams[paramName];
584
- return requestValue === undefined && mockValue === undefined
585
- ? true
586
- : String(requestValue || '') === String(mockValue || '');
587
- });
588
- if (!allRequiredMatch) {
589
- continue; // Required parameter differs, skip this mock
590
- }
591
- }
592
- if ((0, mockifyer_core_1.mockShouldBeIncludedInRequestMatch)(mockData, {
593
- includePassthroughMocks,
594
- filename: file,
595
- scenarioPath,
596
- })) {
597
- similarMatch = { mockData, filename: file, filePath };
598
- }
599
- }
600
- }
601
- catch (e) {
602
- continue;
603
- }
604
- }
605
- }
606
- }
607
- catch (error) {
608
- mockifyer_core_2.logger.warn(`[Mockifyer] Failed to load mock file ${file}:`, error);
609
- }
610
- }
611
- return exactMatch || similarMatch;
612
- }
613
- loadMockData() {
614
- // Skip if using database provider or fs not available
615
- if (this.databaseProvider || !fs) {
616
- return;
617
- }
618
- if (fs.existsSync(this.config.mockDataPath)) {
619
- fs.readdirSync(this.config.mockDataPath)
620
- .filter(file => file.endsWith('.json'));
621
- }
622
- }
623
- setupMockResponses() {
624
- this.httpClient.interceptors.request.use(async (config) => {
625
- // CRITICAL: Runtime toggle — if disabled, bypass all Mockifyer logic
626
- if (!this.runtimeEnabled) {
627
- config.__mockifyer_bypass = true;
628
- return config;
629
- }
630
- // CRITICAL: Completely bypass Mockifyer interception for sync endpoints
631
- // This prevents any Mockifyer processing (mocking, saving, etc.) for these endpoints
632
- const url = config.url || '';
633
- if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(url)) {
634
- // Mark this request to completely skip Mockifyer processing
635
- config.__mockifyer_skip_save = true;
636
- config.__mockifyer_bypass = true;
637
- return config;
638
- }
639
- if ((0, mockifyer_core_1.shouldBypassMockifyerForUrl)(url, this.config.excludedUrls, this.config.baseUrl)) {
640
- config.__mockifyer_bypass = true;
641
- return config;
642
- }
643
- if (!(0, mockifyer_core_1.shouldApplyMockifyer)(this.activationMode, config.headers)) {
644
- config.__mockifyer_bypass = true;
645
- return config;
646
- }
647
- if (!(0, mockifyer_core_1.isExplicitProxyScenarioContext)(this.config)) {
648
- mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Strict proxy scenario: set clientId (lane) or proxy.scenario; passthrough HTTP for this request');
649
- config.__mockifyer_bypass = true;
650
- return config;
651
- }
652
- let correlation = await this.applyOutboundCorrelation(config);
653
- this.stashRequestCorrelation(config, correlation);
654
- // Normalize empty params: treat {} the same as undefined for consistent matching
655
- const rawParams = config.params || {};
656
- const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
657
- const normalizedParams = anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
658
- ? anonymizedQueryParams
659
- : undefined;
660
- const request = {
661
- method: config.method || 'GET',
662
- url: config.url || '',
663
- headers: config.headers || {},
664
- data: config.data,
665
- queryParams: normalizedParams
666
- };
667
- const requestKey = this.generateRequestKey(request);
668
- // Store request key for response interceptor
669
- config.__mockifyer_requestKey = requestKey;
670
- // Store request start time for duration calculation
671
- config.__mockifyer_startTime = Date.now();
672
- // Dashboard proxy owns mock hits (Redis + server-side disk fallback). Do not short-circuit
673
- // from local mock-data while proxy.baseUrl is configured — that bypasses /api/proxy entirely.
674
- if (this.usesDashboardProxy()) {
675
- return config;
676
- }
677
- this.domainPathRules.discover(request.url, this.config.baseUrl);
678
- const trafficGate = this.domainPathRules.getTrafficGate(request.url, this.config.baseUrl);
679
- config.__mockifyer_domain_path_may_record = trafficGate.mayRecord;
680
- if (!trafficGate.mayReplay) {
681
- mockifyer_core_2.logger.debug(`[Mockifyer-Fetch] Domain path rules: replay denied for ${request.method} ${request.url}` +
682
- (trafficGate.matchedDomainPath ? ` (rule: ${trafficGate.matchedDomainPath})` : ' (allowlist unmatched)'));
683
- return config;
684
- }
685
- const cachedMock = await this.findBestMatchingMock(request);
686
- // Return cached mock if found
687
- if (cachedMock) {
688
- const { mockData, filename, filePath } = cachedMock;
689
- correlation = this.bindStoredHopId(config, mockData, correlation) ?? correlation;
690
- if ((0, mockifyer_core_1.mockShouldServeStoredBody)(mockData)) {
691
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
692
- (filePath ? ` (${filePath})` : ''));
693
- const hitScenarioPath = path
694
- ? (0, mockifyer_core_1.getScenarioFolderPath)(path.resolve(this.config.mockDataPath), (0, mockifyer_core_1.getCurrentScenario)(path.resolve(this.config.mockDataPath), this.config.clientId))
695
- : undefined;
696
- if (hitScenarioPath) {
697
- (0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(hitScenarioPath, { clientId: this.config.clientId });
698
- }
699
- const mockResponseBody = this.prepareStoredResponseBody(mockData, filename, hitScenarioPath);
700
- this.logNetworkEvent({
701
- method: (request.method || 'GET').toUpperCase(),
702
- url: this.resolveLoggedRequestUrl(config, request.url),
703
- source: 'mock-hit',
704
- status: mockData.response.status,
705
- requestHash: (0, mockifyer_core_1.networkEventHashFromRequestKey)(requestKey),
706
- requestBody: request.data,
707
- responseBody: mockResponseBody,
708
- }, correlation, request.headers ?? config.headers);
709
- const responseHeaders = {
710
- ...mockData.response.headers,
711
- 'x-mockifyer': 'true',
712
- 'x-mockifyer-timestamp': mockData.timestamp,
713
- 'x-mockifyer-filename': filename,
714
- 'x-mockifyer-filepath': filePath
715
- };
716
- await this.warmPoolResponseCache(mockData);
717
- const mockResponse = {
718
- data: mockResponseBody,
719
- status: mockData.response.status,
720
- statusText: 'OK',
721
- headers: responseHeaders,
722
- config: config
723
- };
724
- return {
725
- ...config,
726
- __mockResponse: Promise.resolve(mockResponse),
727
- __mockifyer_requestKey: requestKey
728
- };
729
- }
730
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Live refresh: ${request.method} ${request.url} → ${filename}` +
731
- (filePath ? ` (${filePath})` : ''));
732
- config.__mockifyer_matchedMock = cachedMock;
733
- }
734
- // Check request limit BEFORE making real API call (only if no mock found and in record mode)
735
- if (this.config.recordMode) {
736
- const limitCheck = (0, mockifyer_core_1.checkRequestLimit)(this.config.mockDataPath);
737
- if (limitCheck.limitReached && limitCheck.error) {
738
- console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
739
- // Return a mock error response instead of making a real API call
740
- const responseHeaders = {
741
- 'x-mockifyer': 'true',
742
- 'x-mockifyer-limit-reached': 'true',
743
- 'content-type': 'application/json'
744
- };
745
- const mockErrorResponse = {
746
- data: {
747
- error: limitCheck.error.message,
748
- message: limitCheck.error.message,
749
- limitReached: true,
750
- maxRequests: limitCheck.error.maxRequests,
751
- currentScenario: limitCheck.error.currentScenario
752
- },
753
- status: 429, // Too Many Requests
754
- statusText: 'Too Many Requests',
755
- headers: responseHeaders,
756
- config: config
757
- };
758
- return {
759
- ...config,
760
- __mockResponse: Promise.resolve(mockErrorResponse),
761
- __mockifyer_requestKey: requestKey,
762
- __mockifyer_limit_reached: true
763
- };
764
- }
765
- }
766
- if (this.config.failOnMissingMock) {
767
- throw new Error(`No mock data found for request: ${this.generateRequestKey(request)}`);
768
- }
769
- return config;
770
- });
771
- }
772
- setupResponseInterceptor() {
773
- this.httpClient.interceptors.response.use(async (response) => {
774
- // CRITICAL: Check for skip flag FIRST (set by request interceptor for sync endpoints)
775
- // This completely bypasses Mockifyer interception for sync endpoints
776
- if (response.config.__mockifyer_skip_save || response.config.__mockifyer_bypass) {
777
- return response;
778
- }
779
- // CRITICAL: Skip Mockifyer sync endpoints to prevent infinite loops
780
- // Check multiple ways to get the URL in case response.config is undefined
781
- const url = response.config?.url || response.request?.responseURL || response.url || response.config?.url || '';
782
- // CRITICAL: Check URL FIRST before any other processing
783
- if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(url)) {
784
- // Mark as bypassed to prevent any further processing
785
- response.config.__mockifyer_skip_save = true;
786
- response.config.__mockifyer_bypass = true;
787
- return response;
788
- }
789
- // Clean up processing requests tracking
790
- const requestKey = response.config.__mockifyer_requestKey;
791
- if (requestKey) {
792
- this.processingRequests.delete(requestKey);
793
- }
794
- // CRITICAL: Check response data for Metro rejection messages (defense in depth)
795
- // This catches any responses that might have gotten through
796
- try {
797
- let responseDataStr = '';
798
- let responseDataObj = null;
799
- if (typeof response.data === 'string') {
800
- responseDataStr = response.data;
801
- try {
802
- responseDataObj = JSON.parse(response.data);
803
- }
804
- catch (e) {
805
- // Not JSON, that's fine
806
- }
807
- }
808
- else if (response.data) {
809
- // Try to stringify, but handle circular references
810
- try {
811
- responseDataStr = JSON.stringify(response.data);
812
- responseDataObj = response.data;
813
- }
814
- catch (stringifyError) {
815
- // If stringify fails, try to get a string representation
816
- responseDataStr = String(response.data);
817
- }
818
- }
819
- // CRITICAL: Check for Metro rejection message
820
- const hasRejectionMessage = responseDataStr && (responseDataStr.includes('Cannot save Mockifyer sync endpoint') ||
821
- responseDataStr.includes('Cannot save Mockifyer sync endpoint requests'));
822
- const hasRejectionInObject = responseDataObj && ((responseDataObj.error && typeof responseDataObj.error === 'string' &&
823
- responseDataObj.error.includes('Cannot save Mockifyer sync endpoint')) ||
824
- (responseDataObj.success === false && responseDataObj.error));
825
- if (hasRejectionMessage || hasRejectionInObject) {
826
- return response;
827
- }
828
- // CRITICAL: Check for sync endpoint URLs in response data
829
- if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(responseDataStr)) {
830
- return response;
831
- }
832
- }
833
- catch (e) {
834
- // Ignore errors - continue processing
835
- mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Error checking response data:', e);
836
- }
837
- const isMocked = response.headers && response.headers['x-mockifyer'] === 'true';
838
- const isLimitReached = response.headers && response.headers['x-mockifyer-limit-reached'] === 'true';
839
- if (isMocked || isLimitReached) {
840
- // Local mock hits are logged in the request interceptor; proxy mock hits must
841
- // be recorded here before early return (otherwise flight recorder stays empty).
842
- const shouldLogMockOrLimit = isLimitReached || (isMocked && this.usesDashboardProxy());
843
- if (shouldLogMockOrLimit) {
844
- const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
845
- const reqMethod = (response.config?.method || 'GET').toUpperCase();
846
- const startTime = response.config.__mockifyer_startTime;
847
- const durationMs = startTime ? Date.now() - startTime : undefined;
848
- this.logNetworkEvent({
849
- method: reqMethod,
850
- url: reqUrl,
851
- source: isLimitReached ? 'error' : 'mock-hit',
852
- status: response.status,
853
- durationMs,
854
- transport: this.usesDashboardProxy() ? 'proxy' : 'fetch',
855
- requestBody: response.config?.data,
856
- responseBody: response.data,
857
- ...(isLimitReached
858
- ? {
859
- errorMessage: typeof response.data === 'object' &&
860
- response.data !== null &&
861
- 'message' in response.data
862
- ? String(response.data.message)
863
- : 'Request limit reached',
864
- }
865
- : {}),
866
- }, this.readRequestCorrelation(response.config), response.config?.headers);
867
- }
868
- // Mock hits return before the upstream path. Still emit nested service
869
- // hops and strip mockifyerTrace so the caller sees the business body.
870
- this.unwrapResponseInlineTrace(response);
871
- return response;
872
- }
873
- if (this.config.proxy?.baseUrl && this.config.proxy?.mirrorRecordedMocksToClient) {
874
- await this.maybeMirrorProxyRecordingToClient(response);
875
- }
876
- const matchedMock = response.config.__mockifyer_matchedMock;
877
- if (matchedMock) {
878
- const startTime = response.config.__mockifyer_startTime;
879
- const durationMs = startTime ? Date.now() - startTime : undefined;
880
- const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
881
- const reqMethod = (response.config?.method || 'GET').toUpperCase();
882
- // Parent hop first, then unwrap nested service hops from downstream services.
883
- this.logNetworkEvent({
884
- method: reqMethod,
885
- url: reqUrl,
886
- source: 'upstream',
887
- status: response.status,
888
- durationMs,
889
- requestBody: response.config?.data,
890
- responseBody: response.data,
891
- }, this.readRequestCorrelation(response.config), response.config?.headers);
892
- this.unwrapResponseInlineTrace(response);
893
- const capturedResponse = {
894
- status: response.status,
895
- data: (0, mockifyer_core_1.stripMockifyerTraceFromBody)(response.data),
896
- headers: response.headers || {},
897
- };
898
- if ((0, mockifyer_core_1.resolveShouldPersistLiveCapture)(matchedMock.mockData, this.config)) {
899
- await this.persistMatchedMockAfterLiveCapture(matchedMock, capturedResponse, durationMs, this.readRequestCorrelation(response.config));
900
- }
901
- const liveScenarioPath = path
902
- ? (0, mockifyer_core_1.getScenarioFolderPath)(path.resolve(this.config.mockDataPath), (0, mockifyer_core_1.getCurrentScenario)(path.resolve(this.config.mockDataPath), this.config.clientId))
903
- : undefined;
904
- if (liveScenarioPath) {
905
- (0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(liveScenarioPath, { clientId: this.config.clientId });
906
- }
907
- const clientResponse = (0, mockifyer_core_1.buildClientResponseFromLiveCapture)(matchedMock.mockData, capturedResponse, (0, mockifyer_core_1.createServeTimeClock)(this.config), { filename: matchedMock.filename, scenarioPath: liveScenarioPath });
908
- response.data = clientResponse.data;
909
- response.status = clientResponse.status;
910
- delete response.config.__mockifyer_matchedMock;
911
- return response;
912
- }
913
- const reqUrl = this.resolveLoggedRequestUrl(response.config, url);
914
- const reqMethod = (response.config?.method || 'GET').toUpperCase();
915
- this.logNetworkEvent({
916
- method: reqMethod,
917
- url: reqUrl,
918
- source: 'upstream',
919
- status: response.status,
920
- durationMs: typeof response.config?.metadata?.durationMs === 'number'
921
- ? response.config.metadata.durationMs
922
- : undefined,
923
- requestBody: response.config?.data,
924
- responseBody: response.data,
925
- }, this.readRequestCorrelation(response.config), response.config?.headers);
926
- this.unwrapResponseInlineTrace(response);
927
- // Only save locally if recordMode is enabled AND we're not proxying upstream calls.
928
- // When proxy is configured, recording should happen on the proxy (e.g. dashboard → Redis).
929
- if (this.config.recordMode && !this.config.proxy?.baseUrl) {
930
- await this.saveResponse(response);
931
- }
932
- return response;
933
- }, async (error) => {
934
- const requestKey = error.config?.__mockifyer_requestKey;
935
- if (requestKey) {
936
- this.processingRequests.delete(requestKey);
937
- }
938
- const reqUrl = this.resolveLoggedRequestUrl(error.config);
939
- if (reqUrl) {
940
- this.logNetworkEvent({
941
- method: (error.config?.method || 'GET').toUpperCase(),
942
- url: reqUrl,
943
- source: 'error',
944
- status: error.response?.status,
945
- errorMessage: error?.message ?? String(error),
946
- requestBody: error.config?.data,
947
- responseBody: error.response?.data,
948
- }, this.readRequestCorrelation(error.config), error.config?.headers);
949
- }
950
- this.throwWithMockifyerRequestId(error);
951
- });
952
- }
953
- /**
954
- * When dashboard proxy records to Redis, optionally persist the same payload next to the client
955
- * (Node fs, database provider with `SaveMockOptions.scenario`, or Metro /mockifyer-save for strict RN).
956
- */
957
- async maybeMirrorProxyRecordingToClient(response) {
958
- const rec = response.mockifyerProxyRecording;
959
- if (!rec?.recordedToStore || !rec.storedMock) {
960
- return;
961
- }
962
- const hash = rec.hash?.trim();
963
- const scenarioName = rec.scenarioName?.trim();
964
- const mockData = rec.storedMock;
965
- const providerType = this.config.databaseProvider?.type;
966
- await (0, core_proxy_1.mirrorProxyRecordingToClient)({
967
- config: this.config,
968
- mockDataPath: this.config.mockDataPath,
969
- recording: rec,
970
- databaseProvider: this.databaseProvider,
971
- databaseProviderInitPromise: this.databaseProviderInitPromise,
972
- logPrefix: 'Mockifyer-Fetch',
973
- });
974
- if (providerType === 'hybrid' && hash && scenarioName && mockData) {
975
- await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
976
- }
977
- else if (!fs && hash && scenarioName && mockData) {
978
- await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
979
- }
980
- }
981
- async tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash) {
982
- const metroPort = process.env.METRO_PORT ? parseInt(process.env.METRO_PORT, 10) : 8081;
983
- const fetchFn = global.__mockifyer_original_fetch || fetch;
984
- if (!fetchFn) {
985
- mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Proxy client mirror: no fetch for Metro save');
986
- return;
987
- }
988
- try {
989
- const body = JSON.stringify({
990
- __mockifyerProxyMirror: true,
991
- mockData,
992
- scenarioName,
993
- relativePath: `redis/${hash}.json`,
994
- });
995
- const res = await fetchFn(`http://localhost:${metroPort}/mockifyer-save`, {
996
- method: 'POST',
997
- headers: { 'Content-Type': 'application/json' },
998
- body,
999
- });
1000
- const text = await res.text().catch(() => '');
1001
- if (!res.ok) {
1002
- mockifyer_core_2.logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): HTTP ${res.status} ${text}`);
1003
- return;
1004
- }
1005
- try {
1006
- const parsed = JSON.parse(text);
1007
- if (parsed.success === false) {
1008
- mockifyer_core_2.logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): ${parsed.error || 'save failed'}`);
1009
- return;
1010
- }
1011
- }
1012
- catch {
1013
- // non-JSON response
1014
- }
1015
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (Metro): ${scenarioName}/redis/${hash}.json`);
1016
- }
1017
- catch (e) {
1018
- mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Proxy client mirror (Metro) failed:', e);
1019
- }
1020
- }
1021
- async saveResponse(response) {
1022
- // CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
1023
- if (response.config?.__mockifyer_skip_save || response.config?.__mockifyer_bypass) {
1024
- return;
1025
- }
1026
- // If using a proxy for upstream calls, do not save locally.
1027
- // Proxy mode can record into Redis on miss (recordOnMiss) and keeps the app runtime stateless.
1028
- if (this.config.proxy?.baseUrl) {
1029
- return;
1030
- }
1031
- if ((0, mockifyer_core_1.shouldBlockLocalMockRecording)(this.config)) {
1032
- mockifyer_core_2.logger.info('[Mockifyer-Fetch] Strict proxy-only mode: skipping local mock save (dashboard proxy unavailable).');
1033
- return;
1034
- }
1035
- const url = response.config?.url || response.request?.responseURL || response.url || '';
1036
- if (url && (0, mockifyer_core_1.shouldBypassMockifyerForUrl)(url, this.config.excludedUrls, this.config.baseUrl)) {
1037
- return;
1038
- }
1039
- const recordingExclusions = (0, mockifyer_core_1.resolveRecordingExclusions)(this.config);
1040
- if (url &&
1041
- (0, mockifyer_core_1.shouldExcludeRecording)(url, recordingExclusions, this.config.baseUrl)) {
1042
- return;
1043
- }
1044
- const mayRecordFlag = response.config?.__mockifyer_domain_path_may_record;
1045
- if (mayRecordFlag === false) {
1046
- return;
1047
- }
1048
- if (mayRecordFlag !== true) {
1049
- this.domainPathRules.discover(url, this.config.baseUrl);
1050
- const gate = this.domainPathRules.getTrafficGate(url, this.config.baseUrl);
1051
- if (!gate.mayRecord) {
1052
- return;
1053
- }
1054
- }
1055
- // CRITICAL: Check response data for sync endpoint references and Metro rejection messages
1056
- // This is a defense-in-depth measure
1057
- try {
1058
- let responseDataStr = '';
1059
- if (typeof response.data === 'string') {
1060
- responseDataStr = response.data;
1061
- }
1062
- else if (response.data) {
1063
- try {
1064
- responseDataStr = JSON.stringify(response.data);
1065
- }
1066
- catch (stringifyError) {
1067
- responseDataStr = String(response.data);
1068
- }
1069
- }
1070
- // CRITICAL: Check for Metro rejection message
1071
- if (responseDataStr && responseDataStr.includes('Cannot save Mockifyer sync endpoint')) {
1072
- return;
1073
- }
1074
- // CRITICAL: Check for sync endpoint URLs in response data
1075
- if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(responseDataStr)) {
1076
- return;
1077
- }
1078
- }
1079
- catch (e) {
1080
- // Ignore JSON stringify errors
1081
- mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Error checking response data in saveResponse:', e);
1082
- }
1083
- // Normalize empty params: treat {} the same as undefined for consistent matching
1084
- const rawParams = response.config.params || {};
1085
- const normalizedParams = rawParams && Object.keys(rawParams).length > 0 ? rawParams : undefined;
1086
- const saveLookupRequest = {
1087
- method: response.config.method?.toUpperCase() || 'GET',
1088
- url: response.config.url || '',
1089
- headers: {},
1090
- data: response.config.data,
1091
- queryParams: normalizedParams,
1092
- };
1093
- const requestKey = this.generateRequestKey(saveLookupRequest);
1094
- if (this.savingResponses.has(requestKey)) {
1095
- return;
1096
- }
1097
- const existingMock = await this.findBestMatchingMock(saveLookupRequest, {
1098
- includePassthroughMocks: true,
1099
- });
1100
- const saveDecision = (0, mockifyer_core_1.resolveMockRecordingSaveDecision)(this.config, existingMock?.mockData);
1101
- if (saveDecision.action === 'skip') {
1102
- if (existingMock && (0, mockifyer_core_1.mockPassesThroughToRealApi)(existingMock.mockData)) {
1103
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Passthrough mock exists for ${requestKey}, skipping save (enable refreshPassthroughRecordings to update).`);
1104
- }
1105
- return;
1106
- }
1107
- this.savingResponses.add(requestKey);
1108
- try {
1109
- const rawParamsForSave = response.config.params || {};
1110
- const anonymizedQueryParams = this.anonymizeQueryParams(rawParamsForSave);
1111
- const normalizedParamsForSave = anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
1112
- ? anonymizedQueryParams
1113
- : undefined;
1114
- const now = Date.now();
1115
- if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
1116
- this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
1117
- this.sessionStartTime = now;
1118
- }
1119
- const startTime = response.config.__mockifyer_startTime;
1120
- const duration = startTime ? Date.now() - startTime : undefined;
1121
- const correlation = this.readRequestCorrelation(response.config);
1122
- const hopIds = (0, mockifyer_core_1.resolvePersistedHopIds)(saveDecision.action === 'overwrite' ? existingMock?.mockData : undefined, correlation);
1123
- const storedRequest = {
1124
- method: response.config?.method?.toUpperCase() || 'GET',
1125
- url: response.config?.url || '',
1126
- headers: this.anonymizeHeaders(response.config?.headers || {}),
1127
- data: response.config?.data,
1128
- queryParams: normalizedParamsForSave,
1129
- };
1130
- // Prefer explicit override / config; else request-only default (same as proxy).
1131
- const recordBodies = (0, mockifyer_core_1.resolveLocalRecordResponses)(this.recordResponsesOverride ??
1132
- this.config.proxy?.recordResponses ??
1133
- this.config.recordResponses);
1134
- const mockData = (0, mockifyer_core_1.buildLocalRecordingMockData)({
1135
- request: storedRequest,
1136
- response: {
1137
- status: response.status,
1138
- data: (0, mockifyer_core_1.stripMockifyerTraceFromBody)(response.data),
1139
- headers: response.headers || {},
1140
- },
1141
- recordResponses: recordBodies,
1142
- meta: {
1143
- timestamp: new Date().toISOString(),
1144
- duration,
1145
- sessionId: saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
1146
- ? existingMock.mockData.sessionId
1147
- : this.currentSessionId,
1148
- requestId: hopIds.requestId,
1149
- parentRequestId: hopIds.parentRequestId,
1150
- parentRequestIds: hopIds.parentRequestIds,
1151
- ...((0, mockifyer_core_1.newRecordingUsesAlwaysUseRealApi)() || !recordBodies
1152
- ? { alwaysUseRealApi: true }
1153
- : {}),
1154
- },
1155
- });
1156
- (0, mockifyer_core_1.applyRecordingPassthroughFlag)(mockData, saveDecision.alwaysUseRealApi);
1157
- if (this.databaseProvider) {
1158
- try {
1159
- await this.databaseProvider.save(mockData);
1160
- if (this.config.generateTests?.enabled) {
1161
- await this.generateTestForMock(mockData);
1162
- }
1163
- }
1164
- catch (error) {
1165
- console.error(`[Mockifyer-Fetch] ❌ Error saving mock using ${this.config.databaseProvider?.type} provider:`, error);
1166
- throw error;
1167
- }
1168
- }
1169
- else if (fs && path) {
1170
- const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId);
1171
- const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(this.config.mockDataPath, currentScenario);
1172
- (0, mockifyer_core_1.ensureScenarioFolder)(this.config.mockDataPath, currentScenario);
1173
- const limitCheck = (0, mockifyer_core_1.checkRequestLimit)(this.config.mockDataPath);
1174
- if (limitCheck.limitReached && limitCheck.error) {
1175
- console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
1176
- return;
1177
- }
1178
- if (saveDecision.action === 'overwrite' && existingMock?.filePath) {
1179
- fs.writeFileSync(existingMock.filePath, JSON.stringify(mockData, null, 2));
1180
- mockifyer_core_2.logger.info(`[Mockifyer] Refreshed passthrough mock: ${currentScenario}/${existingMock.filename}`);
1181
- }
1182
- else {
1183
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
1184
- const urlParts = (response.config.url || '').replace(/https?:\/\//, '').split('/');
1185
- const domain = urlParts[0].replace(/\./g, '_');
1186
- const urlPathPart = urlParts.slice(1).join('_') || 'root';
1187
- const filename = `${timestamp}_${response.config.method?.toUpperCase() || 'GET'}_${domain}_${urlPathPart}.json`;
1188
- const filePath = path.join(scenarioPath, filename);
1189
- fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
1190
- mockifyer_core_2.logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${filename}`);
1191
- }
1192
- if (this.config.generateTests?.enabled && this.testGenerator) {
1193
- await this.generateTestForMock(mockData);
1194
- }
1195
- }
1196
- else {
1197
- console.warn('[Mockifyer] Cannot save mock: no database provider and fs/path not available');
1198
- }
1199
- await this.ensureInboundParentStubForChild(hopIds.parentRequestId, response.config);
1200
- }
1201
- finally {
1202
- this.savingResponses.delete(requestKey);
1203
- }
1204
- }
1205
- /**
1206
- * When a child hop is recorded locally, persist a synthetic inbound-parent stub so
1207
- * Hops does not show "Missing entry hop" for the ALS gateway id.
1208
- */
1209
- async ensureInboundParentStubForChild(parentRequestId, config) {
1210
- const activeInbound = (0, mockifyer_core_1.getActiveInboundRequest)();
1211
- const hop = (0, mockifyer_core_1.readOutboundParentHopFromConfig)(config) ??
1212
- (activeInbound ? { method: activeInbound.method, url: activeInbound.url } : undefined);
1213
- try {
1214
- await (0, mockifyer_core_1.ensureLocalInboundParentStubSaved)({
1215
- parentRequestId,
1216
- hop,
1217
- parentExists: (id) => {
1218
- if (!fs || !path || this.databaseProvider) {
1219
- return false;
1220
- }
1221
- const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId);
1222
- const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(this.config.mockDataPath, currentScenario);
1223
- return fs.existsSync(path.join(scenarioPath, (0, mockifyer_core_1.inboundParentStubFilename)(id)));
1224
- },
1225
- save: async (row) => {
1226
- if (this.databaseProvider) {
1227
- await this.databaseProvider.save(row.mock);
1228
- return;
1229
- }
1230
- if (!fs || !path) {
1231
- return;
1232
- }
1233
- const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId);
1234
- const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(this.config.mockDataPath, currentScenario);
1235
- (0, mockifyer_core_1.ensureScenarioFolder)(this.config.mockDataPath, currentScenario);
1236
- const filePath = path.join(scenarioPath, row.filename);
1237
- if (fs.existsSync(filePath)) {
1238
- return;
1239
- }
1240
- fs.writeFileSync(filePath, JSON.stringify(row.mock, null, 2));
1241
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Saved inbound parent stub: ${currentScenario}/${row.filename}`);
1242
- },
1243
- });
1244
- }
1245
- catch (error) {
1246
- const message = error instanceof Error ? error.message : String(error);
1247
- mockifyer_core_2.logger.warn(`[Mockifyer-Fetch] Failed to save inbound parent stub: ${message}`);
1248
- }
1249
- }
1250
- async persistMatchedMockAfterLiveCapture(cachedMock, capturedResponse, durationMs, liveCorrelation) {
1251
- const updated = (0, mockifyer_core_1.buildMockDataAfterLiveCapture)(cachedMock.mockData, capturedResponse, durationMs);
1252
- (0, mockifyer_core_1.applyPersistedHopIds)(updated, (0, mockifyer_core_1.resolvePersistedHopIds)(cachedMock.mockData, liveCorrelation));
1253
- if (this.databaseProvider) {
1254
- await this.databaseProvider.save(updated);
1255
- return;
1256
- }
1257
- if (fs && cachedMock.filePath) {
1258
- fs.writeFileSync(cachedMock.filePath, JSON.stringify(updated, null, 2));
1259
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Refreshed mock from live API: ${cachedMock.filename}`);
1260
- }
1261
- }
1262
- /**
1263
- * Simple path resolution fallback for React Native (when path module is stubbed)
1264
- */
1265
- resolvePath(...parts) {
1266
- if (path && typeof path.resolve === 'function') {
1267
- return path.resolve(...parts);
1268
- }
1269
- // Fallback: simple string-based path resolution
1270
- const cwd = typeof process !== 'undefined' && process.cwd ? process.cwd() : '.';
1271
- const joined = parts
1272
- .filter(p => p)
1273
- .join('/')
1274
- .replace(/\/+/g, '/')
1275
- .replace(/^\.\//, '');
1276
- if (joined.startsWith('/')) {
1277
- return joined;
1278
- }
1279
- return `${cwd}/${joined}`.replace(/\/+/g, '/');
1280
- }
1281
- /**
1282
- * Simple dirname fallback for React Native (when path module is stubbed)
1283
- */
1284
- dirname(filePath) {
1285
- if (path && typeof path.dirname === 'function') {
1286
- return path.dirname(filePath);
1287
- }
1288
- // Fallback: extract directory from path string
1289
- const lastSlash = filePath.lastIndexOf('/');
1290
- if (lastSlash <= 0) {
1291
- return '.';
1292
- }
1293
- return filePath.substring(0, lastSlash);
1294
- }
1295
- /**
1296
- * Generates test file for a mock
1297
- */
1298
- async generateTestForMock(mockData) {
1299
- if (!this.testGenerator) {
1300
- return;
1301
- }
1302
- // Check if fs is available for writing test files
1303
- // In React Native runtime, fs is not available, but in Metro bundler (Node.js) it should be
1304
- // Try to require it dynamically if not already available
1305
- let testFs = fs;
1306
- if (!testFs) {
1307
- try {
1308
- testFs = require('fs');
1309
- }
1310
- catch (e) {
1311
- return;
1312
- }
1313
- }
1314
- // Use the available fs - ensure it's defined and has required methods
1315
- if (!testFs || typeof testFs.writeFileSync !== 'function' || typeof testFs.mkdirSync !== 'function') {
1316
- return;
1317
- }
1318
- const fsToUse = testFs;
1319
- try {
1320
- const options = {
1321
- framework: this.config.generateTests?.framework || 'jest',
1322
- outputPath: this.config.generateTests?.outputPath || './tests/generated',
1323
- testPattern: this.config.generateTests?.testPattern || '{endpoint}.test.ts',
1324
- includeSetup: this.config.generateTests?.includeSetup !== false,
1325
- groupBy: this.config.generateTests?.groupBy || 'file',
1326
- httpClientType: 'fetch'
1327
- };
1328
- const testCode = this.testGenerator.generateTest(mockData, options);
1329
- const testFilePath = this.testGenerator.determineTestFilePath(mockData, options);
1330
- // Resolve to absolute path (relative to process.cwd() which should be project root in Metro)
1331
- // Use our fallback path resolution that works even when path module is stubbed
1332
- const absoluteTestPath = this.resolvePath(testFilePath);
1333
- // Ensure test directory exists
1334
- const testDir = this.dirname(absoluteTestPath);
1335
- if (!fsToUse.existsSync(testDir)) {
1336
- fsToUse.mkdirSync(testDir, { recursive: true });
1337
- }
1338
- // Check if test file already exists
1339
- if (fsToUse.existsSync(absoluteTestPath)) {
1340
- // Extract test info to check if test already exists
1341
- const testInfo = this.testGenerator.analyzeMock(mockData, 'fetch');
1342
- const testName = this.generateTestNameFromInfo(testInfo);
1343
- // Check if test already exists
1344
- const existingContent = fsToUse.readFileSync(absoluteTestPath, 'utf-8');
1345
- if (existingContent.includes(`it('${testName}'`) || existingContent.includes(`it("${testName}"`)) {
1346
- return;
1347
- }
1348
- // Extract test code without imports and describe wrapper
1349
- const testMatch = testCode.match(/it\('.*?', async \(\) => \{[\s\S]*?\}\);?/);
1350
- if (testMatch) {
1351
- // Append test to existing describe block
1352
- const newTest = testMatch[0];
1353
- const updatedContent = existingContent.replace(/(\s+)(\}\);?\s*)$/, `$1${newTest}\n$1$2`);
1354
- fsToUse.writeFileSync(absoluteTestPath, updatedContent);
1355
- }
1356
- }
1357
- else {
1358
- // Create new test file
1359
- fsToUse.writeFileSync(absoluteTestPath, testCode);
1360
- }
1361
- }
1362
- catch (error) {
1363
- mockifyer_core_2.logger.error('[Mockifyer] ❌ Error generating test:', error);
1364
- mockifyer_core_2.logger.error('[Mockifyer] ❌ Error stack:', error?.stack);
1365
- mockifyer_core_2.logger.error('[Mockifyer] ❌ Error message:', error?.message);
1366
- // Don't throw - test generation failure shouldn't break mock saving
1367
- }
1368
- }
1369
- /**
1370
- * Helper to generate test name from test info
1371
- */
1372
- generateTestNameFromInfo(testInfo) {
1373
- const method = testInfo.method.toUpperCase();
1374
- const endpoint = testInfo.endpoint;
1375
- if (testInfo.isGraphQL && testInfo.graphQLQuery) {
1376
- const operationMatch = testInfo.graphQLQuery.match(/(?:query|mutation|subscription)\s+(\w+)/);
1377
- if (operationMatch) {
1378
- return `should execute ${operationMatch[1]} query`;
1379
- }
1380
- return 'should execute GraphQL query';
1381
- }
1382
- return `should ${method} ${endpoint}`;
1383
- }
1384
- anonymizeHeaders(headers) {
1385
- const defaultHeadersToAnonymize = [
1386
- 'x-rapidapi-key', 'x-api-key', 'authorization', 'api-key', 'apikey',
1387
- 'x-auth-token', 'x-access-token', 'bearer'
1388
- ];
1389
- const headersToAnonymize = this.config.anonymizeHeaders !== undefined
1390
- ? this.config.anonymizeHeaders
1391
- : defaultHeadersToAnonymize;
1392
- if (headersToAnonymize.length === 0) {
1393
- return headers;
1394
- }
1395
- const anonymized = { ...headers };
1396
- const lowerCaseHeadersToAnonymize = headersToAnonymize.map((h) => h.toLowerCase());
1397
- Object.keys(anonymized).forEach(key => {
1398
- if (lowerCaseHeadersToAnonymize.includes(key.toLowerCase())) {
1399
- anonymized[key] = '***';
1400
- }
1401
- });
1402
- return anonymized;
1403
- }
1404
- anonymizeQueryParams(params) {
1405
- const defaultParamsToAnonymize = ['key', 'api_key', 'apikey', 'token', 'access_token'];
1406
- const paramsToAnonymize = this.config.anonymizeQueryParams !== undefined
1407
- ? this.config.anonymizeQueryParams
1408
- : defaultParamsToAnonymize;
1409
- if (paramsToAnonymize.length === 0) {
1410
- return params;
1411
- }
1412
- const anonymized = { ...params };
1413
- const lowerCaseParamsToAnonymize = paramsToAnonymize.map((p) => p.toLowerCase());
1414
- Object.keys(anonymized).forEach(key => {
1415
- if (lowerCaseParamsToAnonymize.includes(key.toLowerCase())) {
1416
- anonymized[key] = '***';
1417
- }
1418
- });
1419
- return anonymized;
1420
- }
1421
- /**
1422
- * Updates the logical client lane for subsequent requests (headers, proxy envelope, scenario paths, Redis).
1423
- * Does not re-read native launch arguments or environment variables.
1424
- */
1425
- setClientId(lane) {
1426
- const t = String(lane).trim();
1427
- if (!t) {
1428
- throw new Error('[Mockifyer-Fetch] setClientId requires a non-empty string');
1429
- }
1430
- this.config.clientId = t;
1431
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] clientId set to: ${t}`);
1432
- }
1433
- /** Current logical lane id (same value used for isolation). */
1434
- getClientId() {
1435
- return this.config.clientId;
1436
- }
1437
- /**
1438
- * Turn record mode on/off at runtime (dev menus, tests).
1439
- * Also updates `proxy.recordOnMiss` when a dashboard proxy is configured so
1440
- * Redis/proxy recording follows the same switch as local hybrid saves.
1441
- *
1442
- * When enabling: flips existing allowlist `recordResponses` to true and new
1443
- * discoveries enable recording. When disabled, allowlist discovery stops
1444
- * persisting new keys (so browsing does not poison the rules file).
1445
- */
1446
- setRecordMode(enabled) {
1447
- const next = Boolean(enabled);
1448
- this.config.recordMode = next;
1449
- if (next) {
1450
- // Recording needs live upstream calls; fail-on-miss conflicts with that.
1451
- this.config.failOnMissingMock = false;
1452
- this.domainPathRules.enableRecordResponsesForAllRules();
1453
- }
1454
- if (this.config.proxy?.baseUrl) {
1455
- this.config.proxy = {
1456
- ...this.config.proxy,
1457
- recordOnMiss: next,
1458
- };
1459
- const client = this.httpClient;
1460
- client.setProxyRecordOnMiss?.(next);
1461
- }
1462
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] recordMode set to: ${next}`);
1463
- }
1464
- /** Whether newly unmatched requests can be recorded (local or proxy record-on-miss). */
1465
- isRecordMode() {
1466
- return this.config.recordMode === true;
1467
- }
1468
- /**
1469
- * Whether new recordings store full response bodies (true) or request-only stubs (false, default).
1470
- * Matches dashboard proxy `recordResponses` / env `MOCKIFYER_RECORD_RESPONSES`.
1471
- */
1472
- setRecordResponses(enabled) {
1473
- const next = Boolean(enabled);
1474
- this.recordResponsesOverride = next;
1475
- this.config.recordResponses = next;
1476
- if (this.config.proxy) {
1477
- this.config.proxy = {
1478
- ...this.config.proxy,
1479
- recordResponses: next,
1480
- };
1481
- }
1482
- const client = this.httpClient;
1483
- client.setProxyRecordResponses?.(next);
1484
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] recordResponses (store bodies) set to: ${next}`);
1485
- }
1486
- /** True when new recordings include response bodies (not request-only stubs). */
1487
- isRecordResponses() {
1488
- if (this.config.proxy?.baseUrl) {
1489
- return (0, mockifyer_core_1.resolveRecordResponses)(this.recordResponsesOverride ?? this.config.proxy.recordResponses);
1490
- }
1491
- return (0, mockifyer_core_1.resolveLocalRecordResponses)(this.recordResponsesOverride ?? this.config.recordResponses);
1492
- }
1493
- /**
1494
- * Enable Mockifyer at runtime. All subsequent requests will go through Mockifyer
1495
- * (mock lookup, recording, dashboard/Redis proxy, etc.).
1496
- * When `persistRuntimeEnabled` is set, the preference is saved for the next app launch.
1497
- */
1498
- enableMockifyer() {
1499
- this.runtimeEnabled = true;
1500
- mockifyer_core_2.logger.info('[Mockifyer-Fetch] Mockifyer enabled at runtime');
1501
- void this.persistRuntimeEnabledState(true);
1502
- }
1503
- /**
1504
- * Disable Mockifyer at runtime. All subsequent requests will bypass Mockifyer completely
1505
- * (no dashboard, Redis, proxy, mock lookup, or recording).
1506
- * When `persistRuntimeEnabled` is set, the preference is saved for the next app launch.
1507
- */
1508
- disableMockifyer() {
1509
- this.runtimeEnabled = false;
1510
- mockifyer_core_2.logger.info('[Mockifyer-Fetch] Mockifyer disabled at runtime - all requests will bypass');
1511
- void this.persistRuntimeEnabledState(false);
1512
- }
1513
- /**
1514
- * Check if Mockifyer is currently enabled at runtime.
1515
- */
1516
- isMockifyerEnabled() {
1517
- return this.runtimeEnabled;
1518
- }
1519
- async persistRuntimeEnabledState(enabled) {
1520
- if (!this.runtimeEnabledStorage) {
1521
- return;
1522
- }
1523
- await (0, mockifyer_core_1.savePersistedRuntimeEnabled)(this.runtimeEnabledStorage, enabled);
1524
- }
1525
- getHTTPClient() {
1526
- return this.httpClient;
1527
- }
1528
- async reloadMockData(syncFromProject = true) {
1529
- await this.databaseProviderInitPromise;
1530
- // `$pool` fixtures are cached write-once for RN (no Node fs). Clear so a reload
1531
- // picks up updated pool response bodies from the provider / Metro sync.
1532
- this.poolResponseCache.clear();
1533
- // If provider has a reload method, use it (for ExpoFileSystemProvider with caching)
1534
- // For HybridProvider, this will also sync files from project folder to device
1535
- if (this.databaseProvider && typeof this.databaseProvider.reload === 'function') {
1536
- if (syncFromProject && typeof this.databaseProvider.reload === 'function') {
1537
- // Pass syncFromProject flag if provider supports it (HybridProvider)
1538
- await this.databaseProvider.reload(syncFromProject);
1539
- }
1540
- else {
1541
- await this.databaseProvider.reload();
1542
- }
1543
- }
1544
- else {
1545
- // Fallback: try to load mock data if method exists
1546
- if (typeof this.loadMockData === 'function') {
1547
- this.loadMockData();
1548
- }
1549
- }
1550
- // RN Hybrid: pull domain-path-rules.json via Metro before traffic can discover
1551
- // allowlist defaults that would block already-enabled paths.
1552
- this.domainPathRules.invalidateCache();
1553
- await this.domainPathRules.hydrate();
1554
- }
1555
- clearStaleCacheEntries() {
1556
- return 0; // No cache in fetch implementation
1557
- }
1558
- async clearAllMocks() {
1559
- if (this.databaseProvider && typeof this.databaseProvider.clearAll === 'function') {
1560
- await this.databaseProvider.clearAll();
1561
- }
1562
- else {
1563
- mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Provider does not support clearAll()');
1564
- }
1565
- }
1566
- }
57
+ const mockifyer_class_1 = require("./mockifyer-class");
58
+ Object.defineProperty(exports, "MockifyerClass", { enumerable: true, get: function () { return mockifyer_class_1.MockifyerClass; } });
1567
59
  function setupMockifyer(config) {
1568
60
  // Node-only inbound capture; safe on RN (no-op when not on Node).
1569
61
  if (typeof mockifyer_core_1.installNodeInboundRequestCorrelationCapture === 'function') {
@@ -1599,7 +91,7 @@ function setupMockifyer(config) {
1599
91
  (0, mockifyer_core_1.initializeDateManipulation)(resolvedConfig);
1600
92
  (0, mockifyer_core_1.initializeScenario)(resolvedConfig);
1601
93
  (0, mockifyer_core_1.scheduleRuntimeDateSyncFromConfig)(resolvedConfig);
1602
- const mockifyer = new MockifyerClass(resolvedConfig);
94
+ const mockifyer = new mockifyer_class_1.MockifyerClass(resolvedConfig);
1603
95
  const httpClient = mockifyer.getHTTPClient();
1604
96
  // Always store original fetch (even if not patching global)
1605
97
  let originalFetch;