@sgedda/mockifyer-fetch 1.7.0

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 ADDED
@@ -0,0 +1,1106 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.setupMockifyer = setupMockifyer;
18
+ // Fetch-only Mockifyer implementation
19
+ // Conditionally import fs - will be undefined in React Native
20
+ let fs;
21
+ let path;
22
+ try {
23
+ // Try to require fs and path - will fail in React Native where they're stubbed
24
+ fs = require('fs');
25
+ path = require('path');
26
+ }
27
+ catch (e) {
28
+ // fs/path not available (React Native environment)
29
+ fs = undefined;
30
+ path = undefined;
31
+ }
32
+ // Import from core package
33
+ const mockifyer_core_1 = require("@sgedda/mockifyer-core");
34
+ const fetch_client_1 = require("./clients/fetch-client");
35
+ class MockifyerClass {
36
+ constructor(config) {
37
+ this.processingRequests = new Set();
38
+ this.savingResponses = new Set();
39
+ this.currentSessionId = null;
40
+ this.sessionStartTime = 0;
41
+ this.SESSION_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
42
+ // Validate database provider - filesystem, expo-filesystem, hybrid, and memory are supported
43
+ if (config.databaseProvider && config.databaseProvider.type) {
44
+ const supportedTypes = ['filesystem', 'expo-filesystem', 'hybrid', 'memory'];
45
+ if (!supportedTypes.includes(config.databaseProvider.type)) {
46
+ throw new Error(`Database provider type '${config.databaseProvider.type}' is not yet available for use. ` +
47
+ `Supported types: ${supportedTypes.join(', ')}. ` +
48
+ `Please use one of the supported provider types.`);
49
+ }
50
+ }
51
+ // Validate and normalize conflicting settings
52
+ if (config.recordMode && config.failOnMissingMock) {
53
+ console.warn('[Mockifyer] Warning: recordMode is true but failOnMissingMock is also set to true. ' +
54
+ 'failOnMissingMock is ignored in record mode (real API calls are made to record responses). ' +
55
+ 'Setting failOnMissingMock to false.');
56
+ config.failOnMissingMock = false;
57
+ }
58
+ // Validate conflicting similar match settings
59
+ if (config.similarMatchIgnoreAllQueryParams &&
60
+ config.similarMatchRequiredParams &&
61
+ config.similarMatchRequiredParams.length > 0) {
62
+ console.warn('[Mockifyer-Fetch] Warning: Both similarMatchIgnoreAllQueryParams and similarMatchRequiredParams are set. ' +
63
+ 'similarMatchIgnoreAllQueryParams takes precedence and all query parameters will be ignored. ' +
64
+ 'similarMatchRequiredParams will be ignored.');
65
+ // Clear similarMatchRequiredParams to avoid confusion
66
+ config.similarMatchRequiredParams = undefined;
67
+ }
68
+ // Auto-enable useSimilarMatch if similarMatchRequiredParams is set (and not ignored)
69
+ if (config.similarMatchRequiredParams && config.similarMatchRequiredParams.length > 0) {
70
+ if (config.useSimilarMatch === undefined || config.useSimilarMatch === false) {
71
+ config.useSimilarMatch = true;
72
+ }
73
+ }
74
+ // Auto-enable useSimilarMatch if similarMatchIgnoreAllQueryParams is set
75
+ if (config.similarMatchIgnoreAllQueryParams) {
76
+ if (config.useSimilarMatch === undefined || config.useSimilarMatch === false) {
77
+ config.useSimilarMatch = true;
78
+ }
79
+ }
80
+ // Store config BEFORE any modifications
81
+ this.config = { ...config }; // Create a copy to avoid mutations
82
+ // Initialize test generator if test generation is enabled
83
+ console.log('[Mockifyer-Fetch] HÖHÖHÖ 🔧 Constructor - Full config received:', JSON.stringify({
84
+ generateTests: config.generateTests,
85
+ recordMode: config.recordMode,
86
+ mockDataPath: config.mockDataPath,
87
+ databaseProvider: config.databaseProvider?.type
88
+ }, null, 2));
89
+ console.log('[Mockifyer-Fetch] 🔧 Constructor - generateTests config:', JSON.stringify(config.generateTests, null, 2));
90
+ console.log('[Mockifyer-Fetch] 🔧 Constructor - config.generateTests?.enabled:', config.generateTests?.enabled);
91
+ if (config.generateTests?.enabled) {
92
+ console.log('[Mockifyer-Fetch] ✅ Initializing test generator...');
93
+ this.testGenerator = new mockifyer_core_1.TestGenerator();
94
+ console.log('[Mockifyer-Fetch] ✅ Test generator initialized:', !!this.testGenerator);
95
+ }
96
+ else {
97
+ console.log('[Mockifyer-Fetch] ⚠️ Test generation NOT enabled in config');
98
+ console.log('[Mockifyer-Fetch] ⚠️ Debug - config.generateTests:', config.generateTests);
99
+ console.log('[Mockifyer-Fetch] ⚠️ Debug - typeof config.generateTests:', typeof config.generateTests);
100
+ console.log('[Mockifyer-Fetch] ⚠️ Debug - config keys:', Object.keys(config));
101
+ }
102
+ // Initialize database provider if specified
103
+ if (config.databaseProvider && config.databaseProvider.type) {
104
+ this.databaseProvider = (0, mockifyer_core_1.createProvider)(config.databaseProvider.type, config.databaseProvider);
105
+ const initResult = this.databaseProvider.initialize();
106
+ // Handle async initialization (expo-filesystem provider has async initialize)
107
+ if (initResult instanceof Promise) {
108
+ initResult.catch((error) => {
109
+ console.error('[Mockifyer-Fetch] Error initializing database provider:', error);
110
+ });
111
+ }
112
+ }
113
+ else {
114
+ // Fallback to Node.js filesystem
115
+ this.ensureMockDataDirectory();
116
+ }
117
+ // Create fetch HTTP client
118
+ this.httpClient = new fetch_client_1.FetchHTTPClient({
119
+ baseUrl: config.baseUrl,
120
+ defaultHeaders: config.defaultHeaders
121
+ });
122
+ if (!config.recordSameEndpoints) {
123
+ this.loadMockData();
124
+ }
125
+ // Always set up mock response interceptor (to use existing mocks)
126
+ this.setupMockResponses();
127
+ // Set up response interceptor to save responses when recordMode is enabled
128
+ this.setupResponseInterceptor();
129
+ }
130
+ ensureMockDataDirectory() {
131
+ // Only use fs if available (Node.js environment) and no database provider is set
132
+ if (!fs || this.databaseProvider) {
133
+ return;
134
+ }
135
+ if (!fs.existsSync(this.config.mockDataPath)) {
136
+ fs.mkdirSync(this.config.mockDataPath, { recursive: true });
137
+ }
138
+ }
139
+ generateRequestKey(request) {
140
+ return (0, mockifyer_core_1.generateRequestKey)(request);
141
+ }
142
+ async findBestMatchingMock(request) {
143
+ // CRITICAL: Never try to match sync endpoint requests - they should never be mocked
144
+ const requestUrl = request?.url || '';
145
+ if (requestUrl.includes('/mockifyer-save') ||
146
+ requestUrl.includes('/mockifyer-clear') ||
147
+ requestUrl.includes('/mockifyer-sync')) {
148
+ return undefined;
149
+ }
150
+ const requestKey = this.generateRequestKey(request);
151
+ // CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
152
+ if (requestKey.includes('/mockifyer-save') ||
153
+ requestKey.includes('/mockifyer-clear') ||
154
+ requestKey.includes('/mockifyer-sync')) {
155
+ return undefined;
156
+ }
157
+ // Use database provider if available, otherwise fallback to filesystem
158
+ if (this.databaseProvider) {
159
+ return await this.findBestMatchingMockFromProvider(request);
160
+ }
161
+ // Fallback to Node.js filesystem
162
+ return this.findBestMatchingMockFromFiles(request);
163
+ }
164
+ async findBestMatchingMockFromProvider(request) {
165
+ if (!this.databaseProvider) {
166
+ return undefined;
167
+ }
168
+ // CRITICAL: Never try to match sync endpoint requests - they should never be mocked
169
+ const requestUrl = request?.url || '';
170
+ if (requestUrl.includes('/mockifyer-save') ||
171
+ requestUrl.includes('/mockifyer-clear') ||
172
+ requestUrl.includes('/mockifyer-sync')) {
173
+ return undefined;
174
+ }
175
+ const requestKey = this.generateRequestKey(request);
176
+ // CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
177
+ if (requestKey.includes('/mockifyer-save') ||
178
+ requestKey.includes('/mockifyer-clear') ||
179
+ requestKey.includes('/mockifyer-sync')) {
180
+ return undefined;
181
+ }
182
+ // Try exact match first
183
+ const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey);
184
+ if (exactMatch) {
185
+ return exactMatch;
186
+ }
187
+ // Try similar match if enabled
188
+ if (this.config.useSimilarMatch) {
189
+ const similarMatches = await this.databaseProvider.findAllForSimilarMatch(request);
190
+ if (similarMatches && similarMatches.length > 0) {
191
+ // Return first similar match
192
+ return similarMatches[0];
193
+ }
194
+ }
195
+ return undefined;
196
+ }
197
+ findBestMatchingMockFromFiles(request) {
198
+ // Only use fs if available (Node.js environment)
199
+ // This method should never be called when using a database provider
200
+ if (!fs || !path) {
201
+ return undefined;
202
+ }
203
+ const resolvedMockDataPath = path.resolve(this.config.mockDataPath);
204
+ console.log('[Mockifyer-Fetch] 📁 Mock data path:', {
205
+ original: this.config.mockDataPath,
206
+ resolved: resolvedMockDataPath,
207
+ exists: fs.existsSync(resolvedMockDataPath)
208
+ });
209
+ if (!fs.existsSync(resolvedMockDataPath)) {
210
+ console.warn('[Mockifyer-Fetch] ⚠️ Mock data path does not exist:', resolvedMockDataPath);
211
+ return undefined;
212
+ }
213
+ const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(resolvedMockDataPath);
214
+ const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(resolvedMockDataPath, currentScenario);
215
+ console.log('[Mockifyer-Fetch] 📁 Scenario path:', {
216
+ scenario: currentScenario,
217
+ path: scenarioPath,
218
+ exists: fs.existsSync(scenarioPath)
219
+ });
220
+ if (!fs.existsSync(scenarioPath)) {
221
+ console.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
222
+ return undefined;
223
+ }
224
+ const files = fs.readdirSync(scenarioPath)
225
+ .filter(file => file.endsWith('.json'));
226
+ const requestKey = this.generateRequestKey(request);
227
+ let exactMatch;
228
+ let similarMatch;
229
+ console.log('[Mockifyer-Fetch] 🔍 Searching for mock:', {
230
+ requestKey,
231
+ useSimilarMatch: this.config.useSimilarMatch,
232
+ similarMatchIgnoreAllQueryParams: this.config.similarMatchIgnoreAllQueryParams,
233
+ filesCount: files.length,
234
+ files: files.slice(0, 5) // Show first 5 files for debugging
235
+ });
236
+ for (const file of files) {
237
+ try {
238
+ const filePath = path.join(scenarioPath, file);
239
+ const fileContent = fs.readFileSync(filePath, 'utf-8');
240
+ const mockData = JSON.parse(fileContent);
241
+ if (!mockData || !mockData.request || typeof mockData.request !== 'object') {
242
+ continue;
243
+ }
244
+ const mockKey = this.generateRequestKey(mockData.request);
245
+ if (mockKey === requestKey) {
246
+ console.log('[Mockifyer-Fetch] ✅ Exact match found:', file);
247
+ exactMatch = { mockData, filename: file, filePath };
248
+ break;
249
+ }
250
+ if (!exactMatch && this.config.useSimilarMatch && !similarMatch) {
251
+ // Check if it's a GraphQL request - skip similar matching for GraphQL
252
+ const isGraphQL = ['POST', 'PUT', 'PATCH'].includes((request.method || 'GET').toUpperCase()) &&
253
+ request.data &&
254
+ (() => {
255
+ try {
256
+ let bodyData = request.data;
257
+ if (typeof request.data === 'string') {
258
+ bodyData = JSON.parse(request.data);
259
+ }
260
+ return typeof bodyData === 'object' && bodyData !== null && typeof bodyData.query === 'string';
261
+ }
262
+ catch {
263
+ return false;
264
+ }
265
+ })();
266
+ if (!isGraphQL) {
267
+ try {
268
+ const requestUrl = new URL(request.url);
269
+ const mockUrl = new URL(mockData.request.url);
270
+ // Check if pathnames match (exact or pattern-based)
271
+ const requestPathname = requestUrl.pathname;
272
+ const mockPathname = mockUrl.pathname;
273
+ const methodMatch = (mockData.request.method || 'GET').toUpperCase() === (request.method || 'GET').toUpperCase();
274
+ // Check for exact pathname match
275
+ const exactPathnameMatch = mockPathname === requestPathname;
276
+ // Check for pattern-based match (e.g., /posts/71 matches /posts/17 when similarMatchIgnoreAllQueryParams is true)
277
+ // This allows matching paths with different IDs when we're ignoring query params
278
+ let patternMatch = false;
279
+ if (this.config.similarMatchIgnoreAllQueryParams && !exactPathnameMatch && methodMatch) {
280
+ // Extract base path by removing the last segment (ID)
281
+ // /posts/71 -> /posts, /users/2/todos -> /users/2
282
+ const requestSegments = requestPathname.split('/').filter(s => s);
283
+ const mockSegments = mockPathname.split('/').filter(s => s);
284
+ // Match if base paths are the same (same number of segments, all but last match)
285
+ if (requestSegments.length === mockSegments.length && requestSegments.length > 0) {
286
+ const requestBase = requestSegments.slice(0, -1);
287
+ const mockBase = mockSegments.slice(0, -1);
288
+ patternMatch = requestBase.join('/') === mockBase.join('/');
289
+ }
290
+ }
291
+ const pathnameMatch = exactPathnameMatch || patternMatch;
292
+ console.log('[Mockifyer-Fetch] 🔍 Checking similar match:', {
293
+ file,
294
+ requestPathname,
295
+ mockPathname,
296
+ requestMethod: (request.method || 'GET').toUpperCase(),
297
+ mockMethod: (mockData.request.method || 'GET').toUpperCase(),
298
+ exactPathnameMatch,
299
+ patternMatch,
300
+ pathnameMatch,
301
+ methodMatch
302
+ });
303
+ if (pathnameMatch && methodMatch) {
304
+ // If ignoreAllQueryParams is set, skip query param checking entirely
305
+ if (this.config.similarMatchIgnoreAllQueryParams) {
306
+ // Ignore all query params, match on path and method only
307
+ console.log('[Mockifyer-Fetch] ✅ Similar match found (ignoring query params):', file);
308
+ }
309
+ else if (this.config.similarMatchRequiredParams && this.config.similarMatchRequiredParams.length > 0) {
310
+ // Check if required parameters match (if configured)
311
+ const requestParams = request.queryParams || {};
312
+ const mockParams = mockData.request.queryParams || {};
313
+ const allRequiredMatch = this.config.similarMatchRequiredParams.every((paramName) => {
314
+ const requestValue = requestParams[paramName];
315
+ const mockValue = mockParams[paramName];
316
+ return requestValue === undefined && mockValue === undefined
317
+ ? true
318
+ : String(requestValue || '') === String(mockValue || '');
319
+ });
320
+ if (!allRequiredMatch) {
321
+ continue; // Required parameter differs, skip this mock
322
+ }
323
+ }
324
+ similarMatch = { mockData, filename: file, filePath };
325
+ }
326
+ }
327
+ catch (e) {
328
+ continue;
329
+ }
330
+ }
331
+ }
332
+ }
333
+ catch (error) {
334
+ console.warn(`[Mockifyer] Failed to load mock file ${file}:`, error);
335
+ }
336
+ }
337
+ return exactMatch || similarMatch;
338
+ }
339
+ loadMockData() {
340
+ // Skip if using database provider or fs not available
341
+ if (this.databaseProvider || !fs) {
342
+ return;
343
+ }
344
+ if (fs.existsSync(this.config.mockDataPath)) {
345
+ fs.readdirSync(this.config.mockDataPath)
346
+ .filter(file => file.endsWith('.json'));
347
+ }
348
+ }
349
+ setupMockResponses() {
350
+ this.httpClient.interceptors.request.use(async (config) => {
351
+ // CRITICAL: Completely bypass Mockifyer interception for sync endpoints
352
+ // This prevents any Mockifyer processing (mocking, saving, etc.) for these endpoints
353
+ const url = config.url || '';
354
+ if (url.includes('/mockifyer-save') || url.includes('/mockifyer-clear') || url.includes('/mockifyer-sync')) {
355
+ // Mark this request to completely skip Mockifyer processing
356
+ config.__mockifyer_skip_save = true;
357
+ config.__mockifyer_bypass = true;
358
+ return config;
359
+ }
360
+ // Normalize empty params: treat {} the same as undefined for consistent matching
361
+ const rawParams = config.params || {};
362
+ const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
363
+ const normalizedParams = anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
364
+ ? anonymizedQueryParams
365
+ : undefined;
366
+ const request = {
367
+ method: config.method || 'GET',
368
+ url: config.url || '',
369
+ headers: config.headers || {},
370
+ data: config.data,
371
+ queryParams: normalizedParams
372
+ };
373
+ const requestKey = this.generateRequestKey(request);
374
+ // Store request key for response interceptor
375
+ config.__mockifyer_requestKey = requestKey;
376
+ // Store request start time for duration calculation
377
+ config.__mockifyer_startTime = Date.now();
378
+ const cachedMock = await this.findBestMatchingMock(request);
379
+ if (!cachedMock) {
380
+ console.log('[Mockifyer-Fetch] ⚠️ No mock found for request:', {
381
+ method: request.method,
382
+ url: request.url,
383
+ queryParams: request.queryParams,
384
+ requestKey: requestKey,
385
+ mockDataPath: this.config.mockDataPath,
386
+ hasDatabaseProvider: !!this.databaseProvider
387
+ });
388
+ }
389
+ else {
390
+ console.log('[Mockifyer-Fetch] ✅ Mock found:', {
391
+ filename: cachedMock.filename,
392
+ url: request.url
393
+ });
394
+ }
395
+ if (cachedMock) {
396
+ const { mockData, filename, filePath } = cachedMock;
397
+ const responseHeaders = {
398
+ ...mockData.response.headers,
399
+ 'x-mockifyer': 'true',
400
+ 'x-mockifyer-timestamp': mockData.timestamp,
401
+ 'x-mockifyer-filename': filename,
402
+ 'x-mockifyer-filepath': filePath
403
+ };
404
+ const mockResponse = {
405
+ data: mockData.response.data,
406
+ status: mockData.response.status,
407
+ statusText: 'OK',
408
+ headers: responseHeaders,
409
+ config: config
410
+ };
411
+ return {
412
+ ...config,
413
+ __mockResponse: Promise.resolve(mockResponse),
414
+ __mockifyer_requestKey: requestKey
415
+ };
416
+ }
417
+ // Check request limit BEFORE making real API call (only if no mock found and in record mode)
418
+ if (this.config.recordMode) {
419
+ const limitCheck = (0, mockifyer_core_1.checkRequestLimit)(this.config.mockDataPath);
420
+ if (limitCheck.limitReached && limitCheck.error) {
421
+ console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
422
+ // Return a mock error response instead of making a real API call
423
+ const responseHeaders = {
424
+ 'x-mockifyer': 'true',
425
+ 'x-mockifyer-limit-reached': 'true',
426
+ 'content-type': 'application/json'
427
+ };
428
+ const mockErrorResponse = {
429
+ data: {
430
+ error: limitCheck.error.message,
431
+ message: limitCheck.error.message,
432
+ limitReached: true,
433
+ maxRequests: limitCheck.error.maxRequests,
434
+ currentScenario: limitCheck.error.currentScenario
435
+ },
436
+ status: 429, // Too Many Requests
437
+ statusText: 'Too Many Requests',
438
+ headers: responseHeaders,
439
+ config: config
440
+ };
441
+ return {
442
+ ...config,
443
+ __mockResponse: Promise.resolve(mockErrorResponse),
444
+ __mockifyer_requestKey: requestKey,
445
+ __mockifyer_limit_reached: true
446
+ };
447
+ }
448
+ }
449
+ if (this.config.failOnMissingMock) {
450
+ throw new Error(`No mock data found for request: ${this.generateRequestKey(request)}`);
451
+ }
452
+ return config;
453
+ });
454
+ }
455
+ setupResponseInterceptor() {
456
+ this.httpClient.interceptors.response.use(async (response) => {
457
+ // CRITICAL: Check for skip flag FIRST (set by request interceptor for sync endpoints)
458
+ // This completely bypasses Mockifyer interception for sync endpoints
459
+ if (response.config.__mockifyer_skip_save || response.config.__mockifyer_bypass) {
460
+ return response;
461
+ }
462
+ // CRITICAL: Skip Mockifyer sync endpoints to prevent infinite loops
463
+ // Check multiple ways to get the URL in case response.config is undefined
464
+ const url = response.config?.url || response.request?.responseURL || response.url || response.config?.url || '';
465
+ // CRITICAL: Check URL FIRST before any other processing
466
+ if (url && (url.includes('/mockifyer-save') || url.includes('/mockifyer-clear') || url.includes('/mockifyer-sync'))) {
467
+ // Mark as bypassed to prevent any further processing
468
+ response.config.__mockifyer_skip_save = true;
469
+ response.config.__mockifyer_bypass = true;
470
+ return response;
471
+ }
472
+ // Clean up processing requests tracking
473
+ const requestKey = response.config.__mockifyer_requestKey;
474
+ if (requestKey) {
475
+ this.processingRequests.delete(requestKey);
476
+ }
477
+ // CRITICAL: Check response data for Metro rejection messages (defense in depth)
478
+ // This catches any responses that might have gotten through
479
+ try {
480
+ let responseDataStr = '';
481
+ let responseDataObj = null;
482
+ if (typeof response.data === 'string') {
483
+ responseDataStr = response.data;
484
+ try {
485
+ responseDataObj = JSON.parse(response.data);
486
+ }
487
+ catch (e) {
488
+ // Not JSON, that's fine
489
+ }
490
+ }
491
+ else if (response.data) {
492
+ // Try to stringify, but handle circular references
493
+ try {
494
+ responseDataStr = JSON.stringify(response.data);
495
+ responseDataObj = response.data;
496
+ }
497
+ catch (stringifyError) {
498
+ // If stringify fails, try to get a string representation
499
+ responseDataStr = String(response.data);
500
+ }
501
+ }
502
+ // CRITICAL: Check for Metro rejection message
503
+ const hasRejectionMessage = responseDataStr && (responseDataStr.includes('Cannot save Mockifyer sync endpoint') ||
504
+ responseDataStr.includes('Cannot save Mockifyer sync endpoint requests'));
505
+ const hasRejectionInObject = responseDataObj && ((responseDataObj.error && typeof responseDataObj.error === 'string' &&
506
+ responseDataObj.error.includes('Cannot save Mockifyer sync endpoint')) ||
507
+ (responseDataObj.success === false && responseDataObj.error));
508
+ if (hasRejectionMessage || hasRejectionInObject) {
509
+ return response;
510
+ }
511
+ // CRITICAL: Check for sync endpoint URLs in response data
512
+ if (responseDataStr && (responseDataStr.includes('/mockifyer-save') ||
513
+ responseDataStr.includes('/mockifyer-clear') ||
514
+ responseDataStr.includes('/mockifyer-sync'))) {
515
+ console.log('[Mockifyer-Fetch] ⚠️ Bypassing Mockifyer - sync endpoint in response data');
516
+ return response;
517
+ }
518
+ }
519
+ catch (e) {
520
+ // Ignore errors - continue processing
521
+ console.warn('[Mockifyer-Fetch] Error checking response data:', e);
522
+ }
523
+ const isMocked = response.headers && response.headers['x-mockifyer'] === 'true';
524
+ const isLimitReached = response.headers && response.headers['x-mockifyer-limit-reached'] === 'true';
525
+ if (isMocked || isLimitReached) {
526
+ console.log('[Mockifyer-Fetch] Response is mocked, skipping save' + (isLimitReached ? ' (limit reached)' : ''));
527
+ return response;
528
+ }
529
+ // Only save if recordMode is enabled
530
+ if (this.config.recordMode) {
531
+ console.log('[Mockifyer-Fetch] ✅ recordMode enabled, saving response');
532
+ console.log('[Mockifyer-Fetch] Response URL:', response.config?.url);
533
+ console.log('[Mockifyer-Fetch] Response method:', response.config?.method);
534
+ console.log('[Mockifyer-Fetch] Response status:', response.status);
535
+ console.log('[Mockifyer-Fetch] Response config.data:', response.config?.data);
536
+ console.log('[Mockifyer-Fetch] Response config exists:', !!response.config);
537
+ await this.saveResponse(response);
538
+ }
539
+ else {
540
+ console.log('[Mockifyer-Fetch] ⚠️ recordMode disabled, not saving response');
541
+ console.log('[Mockifyer-Fetch] Current config.recordMode:', this.config.recordMode);
542
+ }
543
+ return response;
544
+ }, async (error) => {
545
+ const requestKey = error.config?.__mockifyer_requestKey;
546
+ if (requestKey) {
547
+ this.processingRequests.delete(requestKey);
548
+ }
549
+ throw error;
550
+ });
551
+ }
552
+ async saveResponse(response) {
553
+ console.log('[Mockifyer-Fetch] 💾 saveResponse called');
554
+ console.log('[Mockifyer-Fetch] 💾 Config at saveResponse:', {
555
+ generateTestsEnabled: this.config.generateTests?.enabled,
556
+ hasGenerateTests: !!this.config.generateTests,
557
+ recordMode: this.config.recordMode,
558
+ hasDatabaseProvider: !!this.databaseProvider
559
+ });
560
+ console.log('[Mockifyer-Fetch] saveResponse - response.config:', response.config ? {
561
+ url: response.config.url,
562
+ method: response.config.method,
563
+ hasData: !!response.config.data,
564
+ dataType: typeof response.config.data
565
+ } : 'NO CONFIG');
566
+ // CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
567
+ if (response.config?.__mockifyer_skip_save || response.config?.__mockifyer_bypass) {
568
+ console.log('[Mockifyer-Fetch] ⚠️ saveResponse: BLOCKING - bypass flag set');
569
+ return;
570
+ }
571
+ // CRITICAL: Skip saving responses from Mockifyer sync endpoints and Resend API FIRST
572
+ // Check multiple ways to get the URL in case response.config is undefined
573
+ const url = response.config?.url || response.request?.responseURL || response.url || '';
574
+ if (url && (url.includes('/mockifyer-save') ||
575
+ url.includes('/mockifyer-clear') ||
576
+ url.includes('/mockifyer-sync') ||
577
+ url.includes('api.resend.com'))) {
578
+ console.log('[Mockifyer-Fetch] ⚠️ Skipping save - Resend API request:', url);
579
+ return;
580
+ }
581
+ // CRITICAL: Check response data for sync endpoint references and Metro rejection messages
582
+ // This is a defense-in-depth measure
583
+ try {
584
+ let responseDataStr = '';
585
+ if (typeof response.data === 'string') {
586
+ responseDataStr = response.data;
587
+ }
588
+ else if (response.data) {
589
+ try {
590
+ responseDataStr = JSON.stringify(response.data);
591
+ }
592
+ catch (stringifyError) {
593
+ responseDataStr = String(response.data);
594
+ }
595
+ }
596
+ // CRITICAL: Check for Metro rejection message
597
+ if (responseDataStr && responseDataStr.includes('Cannot save Mockifyer sync endpoint')) {
598
+ return;
599
+ }
600
+ // CRITICAL: Check for sync endpoint URLs in response data
601
+ if (responseDataStr && (responseDataStr.includes('/mockifyer-save') ||
602
+ responseDataStr.includes('/mockifyer-clear') ||
603
+ responseDataStr.includes('/mockifyer-sync'))) {
604
+ return;
605
+ }
606
+ }
607
+ catch (e) {
608
+ // Ignore JSON stringify errors
609
+ console.warn('[Mockifyer-Fetch] Error checking response data in saveResponse:', e);
610
+ }
611
+ // Normalize empty params: treat {} the same as undefined for consistent matching
612
+ const rawParams = response.config.params || {};
613
+ const normalizedParams = rawParams && Object.keys(rawParams).length > 0 ? rawParams : undefined;
614
+ const requestKey = this.generateRequestKey({
615
+ method: response.config.method?.toUpperCase() || 'GET',
616
+ url: response.config.url || '',
617
+ headers: {},
618
+ data: response.config.data,
619
+ queryParams: normalizedParams
620
+ });
621
+ if (this.savingResponses.has(requestKey)) {
622
+ return;
623
+ }
624
+ this.savingResponses.add(requestKey);
625
+ try {
626
+ // Normalize empty params: treat {} the same as undefined for consistent matching
627
+ const rawParams = response.config.params || {};
628
+ const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
629
+ const normalizedParams = anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
630
+ ? anonymizedQueryParams
631
+ : undefined;
632
+ // Generate or reuse sessionId
633
+ const now = Date.now();
634
+ if (!this.currentSessionId || (now - this.sessionStartTime) > this.SESSION_TIMEOUT_MS) {
635
+ // Generate new session ID
636
+ this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
637
+ this.sessionStartTime = now;
638
+ }
639
+ // Calculate request duration if start time is available
640
+ const startTime = response.config.__mockifyer_startTime;
641
+ const duration = startTime ? Date.now() - startTime : undefined;
642
+ const mockData = {
643
+ request: {
644
+ method: response.config?.method?.toUpperCase() || 'GET',
645
+ url: response.config?.url || '',
646
+ headers: this.anonymizeHeaders(response.config?.headers || {}),
647
+ data: response.config?.data,
648
+ queryParams: normalizedParams
649
+ },
650
+ response: {
651
+ status: response.status,
652
+ data: response.data,
653
+ headers: response.headers || {}
654
+ },
655
+ timestamp: new Date().toISOString(),
656
+ duration,
657
+ sessionId: this.currentSessionId
658
+ };
659
+ console.log('[Mockifyer-Fetch] Saving mock data:', {
660
+ method: mockData.request.method,
661
+ url: mockData.request.url,
662
+ hasRequestData: !!mockData.request.data,
663
+ responseStatus: mockData.response.status,
664
+ provider: this.config.databaseProvider?.type || 'filesystem'
665
+ });
666
+ // Use database provider if available, otherwise fallback to filesystem
667
+ if (this.databaseProvider) {
668
+ try {
669
+ console.log('[Mockifyer-Fetch] 💾 Saving mock via database provider...');
670
+ await this.databaseProvider.save(mockData);
671
+ console.log('[Mockifyer-Fetch] ✅ Successfully saved mock using provider');
672
+ // Generate test if enabled (try to write test files even with database provider)
673
+ // In React Native Metro bundler (Node.js), fs/path are available for writing test files
674
+ console.log('[Mockifyer-Fetch] 🔍 Checking test generation config...');
675
+ console.log('[Mockifyer-Fetch] 🔍 this.config.generateTests:', JSON.stringify(this.config.generateTests, null, 2));
676
+ console.log('[Mockifyer-Fetch] 🔍 this.config.generateTests?.enabled:', this.config.generateTests?.enabled);
677
+ if (this.config.generateTests?.enabled) {
678
+ console.log('[Mockifyer-Fetch] 🔧 Test generation enabled, attempting to generate test...');
679
+ console.log('[Mockifyer-Fetch] 🔧 Test generator available:', !!this.testGenerator);
680
+ console.log('[Mockifyer-Fetch] 🔧 fs available:', !!fs);
681
+ console.log('[Mockifyer-Fetch] 🔧 path available:', !!path);
682
+ await this.generateTestForMock(mockData);
683
+ }
684
+ else {
685
+ console.log('[Mockifyer-Fetch] ⚠️ Test generation NOT enabled - skipping');
686
+ console.log('[Mockifyer-Fetch] ⚠️ Config check:', {
687
+ hasGenerateTests: !!this.config.generateTests,
688
+ enabled: this.config.generateTests?.enabled,
689
+ fullConfig: JSON.stringify(this.config.generateTests)
690
+ });
691
+ }
692
+ }
693
+ catch (error) {
694
+ console.error(`[Mockifyer-Fetch] ❌ Error saving mock using ${this.config.databaseProvider?.type} provider:`, error);
695
+ throw error;
696
+ }
697
+ }
698
+ else if (fs && path) {
699
+ // Fallback to Node.js filesystem (only if fs/path are available)
700
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
701
+ const urlParts = (response.config.url || '').replace(/https?:\/\//, '').split('/');
702
+ const domain = urlParts[0].replace(/\./g, '_');
703
+ const urlPathPart = urlParts.slice(1).join('_') || 'root';
704
+ const filename = `${timestamp}_${response.config.method?.toUpperCase() || 'GET'}_${domain}_${urlPathPart}.json`;
705
+ const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath);
706
+ const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(this.config.mockDataPath, currentScenario);
707
+ (0, mockifyer_core_1.ensureScenarioFolder)(this.config.mockDataPath, currentScenario);
708
+ // Check request limit before saving (only if limit is set via env var)
709
+ const limitCheck = (0, mockifyer_core_1.checkRequestLimit)(this.config.mockDataPath);
710
+ if (limitCheck.limitReached && limitCheck.error) {
711
+ console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
712
+ // Don't throw - just log and return to prevent app crash
713
+ return;
714
+ }
715
+ const filePath = path.join(scenarioPath, filename);
716
+ fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
717
+ console.log(`[Mockifyer] Saved new mock to file: ${currentScenario}/${filename}`);
718
+ // Generate test if enabled
719
+ if (this.config.generateTests?.enabled && this.testGenerator) {
720
+ await this.generateTestForMock(mockData);
721
+ }
722
+ }
723
+ else {
724
+ console.warn('[Mockifyer] Cannot save mock: no database provider and fs/path not available');
725
+ }
726
+ }
727
+ finally {
728
+ this.savingResponses.delete(requestKey);
729
+ }
730
+ }
731
+ /**
732
+ * Simple path resolution fallback for React Native (when path module is stubbed)
733
+ */
734
+ resolvePath(...parts) {
735
+ if (path && typeof path.resolve === 'function') {
736
+ return path.resolve(...parts);
737
+ }
738
+ // Fallback: simple string-based path resolution
739
+ const cwd = typeof process !== 'undefined' && process.cwd ? process.cwd() : '.';
740
+ const joined = parts
741
+ .filter(p => p)
742
+ .join('/')
743
+ .replace(/\/+/g, '/')
744
+ .replace(/^\.\//, '');
745
+ if (joined.startsWith('/')) {
746
+ return joined;
747
+ }
748
+ return `${cwd}/${joined}`.replace(/\/+/g, '/');
749
+ }
750
+ /**
751
+ * Simple dirname fallback for React Native (when path module is stubbed)
752
+ */
753
+ dirname(filePath) {
754
+ if (path && typeof path.dirname === 'function') {
755
+ return path.dirname(filePath);
756
+ }
757
+ // Fallback: extract directory from path string
758
+ const lastSlash = filePath.lastIndexOf('/');
759
+ if (lastSlash <= 0) {
760
+ return '.';
761
+ }
762
+ return filePath.substring(0, lastSlash);
763
+ }
764
+ /**
765
+ * Generates test file for a mock
766
+ */
767
+ async generateTestForMock(mockData) {
768
+ if (!this.testGenerator) {
769
+ return;
770
+ }
771
+ // Check if fs is available for writing test files
772
+ // In React Native runtime, fs is not available, but in Metro bundler (Node.js) it should be
773
+ // Try to require it dynamically if not already available
774
+ let testFs = fs;
775
+ if (!testFs) {
776
+ try {
777
+ testFs = require('fs');
778
+ console.log('[Mockifyer] ✅ Found fs module for test generation');
779
+ }
780
+ catch (e) {
781
+ console.log('[Mockifyer] ⚠️ Test generation skipped: fs not available');
782
+ console.log('[Mockifyer] 💡 Tip: Test generation requires Node.js fs module.');
783
+ console.log('[Mockifyer] 💡 In React Native, tests are generated in Metro bundler (Node.js environment).');
784
+ return;
785
+ }
786
+ }
787
+ // Use the available fs - ensure it's defined and has required methods
788
+ if (!testFs || typeof testFs.writeFileSync !== 'function' || typeof testFs.mkdirSync !== 'function') {
789
+ console.log('[Mockifyer] ⚠️ Test generation skipped: fs module missing required methods');
790
+ console.log('[Mockifyer] 💡 fs.writeFileSync:', typeof testFs?.writeFileSync);
791
+ console.log('[Mockifyer] 💡 fs.mkdirSync:', typeof testFs?.mkdirSync);
792
+ return;
793
+ }
794
+ const fsToUse = testFs;
795
+ try {
796
+ const options = {
797
+ framework: this.config.generateTests?.framework || 'jest',
798
+ outputPath: this.config.generateTests?.outputPath || './tests/generated',
799
+ testPattern: this.config.generateTests?.testPattern || '{endpoint}.test.ts',
800
+ includeSetup: this.config.generateTests?.includeSetup !== false,
801
+ groupBy: this.config.generateTests?.groupBy || 'file',
802
+ httpClientType: 'fetch'
803
+ };
804
+ console.log('[Mockifyer] 📝 Test generation options:', JSON.stringify(options, null, 2));
805
+ const testCode = this.testGenerator.generateTest(mockData, options);
806
+ const testFilePath = this.testGenerator.determineTestFilePath(mockData, options);
807
+ console.log('[Mockifyer] 📝 Generated test file path:', testFilePath);
808
+ // Resolve to absolute path (relative to process.cwd() which should be project root in Metro)
809
+ // Use our fallback path resolution that works even when path module is stubbed
810
+ const absoluteTestPath = this.resolvePath(testFilePath);
811
+ console.log('[Mockifyer] 📝 Final absolute test path:', absoluteTestPath);
812
+ // Ensure test directory exists
813
+ const testDir = this.dirname(absoluteTestPath);
814
+ console.log('[Mockifyer] 📝 Test directory:', testDir);
815
+ if (!fsToUse.existsSync(testDir)) {
816
+ console.log('[Mockifyer] 📝 Creating test directory:', testDir);
817
+ fsToUse.mkdirSync(testDir, { recursive: true });
818
+ }
819
+ // Check if test file already exists
820
+ if (fsToUse.existsSync(absoluteTestPath)) {
821
+ console.log('[Mockifyer] 📝 Test file already exists, checking if test needs to be appended...');
822
+ // Extract test info to check if test already exists
823
+ const testInfo = this.testGenerator.analyzeMock(mockData, 'fetch');
824
+ const testName = this.generateTestNameFromInfo(testInfo);
825
+ // Check if test already exists
826
+ const existingContent = fsToUse.readFileSync(absoluteTestPath, 'utf-8');
827
+ if (existingContent.includes(`it('${testName}'`) || existingContent.includes(`it("${testName}"`)) {
828
+ console.log(`[Mockifyer] ✅ Test already exists in ${absoluteTestPath}, skipping generation`);
829
+ return;
830
+ }
831
+ // Extract test code without imports and describe wrapper
832
+ const testMatch = testCode.match(/it\('.*?', async \(\) => \{[\s\S]*?\}\);?/);
833
+ if (testMatch) {
834
+ // Append test to existing describe block
835
+ const newTest = testMatch[0];
836
+ const updatedContent = existingContent.replace(/(\s+)(\}\);?\s*)$/, `$1${newTest}\n$1$2`);
837
+ fsToUse.writeFileSync(absoluteTestPath, updatedContent);
838
+ console.log(`[Mockifyer] ✅ Appended test to existing file: ${absoluteTestPath}`);
839
+ }
840
+ }
841
+ else {
842
+ // Create new test file
843
+ console.log('[Mockifyer] 📝 Creating new test file...');
844
+ fsToUse.writeFileSync(absoluteTestPath, testCode);
845
+ console.log(`[Mockifyer] ✅ Generated test: ${absoluteTestPath}`);
846
+ console.log(`[Mockifyer] ✅ Test file size: ${fsToUse.statSync(absoluteTestPath).size} bytes`);
847
+ }
848
+ }
849
+ catch (error) {
850
+ console.error('[Mockifyer] ❌ Error generating test:', error);
851
+ console.error('[Mockifyer] ❌ Error stack:', error?.stack);
852
+ console.error('[Mockifyer] ❌ Error message:', error?.message);
853
+ // Don't throw - test generation failure shouldn't break mock saving
854
+ }
855
+ }
856
+ /**
857
+ * Helper to generate test name from test info
858
+ */
859
+ generateTestNameFromInfo(testInfo) {
860
+ const method = testInfo.method.toUpperCase();
861
+ const endpoint = testInfo.endpoint;
862
+ if (testInfo.isGraphQL && testInfo.graphQLQuery) {
863
+ const operationMatch = testInfo.graphQLQuery.match(/(?:query|mutation|subscription)\s+(\w+)/);
864
+ if (operationMatch) {
865
+ return `should execute ${operationMatch[1]} query`;
866
+ }
867
+ return 'should execute GraphQL query';
868
+ }
869
+ return `should ${method} ${endpoint}`;
870
+ }
871
+ anonymizeHeaders(headers) {
872
+ const defaultHeadersToAnonymize = [
873
+ 'x-rapidapi-key', 'x-api-key', 'authorization', 'api-key', 'apikey',
874
+ 'x-auth-token', 'x-access-token', 'bearer'
875
+ ];
876
+ const headersToAnonymize = this.config.anonymizeHeaders !== undefined
877
+ ? this.config.anonymizeHeaders
878
+ : defaultHeadersToAnonymize;
879
+ if (headersToAnonymize.length === 0) {
880
+ return headers;
881
+ }
882
+ const anonymized = { ...headers };
883
+ const lowerCaseHeadersToAnonymize = headersToAnonymize.map((h) => h.toLowerCase());
884
+ Object.keys(anonymized).forEach(key => {
885
+ if (lowerCaseHeadersToAnonymize.includes(key.toLowerCase())) {
886
+ anonymized[key] = '***';
887
+ }
888
+ });
889
+ return anonymized;
890
+ }
891
+ anonymizeQueryParams(params) {
892
+ const defaultParamsToAnonymize = ['key', 'api_key', 'apikey', 'token', 'access_token'];
893
+ const paramsToAnonymize = this.config.anonymizeQueryParams !== undefined
894
+ ? this.config.anonymizeQueryParams
895
+ : defaultParamsToAnonymize;
896
+ if (paramsToAnonymize.length === 0) {
897
+ return params;
898
+ }
899
+ const anonymized = { ...params };
900
+ const lowerCaseParamsToAnonymize = paramsToAnonymize.map((p) => p.toLowerCase());
901
+ Object.keys(anonymized).forEach(key => {
902
+ if (lowerCaseParamsToAnonymize.includes(key.toLowerCase())) {
903
+ anonymized[key] = '***';
904
+ }
905
+ });
906
+ return anonymized;
907
+ }
908
+ getHTTPClient() {
909
+ return this.httpClient;
910
+ }
911
+ async reloadMockData(syncFromProject = true) {
912
+ // If provider has a reload method, use it (for ExpoFileSystemProvider with caching)
913
+ // For HybridProvider, this will also sync files from project folder to device
914
+ if (this.databaseProvider && typeof this.databaseProvider.reload === 'function') {
915
+ if (syncFromProject && typeof this.databaseProvider.reload === 'function') {
916
+ // Pass syncFromProject flag if provider supports it (HybridProvider)
917
+ await this.databaseProvider.reload(syncFromProject);
918
+ }
919
+ else {
920
+ await this.databaseProvider.reload();
921
+ }
922
+ }
923
+ else {
924
+ // Fallback: try to load mock data if method exists
925
+ if (typeof this.loadMockData === 'function') {
926
+ this.loadMockData();
927
+ }
928
+ }
929
+ }
930
+ clearStaleCacheEntries() {
931
+ return 0; // No cache in fetch implementation
932
+ }
933
+ async clearAllMocks() {
934
+ if (this.databaseProvider && typeof this.databaseProvider.clearAll === 'function') {
935
+ await this.databaseProvider.clearAll();
936
+ }
937
+ else {
938
+ console.warn('[Mockifyer-Fetch] Provider does not support clearAll()');
939
+ }
940
+ }
941
+ }
942
+ function setupMockifyer(config) {
943
+ console.log('[Mockifyer-Fetch] 🚀 setupMockifyer called with config:', JSON.stringify({
944
+ generateTests: config.generateTests,
945
+ recordMode: config.recordMode,
946
+ mockDataPath: config.mockDataPath,
947
+ databaseProvider: config.databaseProvider?.type
948
+ }, null, 2));
949
+ // Set environment variables for Metro middleware to read test generation config
950
+ // This allows Metro middleware (which runs in Node.js) to generate tests
951
+ // when Hybrid Provider saves mocks via Metro endpoint
952
+ if (config.generateTests?.enabled) {
953
+ process.env.MOCKIFYER_GENERATE_TESTS = 'true';
954
+ if (config.generateTests.framework) {
955
+ process.env.MOCKIFYER_TEST_FRAMEWORK = config.generateTests.framework;
956
+ }
957
+ if (config.generateTests.outputPath) {
958
+ process.env.MOCKIFYER_TEST_OUTPUT_PATH = config.generateTests.outputPath;
959
+ }
960
+ if (config.generateTests.testPattern) {
961
+ process.env.MOCKIFYER_TEST_PATTERN = config.generateTests.testPattern;
962
+ }
963
+ if (config.generateTests.includeSetup === false) {
964
+ process.env.MOCKIFYER_TEST_INCLUDE_SETUP = 'false';
965
+ }
966
+ if (config.generateTests.groupBy) {
967
+ process.env.MOCKIFYER_TEST_GROUP_BY = config.generateTests.groupBy;
968
+ }
969
+ if (config.generateTests.uniqueTestsPerEndpoint) {
970
+ process.env.MOCKIFYER_UNIQUE_TESTS_PER_ENDPOINT = 'true';
971
+ }
972
+ }
973
+ (0, mockifyer_core_1.initializeDateManipulation)(config);
974
+ (0, mockifyer_core_1.initializeScenario)(config);
975
+ console.log('[Mockifyer-Fetch] 🚀 After initializeScenario - config:', JSON.stringify({
976
+ generateTests: config.generateTests,
977
+ recordMode: config.recordMode
978
+ }, null, 2));
979
+ const mockifyer = new MockifyerClass(config);
980
+ const httpClient = mockifyer.getHTTPClient();
981
+ // Always store original fetch (even if not patching global)
982
+ let originalFetch;
983
+ if (global.__mockifyer_original_fetch) {
984
+ originalFetch = global.__mockifyer_original_fetch;
985
+ }
986
+ else {
987
+ originalFetch = global.fetch;
988
+ global.__mockifyer_original_fetch = originalFetch;
989
+ }
990
+ const fetchClient = httpClient;
991
+ if (fetchClient && typeof fetchClient.performRequest === 'function') {
992
+ fetchClient._originalFetch = originalFetch;
993
+ }
994
+ // Patch global fetch if useGlobalFetch is true
995
+ if (config.useGlobalFetch) {
996
+ const mockifyerInstance = mockifyer;
997
+ const originalFetchForPatched = global.__mockifyer_original_fetch || originalFetch;
998
+ global.fetch = async function (input, init) {
999
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
1000
+ const method = init?.method || 'GET';
1001
+ const headers = init?.headers || {};
1002
+ const body = init?.body;
1003
+ // Skip Mockifyer sync endpoints and Resend API to prevent infinite loops
1004
+ if (url.includes('/mockifyer-save') || url.includes('/mockifyer-clear') || url.includes('/mockifyer-sync') || url.includes('api.resend.com')) {
1005
+ return await originalFetchForPatched(input, init);
1006
+ }
1007
+ const simpleRequestKey = `${method}:${url}`;
1008
+ const isProcessing = mockifyerInstance.processingRequests?.has(simpleRequestKey);
1009
+ if (isProcessing) {
1010
+ return await originalFetchForPatched(input, init);
1011
+ }
1012
+ let params = undefined;
1013
+ let baseUrl = url;
1014
+ try {
1015
+ const urlObj = new URL(url);
1016
+ if (urlObj.search) {
1017
+ params = {};
1018
+ urlObj.searchParams.forEach((value, key) => {
1019
+ params[key] = value;
1020
+ });
1021
+ urlObj.search = '';
1022
+ baseUrl = urlObj.toString();
1023
+ }
1024
+ }
1025
+ catch (error) {
1026
+ // URL parsing failed, use URL as-is
1027
+ }
1028
+ let headersObj = {};
1029
+ if (headers instanceof Headers) {
1030
+ headers.forEach((value, key) => {
1031
+ headersObj[key] = value;
1032
+ });
1033
+ }
1034
+ else if (Array.isArray(headers)) {
1035
+ headers.forEach(([key, value]) => {
1036
+ headersObj[key] = value;
1037
+ });
1038
+ }
1039
+ else {
1040
+ headersObj = headers;
1041
+ }
1042
+ try {
1043
+ const requestConfig = {
1044
+ url: baseUrl,
1045
+ method: method,
1046
+ headers: headersObj,
1047
+ params: params,
1048
+ data: body ? (typeof body === 'string' ? (body.startsWith('{') || body.startsWith('[') ? JSON.parse(body) : body) : body) : undefined
1049
+ };
1050
+ const response = await httpClient.request(requestConfig);
1051
+ const responseHeaders = new Headers();
1052
+ // Copy all headers from response, ensuring x-mockifyer header is included if present
1053
+ if (response.headers) {
1054
+ Object.entries(response.headers).forEach(([key, value]) => {
1055
+ if (value !== undefined && value !== null) {
1056
+ responseHeaders.set(key, String(value));
1057
+ }
1058
+ });
1059
+ // Debug: Verify x-mockifyer header is present
1060
+ if (response.headers['x-mockifyer']) {
1061
+ console.log('[Mockifyer-Fetch] ✅ x-mockifyer header found in response:', response.headers['x-mockifyer']);
1062
+ }
1063
+ else {
1064
+ console.warn('[Mockifyer-Fetch] ⚠️ x-mockifyer header NOT found in response.headers');
1065
+ console.warn('[Mockifyer-Fetch] Available headers:', Object.keys(response.headers));
1066
+ }
1067
+ }
1068
+ else {
1069
+ console.warn('[Mockifyer-Fetch] ⚠️ response.headers is undefined/null');
1070
+ }
1071
+ const responseBody = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
1072
+ return new Response(responseBody, {
1073
+ status: response.status,
1074
+ statusText: response.statusText || '',
1075
+ headers: responseHeaders
1076
+ });
1077
+ }
1078
+ catch (error) {
1079
+ if (error.response) {
1080
+ const responseHeaders = new Headers();
1081
+ Object.entries(error.response.headers || {}).forEach(([key, value]) => {
1082
+ responseHeaders.set(key, String(value));
1083
+ });
1084
+ const errorBody = typeof error.response.data === 'string'
1085
+ ? error.response.data
1086
+ : JSON.stringify(error.response.data);
1087
+ return new Response(errorBody, {
1088
+ status: error.response.status,
1089
+ statusText: error.response.statusText || '',
1090
+ headers: responseHeaders
1091
+ });
1092
+ }
1093
+ throw error;
1094
+ }
1095
+ };
1096
+ }
1097
+ const extendedClient = httpClient;
1098
+ extendedClient.reloadMockData = async () => await mockifyer.reloadMockData();
1099
+ extendedClient.clearStaleCacheEntries = () => mockifyer.clearStaleCacheEntries();
1100
+ extendedClient.clearAllMocks = () => mockifyer.clearAllMocks();
1101
+ return extendedClient;
1102
+ }
1103
+ // Re-export types from core
1104
+ __exportStar(require("@sgedda/mockifyer-core"), exports);
1105
+ // Export React Native helpers
1106
+ __exportStar(require("./react-native"), exports);