@sgedda/mockifyer-fetch 1.7.0 → 1.7.2
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 +60 -0
- package/dist/index.js +18 -165
- package/dist/metro-config.d.ts +89 -8
- package/dist/metro-config.js +126 -8
- package/dist/metro-sync-middleware.js +36 -19
- package/dist/react-native.js +8 -7
- package/package.json +4 -3
- package/src/clients/fetch-client.d.ts +14 -0
- package/src/clients/fetch-client.d.ts.map +1 -0
- package/src/clients/fetch-client.js +75 -0
- package/src/index.d.ts +10 -0
- package/src/index.d.ts.map +1 -0
- package/src/index.js +966 -0
- package/src/index.ts +18 -166
- package/src/metro-config.ts +153 -9
- package/src/metro-sync-middleware.ts +40 -20
- package/src/react-native.d.ts +45 -0
- package/src/react-native.d.ts.map +1 -0
- package/src/react-native.js +141 -0
- package/src/react-native.ts +8 -7
package/dist/metro-config.js
CHANGED
|
@@ -4,8 +4,9 @@
|
|
|
4
4
|
*
|
|
5
5
|
* This helper configures Metro to stub Node.js built-in modules that aren't
|
|
6
6
|
* available in React Native, allowing Mockifyer to bundle successfully.
|
|
7
|
+
* Optionally sets up sync middleware for Hybrid Provider.
|
|
7
8
|
*
|
|
8
|
-
* @example
|
|
9
|
+
* @example Basic usage (fs stubbing only):
|
|
9
10
|
* ```javascript
|
|
10
11
|
* const { getDefaultConfig } = require('expo/metro-config');
|
|
11
12
|
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
@@ -13,9 +14,40 @@
|
|
|
13
14
|
* const config = getDefaultConfig(__dirname);
|
|
14
15
|
* module.exports = configureMetroForMockifyer(config);
|
|
15
16
|
* ```
|
|
17
|
+
*
|
|
18
|
+
* @example With sync middleware (for Hybrid Provider):
|
|
19
|
+
* ```javascript
|
|
20
|
+
* const { getDefaultConfig } = require('expo/metro-config');
|
|
21
|
+
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
22
|
+
*
|
|
23
|
+
* const config = getDefaultConfig(__dirname);
|
|
24
|
+
* module.exports = configureMetroForMockifyer(config, {
|
|
25
|
+
* syncMiddleware: {
|
|
26
|
+
* projectRoot: __dirname,
|
|
27
|
+
* mockDataPath: './mock-data',
|
|
28
|
+
* },
|
|
29
|
+
* });
|
|
30
|
+
* ```
|
|
31
|
+
*
|
|
32
|
+
* @example With auto-sync (for ExpoFileSystem Provider - syncs files from device to project folder):
|
|
33
|
+
* ```javascript
|
|
34
|
+
* const { getDefaultConfig } = require('expo/metro-config');
|
|
35
|
+
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
36
|
+
*
|
|
37
|
+
* const config = getDefaultConfig(__dirname);
|
|
38
|
+
* module.exports = configureMetroForMockifyer(config, {
|
|
39
|
+
* autoSync: {
|
|
40
|
+
* enabled: true,
|
|
41
|
+
* intervalMs: 5000,
|
|
42
|
+
* projectRoot: __dirname,
|
|
43
|
+
* mockDataPath: './mock-data',
|
|
44
|
+
* },
|
|
45
|
+
* });
|
|
46
|
+
* ```
|
|
16
47
|
*/
|
|
17
48
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
49
|
exports.configureMetroForMockifyer = configureMetroForMockifyer;
|
|
50
|
+
const mockifyer_core_1 = require("@sgedda/mockifyer-core");
|
|
19
51
|
/**
|
|
20
52
|
* Node.js built-in modules that need to be stubbed for React Native
|
|
21
53
|
* Includes modules used by Mockifyer packages and their dependencies:
|
|
@@ -27,15 +59,16 @@ const NODE_BUILTINS = ['fs', 'path', 'assert', 'util'];
|
|
|
27
59
|
/**
|
|
28
60
|
* Configure Metro bundler for Mockifyer
|
|
29
61
|
*
|
|
30
|
-
* This function
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
62
|
+
* This function:
|
|
63
|
+
* 1. Adds resolver configuration to stub Node.js built-in modules (fs, path, assert, util)
|
|
64
|
+
* 2. Optionally sets up sync middleware for Hybrid Provider (if syncMiddleware options provided)
|
|
65
|
+
* 3. Optionally sets up auto-sync polling (if autoSync options provided - needed for ExpoFileSystem Provider, not needed with Hybrid Provider)
|
|
34
66
|
*
|
|
35
67
|
* @param config - Existing Metro config (e.g., from getDefaultConfig)
|
|
36
|
-
* @
|
|
68
|
+
* @param options - Optional configuration including sync middleware setup
|
|
69
|
+
* @returns Metro config with Mockifyer configuration merged in
|
|
37
70
|
*
|
|
38
|
-
* @example
|
|
71
|
+
* @example Basic usage (fs stubbing only):
|
|
39
72
|
* ```javascript
|
|
40
73
|
* const { getDefaultConfig } = require('expo/metro-config');
|
|
41
74
|
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
@@ -43,8 +76,38 @@ const NODE_BUILTINS = ['fs', 'path', 'assert', 'util'];
|
|
|
43
76
|
* const config = getDefaultConfig(__dirname);
|
|
44
77
|
* module.exports = configureMetroForMockifyer(config);
|
|
45
78
|
* ```
|
|
79
|
+
*
|
|
80
|
+
* @example With sync middleware (for Hybrid Provider):
|
|
81
|
+
* ```javascript
|
|
82
|
+
* const { getDefaultConfig } = require('expo/metro-config');
|
|
83
|
+
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
84
|
+
*
|
|
85
|
+
* const config = getDefaultConfig(__dirname);
|
|
86
|
+
* module.exports = configureMetroForMockifyer(config, {
|
|
87
|
+
* syncMiddleware: {
|
|
88
|
+
* projectRoot: __dirname,
|
|
89
|
+
* mockDataPath: './mock-data',
|
|
90
|
+
* },
|
|
91
|
+
* });
|
|
92
|
+
* ```
|
|
93
|
+
*
|
|
94
|
+
* @example With auto-sync (for ExpoFileSystem Provider - syncs files from device to project folder):
|
|
95
|
+
* ```javascript
|
|
96
|
+
* const { getDefaultConfig } = require('expo/metro-config');
|
|
97
|
+
* const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
|
|
98
|
+
*
|
|
99
|
+
* const config = getDefaultConfig(__dirname);
|
|
100
|
+
* module.exports = configureMetroForMockifyer(config, {
|
|
101
|
+
* autoSync: {
|
|
102
|
+
* enabled: true,
|
|
103
|
+
* intervalMs: 5000,
|
|
104
|
+
* projectRoot: __dirname,
|
|
105
|
+
* mockDataPath: './mock-data',
|
|
106
|
+
* },
|
|
107
|
+
* });
|
|
108
|
+
* ```
|
|
46
109
|
*/
|
|
47
|
-
function configureMetroForMockifyer(config) {
|
|
110
|
+
function configureMetroForMockifyer(config, options) {
|
|
48
111
|
// Get path to empty module stub
|
|
49
112
|
// Resolve using the package export path, which points to metro-polyfills/empty-module.js
|
|
50
113
|
let emptyModulePath;
|
|
@@ -79,6 +142,61 @@ function configureMetroForMockifyer(config) {
|
|
|
79
142
|
// Fallback to default Metro resolution
|
|
80
143
|
return context.resolveRequest(context, moduleName, platform);
|
|
81
144
|
};
|
|
145
|
+
// Set up sync middleware if options provided
|
|
146
|
+
if (options?.syncMiddleware) {
|
|
147
|
+
try {
|
|
148
|
+
const { createMockSyncMiddleware } = require('./metro-sync-middleware');
|
|
149
|
+
const syncMiddleware = createMockSyncMiddleware({
|
|
150
|
+
projectRoot: options.syncMiddleware.projectRoot || process.cwd(),
|
|
151
|
+
mockDataPath: options.syncMiddleware.mockDataPath || 'mock-data',
|
|
152
|
+
testGeneration: options.syncMiddleware.testGeneration,
|
|
153
|
+
});
|
|
154
|
+
// Add middleware to server config
|
|
155
|
+
// Expo Metro uses enhanceMiddleware, but also supports middleware array
|
|
156
|
+
config.server = config.server || {};
|
|
157
|
+
// Use enhanceMiddleware if available (Expo Metro standard)
|
|
158
|
+
// enhanceMiddleware receives existing middleware and returns new middleware
|
|
159
|
+
const existingEnhance = config.server.enhanceMiddleware;
|
|
160
|
+
config.server.enhanceMiddleware = (middleware) => {
|
|
161
|
+
// Return a middleware function that runs our syncMiddleware first,
|
|
162
|
+
// then calls the existing enhanced middleware
|
|
163
|
+
return (req, res, next) => {
|
|
164
|
+
// Try our middleware first (it calls next() if not handling the request)
|
|
165
|
+
syncMiddleware(req, res, (err) => {
|
|
166
|
+
if (err) {
|
|
167
|
+
return next(err);
|
|
168
|
+
}
|
|
169
|
+
// If our middleware didn't handle it, call the existing middleware
|
|
170
|
+
if (!res.headersSent) {
|
|
171
|
+
return middleware(req, res, next);
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
};
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
catch (e) {
|
|
178
|
+
mockifyer_core_1.logger.warn('[Metro] Could not set up Mockifyer sync middleware:', e);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
// Set up auto-sync (polling-based sync from iOS Simulator to project folder) if options provided
|
|
182
|
+
// Required when using ExpoFileSystem Provider to sync files from device to project folder for code search
|
|
183
|
+
// Not needed with Hybrid Provider (uses instant HTTP sync via syncMiddleware)
|
|
184
|
+
if (options?.autoSync?.enabled) {
|
|
185
|
+
try {
|
|
186
|
+
const { startAutoSync } = require('./metro-sync-middleware');
|
|
187
|
+
const intervalMs = options.autoSync.intervalMs || 5000;
|
|
188
|
+
const projectRoot = options.autoSync.projectRoot || process.cwd();
|
|
189
|
+
const mockDataPath = options.autoSync.mockDataPath || 'mock-data';
|
|
190
|
+
startAutoSync(intervalMs, {
|
|
191
|
+
projectRoot,
|
|
192
|
+
mockDataPath,
|
|
193
|
+
});
|
|
194
|
+
console.log(`[Metro] ✅ Auto-sync enabled: polling every ${intervalMs}ms`);
|
|
195
|
+
}
|
|
196
|
+
catch (e) {
|
|
197
|
+
mockifyer_core_1.logger.warn('[Metro] Could not set up Mockifyer auto-sync:', e);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
82
200
|
// Merge config with new resolver
|
|
83
201
|
return {
|
|
84
202
|
...config,
|
|
@@ -51,6 +51,7 @@ exports.stopAutoSync = stopAutoSync;
|
|
|
51
51
|
exports.syncFromIOSSimulator = syncFromIOSSimulator;
|
|
52
52
|
const fs = __importStar(require("fs"));
|
|
53
53
|
const path = __importStar(require("path"));
|
|
54
|
+
const mockifyer_core_1 = require("@sgedda/mockifyer-core");
|
|
54
55
|
const DEFAULT_SCENARIO = 'default';
|
|
55
56
|
let autoSyncInterval = null;
|
|
56
57
|
/**
|
|
@@ -139,11 +140,9 @@ function generateTestForMock(mockData, testConfig, projectRoot) {
|
|
|
139
140
|
}
|
|
140
141
|
}
|
|
141
142
|
catch (e) {
|
|
142
|
-
console.log(`[MockSync] ⚠️ Could not load TestGenerator: ${e.message}`);
|
|
143
143
|
return false;
|
|
144
144
|
}
|
|
145
145
|
if (!TestGeneratorClass) {
|
|
146
|
-
console.log('[MockSync] ⚠️ TestGenerator not available');
|
|
147
146
|
return false;
|
|
148
147
|
}
|
|
149
148
|
const generator = new TestGeneratorClass();
|
|
@@ -162,7 +161,6 @@ function generateTestForMock(mockData, testConfig, projectRoot) {
|
|
|
162
161
|
const testDir = path.dirname(absoluteTestPath);
|
|
163
162
|
// If uniqueTestsPerEndpoint is enabled, check if a test file already exists
|
|
164
163
|
if (options.uniqueTestsPerEndpoint && fs.existsSync(absoluteTestPath)) {
|
|
165
|
-
console.log(`[MockSync] ✅ Test file already exists for endpoint ${testInfo.method} ${testInfo.endpoint}, skipping generation`);
|
|
166
164
|
return true;
|
|
167
165
|
}
|
|
168
166
|
// Ensure test directory exists
|
|
@@ -175,7 +173,6 @@ function generateTestForMock(mockData, testConfig, projectRoot) {
|
|
|
175
173
|
const testName = `${testInfo.method} ${testInfo.endpoint}`;
|
|
176
174
|
const existingContent = fs.readFileSync(absoluteTestPath, 'utf-8');
|
|
177
175
|
if (existingContent.includes(`it('${testName}'`) || existingContent.includes(`it("${testName}"`)) {
|
|
178
|
-
console.log(`[MockSync] ✅ Test already exists in ${absoluteTestPath}, skipping generation`);
|
|
179
176
|
return true;
|
|
180
177
|
}
|
|
181
178
|
// Append test to existing file
|
|
@@ -184,19 +181,17 @@ function generateTestForMock(mockData, testConfig, projectRoot) {
|
|
|
184
181
|
const newTest = testMatch[0];
|
|
185
182
|
const updatedContent = existingContent.replace(/(\s+)(\}\);?\s*)$/, `$1${newTest}\n$1$2`);
|
|
186
183
|
fs.writeFileSync(absoluteTestPath, updatedContent);
|
|
187
|
-
console.log(`[MockSync] ✅ Appended test to existing file: ${absoluteTestPath}`);
|
|
188
184
|
return true;
|
|
189
185
|
}
|
|
190
186
|
}
|
|
191
187
|
else {
|
|
192
188
|
// Create new test file
|
|
193
189
|
fs.writeFileSync(absoluteTestPath, testCode);
|
|
194
|
-
console.log(`[MockSync] ✅ Generated test: ${absoluteTestPath}`);
|
|
195
190
|
}
|
|
196
191
|
return true;
|
|
197
192
|
}
|
|
198
193
|
catch (error) {
|
|
199
|
-
|
|
194
|
+
mockifyer_core_1.logger.error(`[MockSync] ❌ Error generating test:`, error);
|
|
200
195
|
return false;
|
|
201
196
|
}
|
|
202
197
|
}
|
|
@@ -215,7 +210,7 @@ function saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig
|
|
|
215
210
|
// Also check if the mockData string contains nested sync requests
|
|
216
211
|
const mockDataStr = JSON.stringify(mockData);
|
|
217
212
|
if (mockDataStr.includes('/mockifyer-save') || mockDataStr.includes('/mockifyer-clear') || mockDataStr.includes('/mockifyer-sync')) {
|
|
218
|
-
|
|
213
|
+
mockifyer_core_1.logger.warn(`[MockSync] ⚠️ Rejecting save - Mock data contains nested Mockifyer sync requests`);
|
|
219
214
|
return { success: false, error: 'Mock data contains nested Mockifyer sync requests' };
|
|
220
215
|
}
|
|
221
216
|
// Get current scenario and ensure scenario folder exists
|
|
@@ -236,12 +231,10 @@ function saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig
|
|
|
236
231
|
const filePath = path.join(scenarioPath, filename);
|
|
237
232
|
// Check if file already exists - skip saving if it does
|
|
238
233
|
if (fs.existsSync(filePath)) {
|
|
239
|
-
console.log(`[MockSync] ⚠️ File already exists, skipping save: ${filename}`);
|
|
240
234
|
return { success: true, filename, skipped: true, reason: 'File already exists' };
|
|
241
235
|
}
|
|
242
236
|
// Write to file
|
|
243
237
|
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
244
|
-
console.log(`[MockSync] ✅ Saved mock to project folder: ${currentScenario}/${filename}`);
|
|
245
238
|
// Generate test file if enabled
|
|
246
239
|
if (testConfig) {
|
|
247
240
|
generateTestForMock(mockData, testConfig, projectRoot);
|
|
@@ -272,11 +265,10 @@ function clearMockFiles(mockDataPath) {
|
|
|
272
265
|
deleted++;
|
|
273
266
|
}
|
|
274
267
|
});
|
|
275
|
-
console.log(`[MockSync] ✅ Cleared ${deleted} mock files from ${currentScenario}`);
|
|
276
268
|
return { success: true, filesDeleted: deleted };
|
|
277
269
|
}
|
|
278
270
|
catch (error) {
|
|
279
|
-
|
|
271
|
+
mockifyer_core_1.logger.error(`[MockSync] ❌ Error clearing mock files:`, error);
|
|
280
272
|
return { success: false, error: error.message };
|
|
281
273
|
}
|
|
282
274
|
}
|
|
@@ -333,7 +325,6 @@ function syncFromIOSSimulator(projectRoot, mockDataPath) {
|
|
|
333
325
|
syncedFiles.push(file);
|
|
334
326
|
}
|
|
335
327
|
});
|
|
336
|
-
console.log(`[MockSync] ✅ Synced ${filesSynced} files from iOS Simulator to ${currentScenario}`);
|
|
337
328
|
break;
|
|
338
329
|
}
|
|
339
330
|
}
|
|
@@ -353,6 +344,8 @@ function createMockSyncMiddleware(options) {
|
|
|
353
344
|
const projectRoot = options?.projectRoot || process.cwd();
|
|
354
345
|
const mockDataPath = path.resolve(projectRoot, options?.mockDataPath || 'mock-data');
|
|
355
346
|
const testConfig = getTestGenerationConfig(options);
|
|
347
|
+
// Log the resolved paths for debugging
|
|
348
|
+
mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Initialized with projectRoot: ${projectRoot}, mockDataPath: ${mockDataPath}`);
|
|
356
349
|
return function mockSyncMiddleware(req, res, next) {
|
|
357
350
|
const url = req.url.split('?')[0]; // Remove query params
|
|
358
351
|
// Handle POST endpoint for clearing mocks
|
|
@@ -412,18 +405,44 @@ function createMockSyncMiddleware(options) {
|
|
|
412
405
|
// Handle GET endpoint for scenario config
|
|
413
406
|
if (url === '/mockifyer-scenario-config' && req.method === 'GET') {
|
|
414
407
|
try {
|
|
408
|
+
// Check environment variable first (highest priority)
|
|
409
|
+
if (process.env.MOCKIFYER_SCENARIO) {
|
|
410
|
+
mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Using scenario from MOCKIFYER_SCENARIO env var: ${process.env.MOCKIFYER_SCENARIO}`);
|
|
411
|
+
res.setHeader('Content-Type', 'application/json');
|
|
412
|
+
res.end(JSON.stringify({
|
|
413
|
+
success: true,
|
|
414
|
+
currentScenario: process.env.MOCKIFYER_SCENARIO
|
|
415
|
+
}));
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
415
418
|
const configPath = path.join(mockDataPath, 'scenario-config.json');
|
|
419
|
+
const resolvedPath = path.resolve(configPath);
|
|
420
|
+
mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Reading scenario config from: ${resolvedPath}`);
|
|
421
|
+
mockifyer_core_1.logger.info(`[MetroSyncMiddleware] mockDataPath: ${mockDataPath}, projectRoot: ${projectRoot}`);
|
|
416
422
|
if (fs.existsSync(configPath)) {
|
|
417
|
-
const
|
|
423
|
+
const fileContent = fs.readFileSync(configPath, 'utf-8');
|
|
424
|
+
mockifyer_core_1.logger.info(`[MetroSyncMiddleware] File content: ${fileContent}`);
|
|
425
|
+
const config = JSON.parse(fileContent);
|
|
426
|
+
const scenario = config.currentScenario || DEFAULT_SCENARIO;
|
|
427
|
+
mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Found scenario in config: ${scenario} (from file: ${JSON.stringify(config)})`);
|
|
418
428
|
res.setHeader('Content-Type', 'application/json');
|
|
419
|
-
|
|
429
|
+
// Return format expected by ExpoFileSystemProvider: { success: true, currentScenario: ... }
|
|
430
|
+
res.end(JSON.stringify({
|
|
431
|
+
success: true,
|
|
432
|
+
currentScenario: scenario
|
|
433
|
+
}));
|
|
420
434
|
}
|
|
421
435
|
else {
|
|
436
|
+
mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Config file not found at ${resolvedPath}, returning default scenario`);
|
|
422
437
|
res.setHeader('Content-Type', 'application/json');
|
|
423
|
-
res.end(JSON.stringify({
|
|
438
|
+
res.end(JSON.stringify({
|
|
439
|
+
success: true,
|
|
440
|
+
currentScenario: DEFAULT_SCENARIO
|
|
441
|
+
}));
|
|
424
442
|
}
|
|
425
443
|
}
|
|
426
444
|
catch (error) {
|
|
445
|
+
mockifyer_core_1.logger.error(`[MetroSyncMiddleware] Error reading scenario config:`, error);
|
|
427
446
|
res.statusCode = 500;
|
|
428
447
|
res.setHeader('Content-Type', 'application/json');
|
|
429
448
|
res.end(JSON.stringify({ success: false, error: error.message }));
|
|
@@ -461,12 +480,11 @@ function createMockSyncMiddleware(options) {
|
|
|
461
480
|
*/
|
|
462
481
|
function startAutoSync(intervalMs = 5000, options) {
|
|
463
482
|
if (autoSyncInterval) {
|
|
464
|
-
console.log('[MockSync] Auto-sync already running');
|
|
465
483
|
return;
|
|
466
484
|
}
|
|
467
485
|
const projectRoot = options?.projectRoot || process.cwd();
|
|
468
486
|
const mockDataPath = path.resolve(projectRoot, options?.mockDataPath || 'mock-data');
|
|
469
|
-
|
|
487
|
+
mockifyer_core_1.logger.info(`[MockSync] Starting auto-sync every ${intervalMs}ms`);
|
|
470
488
|
autoSyncInterval = setInterval(() => {
|
|
471
489
|
syncFromIOSSimulator(projectRoot, mockDataPath);
|
|
472
490
|
}, intervalMs);
|
|
@@ -478,6 +496,5 @@ function stopAutoSync() {
|
|
|
478
496
|
if (autoSyncInterval) {
|
|
479
497
|
clearInterval(autoSyncInterval);
|
|
480
498
|
autoSyncInterval = null;
|
|
481
|
-
console.log('[MockSync] Auto-sync disabled');
|
|
482
499
|
}
|
|
483
500
|
}
|
package/dist/react-native.js
CHANGED
|
@@ -9,6 +9,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
9
9
|
exports.setupMockifyerForReactNative = setupMockifyerForReactNative;
|
|
10
10
|
const index_1 = require("./index");
|
|
11
11
|
const mockifyer_core_1 = require("@sgedda/mockifyer-core");
|
|
12
|
+
const mockifyer_core_2 = require("@sgedda/mockifyer-core");
|
|
12
13
|
// Lazy load bundled data (only used in production builds)
|
|
13
14
|
let bundledMockData = null;
|
|
14
15
|
/**
|
|
@@ -40,7 +41,7 @@ async function loadBundledMockData(bundledDataPath) {
|
|
|
40
41
|
return data;
|
|
41
42
|
}
|
|
42
43
|
catch (error) {
|
|
43
|
-
|
|
44
|
+
mockifyer_core_2.logger.warn('[Mockifyer] Could not load bundled mock data:', error);
|
|
44
45
|
return [];
|
|
45
46
|
}
|
|
46
47
|
}
|
|
@@ -67,7 +68,7 @@ async function setupMockifyerForReactNative(options) {
|
|
|
67
68
|
// Check if Mockifyer is enabled
|
|
68
69
|
const isEnabled = process.env.MOCKIFYER_ENABLED === 'true' || isDev;
|
|
69
70
|
if (!isEnabled) {
|
|
70
|
-
|
|
71
|
+
mockifyer_core_2.logger.info('[Mockifyer] Disabled');
|
|
71
72
|
return null;
|
|
72
73
|
}
|
|
73
74
|
if (isDev === true) {
|
|
@@ -103,10 +104,10 @@ async function setupMockifyerForReactNative(options) {
|
|
|
103
104
|
useGlobalFetch: true,
|
|
104
105
|
...config,
|
|
105
106
|
});
|
|
106
|
-
|
|
107
|
-
|
|
107
|
+
mockifyer_core_2.logger.info('[Mockifyer] Development mode: Using Hybrid provider (device + project folder)');
|
|
108
|
+
mockifyer_core_2.logger.info(`[Mockifyer] Metro endpoint: http://localhost:${metroPort}/mockifyer-save`);
|
|
108
109
|
if (recordMode) {
|
|
109
|
-
|
|
110
|
+
mockifyer_core_2.logger.info('[Mockifyer] Recording mode enabled - new API responses will be saved');
|
|
110
111
|
}
|
|
111
112
|
return instance;
|
|
112
113
|
}
|
|
@@ -118,7 +119,7 @@ async function setupMockifyerForReactNative(options) {
|
|
|
118
119
|
// Load bundled mock data
|
|
119
120
|
const mockDataArray = await loadBundledMockData(bundledDataPath);
|
|
120
121
|
if (mockDataArray.length === 0) {
|
|
121
|
-
|
|
122
|
+
mockifyer_core_2.logger.warn('[Mockifyer] No bundled mock data found. Make sure to run the build script first.');
|
|
122
123
|
return null;
|
|
123
124
|
}
|
|
124
125
|
// Pre-load all mocks into memory
|
|
@@ -134,7 +135,7 @@ async function setupMockifyerForReactNative(options) {
|
|
|
134
135
|
useGlobalFetch: true,
|
|
135
136
|
...config,
|
|
136
137
|
});
|
|
137
|
-
|
|
138
|
+
mockifyer_core_2.logger.info(`[Mockifyer] Production mode: Loaded ${mockDataArray.length} mocks from bundle`);
|
|
138
139
|
return instance;
|
|
139
140
|
}
|
|
140
141
|
}
|
package/package.json
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sgedda/mockifyer-fetch",
|
|
3
|
-
"version": "1.7.
|
|
3
|
+
"version": "1.7.2",
|
|
4
4
|
"description": "Mockifyer for Fetch - API mocking and logging utility for storing and replaying API responses",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
|
+
"react-native": "dist/react-native.js",
|
|
7
8
|
"exports": {
|
|
8
9
|
".": {
|
|
10
|
+
"react-native": "./dist/react-native.js",
|
|
9
11
|
"types": "./dist/index.d.ts",
|
|
10
12
|
"default": "./dist/index.js"
|
|
11
13
|
},
|
|
@@ -44,7 +46,7 @@
|
|
|
44
46
|
"author": "sgedda",
|
|
45
47
|
"license": "MIT",
|
|
46
48
|
"dependencies": {
|
|
47
|
-
"@sgedda/mockifyer-core": "^1.7.
|
|
49
|
+
"@sgedda/mockifyer-core": "^1.7.1"
|
|
48
50
|
},
|
|
49
51
|
"publishConfig": {
|
|
50
52
|
"access": "public"
|
|
@@ -54,4 +56,3 @@
|
|
|
54
56
|
"url": "git+https://github.com/sgedda/mockifyer.git"
|
|
55
57
|
}
|
|
56
58
|
}
|
|
57
|
-
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { BaseHTTPClient } from '@sgedda/mockifyer-core';
|
|
2
|
+
import { HTTPRequestConfig, HTTPResponse } from '@sgedda/mockifyer-core';
|
|
3
|
+
export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
|
|
4
|
+
private baseUrl?;
|
|
5
|
+
private defaultHeaders;
|
|
6
|
+
constructor(config?: {
|
|
7
|
+
baseUrl?: string;
|
|
8
|
+
defaultHeaders?: Record<string, string>;
|
|
9
|
+
});
|
|
10
|
+
protected performRequest<D = any>(config: HTTPRequestConfig<D>): Promise<HTTPResponse<any>>;
|
|
11
|
+
protected getDefaultHeaders(): Record<string, string>;
|
|
12
|
+
protected getDefaultConfig(): Record<string, any>;
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=fetch-client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetch-client.d.ts","sourceRoot":"","sources":["fetch-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAEzE,qBAAa,eAAgB,SAAQ,cAAc,CAAC,GAAG,EAAE,YAAY,CAAC,GAAG,CAAC,CAAC;IACzE,OAAO,CAAC,OAAO,CAAC,CAAS;IACzB,OAAO,CAAC,cAAc,CAAyB;gBAEnC,MAAM,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAC;QAAC,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE;cAMlE,cAAc,CAAC,CAAC,GAAG,GAAG,EAAE,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC;IA+DjG,SAAS,CAAC,iBAAiB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IAIrD,SAAS,CAAC,gBAAgB,IAAI,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;CAKlD"}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.FetchHTTPClient = void 0;
|
|
4
|
+
const mockifyer_core_1 = require("@sgedda/mockifyer-core");
|
|
5
|
+
class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
|
|
6
|
+
constructor(config) {
|
|
7
|
+
super();
|
|
8
|
+
this.baseUrl = config === null || config === void 0 ? void 0 : config.baseUrl;
|
|
9
|
+
this.defaultHeaders = (config === null || config === void 0 ? void 0 : config.defaultHeaders) || {};
|
|
10
|
+
}
|
|
11
|
+
async performRequest(config) {
|
|
12
|
+
// Check if this is a mock response (set by Mockifyer interceptor)
|
|
13
|
+
if (config.__mockResponse) {
|
|
14
|
+
return config.__mockResponse;
|
|
15
|
+
}
|
|
16
|
+
let url = this.baseUrl ? new URL(config.url || '', this.baseUrl).toString() : config.url;
|
|
17
|
+
if (!url) {
|
|
18
|
+
throw new Error('URL is required');
|
|
19
|
+
}
|
|
20
|
+
// Handle query parameters (params) - append them to the URL
|
|
21
|
+
if (config.params && Object.keys(config.params).length > 0) {
|
|
22
|
+
try {
|
|
23
|
+
const urlObj = new URL(url);
|
|
24
|
+
Object.entries(config.params).forEach(([key, value]) => {
|
|
25
|
+
if (value !== undefined && value !== null) {
|
|
26
|
+
urlObj.searchParams.append(key, String(value));
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
url = urlObj.toString();
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
console.error('[FetchHTTPClient] Error adding params to URL:', error);
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const headers = new Headers({
|
|
37
|
+
...this.defaultHeaders,
|
|
38
|
+
...config.headers
|
|
39
|
+
});
|
|
40
|
+
const requestConfig = {
|
|
41
|
+
method: config.method || 'GET',
|
|
42
|
+
headers,
|
|
43
|
+
body: config.data ? JSON.stringify(config.data) : undefined
|
|
44
|
+
};
|
|
45
|
+
// Use original fetch if available (when global fetch is patched), otherwise use global fetch
|
|
46
|
+
// CRITICAL: Always use _originalFetch if available to prevent infinite loops
|
|
47
|
+
const fetchFn = this._originalFetch || fetch;
|
|
48
|
+
if (!this._originalFetch) {
|
|
49
|
+
console.warn('[FetchHTTPClient] _originalFetch not set! This may cause infinite loops if global fetch is patched.');
|
|
50
|
+
}
|
|
51
|
+
const response = await fetchFn(url, requestConfig);
|
|
52
|
+
const data = await response.json();
|
|
53
|
+
// Convert response Headers to Record<string, string>
|
|
54
|
+
const responseHeaders = {};
|
|
55
|
+
response.headers.forEach((value, key) => {
|
|
56
|
+
responseHeaders[key] = value;
|
|
57
|
+
});
|
|
58
|
+
return {
|
|
59
|
+
data,
|
|
60
|
+
status: response.status,
|
|
61
|
+
statusText: response.statusText,
|
|
62
|
+
headers: responseHeaders,
|
|
63
|
+
config
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
getDefaultHeaders() {
|
|
67
|
+
return this.defaultHeaders;
|
|
68
|
+
}
|
|
69
|
+
getDefaultConfig() {
|
|
70
|
+
return {
|
|
71
|
+
baseUrl: this.baseUrl
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
exports.FetchHTTPClient = FetchHTTPClient;
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { MockifyerConfig, HTTPClient } from '@sgedda/mockifyer-core';
|
|
2
|
+
export interface MockifyerInstance extends HTTPClient {
|
|
3
|
+
reloadMockData: () => Promise<void>;
|
|
4
|
+
clearStaleCacheEntries: () => number;
|
|
5
|
+
clearAllMocks: () => Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
export declare function setupMockifyer(config: MockifyerConfig): MockifyerInstance;
|
|
8
|
+
export * from '@sgedda/mockifyer-core';
|
|
9
|
+
export * from './react-native';
|
|
10
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAgBA,OAAO,EACL,eAAe,EAIf,UAAU,EAcX,MAAM,wBAAwB,CAAC;AAq5BhC,MAAM,WAAW,iBAAkB,SAAQ,UAAU;IACnD,cAAc,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IACpC,sBAAsB,EAAE,MAAM,MAAM,CAAC;IACrC,aAAa,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CACpC;AAED,wBAAgB,cAAc,CAAC,MAAM,EAAE,eAAe,GAAG,iBAAiB,CA6JzE;AAGD,cAAc,wBAAwB,CAAC;AAGvC,cAAc,gBAAgB,CAAC"}
|