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