@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.
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Metro bundler configuration helper for Mockifyer
3
+ *
4
+ * This helper configures Metro to stub Node.js built-in modules that aren't
5
+ * available in React Native, allowing Mockifyer to bundle successfully.
6
+ *
7
+ * @example
8
+ * ```javascript
9
+ * const { getDefaultConfig } = require('expo/metro-config');
10
+ * const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
11
+ *
12
+ * const config = getDefaultConfig(__dirname);
13
+ * module.exports = configureMetroForMockifyer(config);
14
+ * ```
15
+ */
16
+ export interface MetroConfig {
17
+ resolver?: {
18
+ resolveRequest?: (context: any, moduleName: string, platform: string | null) => {
19
+ filePath: string;
20
+ type: string;
21
+ } | null | undefined;
22
+ extraNodeModules?: Record<string, string>;
23
+ nodeModulesPaths?: string[];
24
+ };
25
+ watchFolders?: string[];
26
+ transformer?: any;
27
+ server?: any;
28
+ [key: string]: any;
29
+ }
30
+ /**
31
+ * Configure Metro bundler for Mockifyer
32
+ *
33
+ * This function adds resolver configuration to stub Node.js built-in modules
34
+ * that aren't available in React Native. The stubs are empty modules that
35
+ * allow Metro to bundle successfully while the code gracefully handles
36
+ * their absence at runtime.
37
+ *
38
+ * @param config - Existing Metro config (e.g., from getDefaultConfig)
39
+ * @returns Metro config with Mockifyer resolver configuration merged in
40
+ *
41
+ * @example
42
+ * ```javascript
43
+ * const { getDefaultConfig } = require('expo/metro-config');
44
+ * const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
45
+ *
46
+ * const config = getDefaultConfig(__dirname);
47
+ * module.exports = configureMetroForMockifyer(config);
48
+ * ```
49
+ */
50
+ export declare function configureMetroForMockifyer(config: MetroConfig): MetroConfig;
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ /**
3
+ * Metro bundler configuration helper for Mockifyer
4
+ *
5
+ * This helper configures Metro to stub Node.js built-in modules that aren't
6
+ * available in React Native, allowing Mockifyer to bundle successfully.
7
+ *
8
+ * @example
9
+ * ```javascript
10
+ * const { getDefaultConfig } = require('expo/metro-config');
11
+ * const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
12
+ *
13
+ * const config = getDefaultConfig(__dirname);
14
+ * module.exports = configureMetroForMockifyer(config);
15
+ * ```
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.configureMetroForMockifyer = configureMetroForMockifyer;
19
+ /**
20
+ * Node.js built-in modules that need to be stubbed for React Native
21
+ * Includes modules used by Mockifyer packages and their dependencies:
22
+ * - fs, path: Used by FilesystemProvider
23
+ * - assert: Used by @sinonjs/fake-timers
24
+ * - util: Used by @sinonjs/fake-timers
25
+ */
26
+ const NODE_BUILTINS = ['fs', 'path', 'assert', 'util'];
27
+ /**
28
+ * Configure Metro bundler for Mockifyer
29
+ *
30
+ * This function adds resolver configuration to stub Node.js built-in modules
31
+ * that aren't available in React Native. The stubs are empty modules that
32
+ * allow Metro to bundle successfully while the code gracefully handles
33
+ * their absence at runtime.
34
+ *
35
+ * @param config - Existing Metro config (e.g., from getDefaultConfig)
36
+ * @returns Metro config with Mockifyer resolver configuration merged in
37
+ *
38
+ * @example
39
+ * ```javascript
40
+ * const { getDefaultConfig } = require('expo/metro-config');
41
+ * const { configureMetroForMockifyer } = require('@sgedda/mockifyer-fetch/metro-config');
42
+ *
43
+ * const config = getDefaultConfig(__dirname);
44
+ * module.exports = configureMetroForMockifyer(config);
45
+ * ```
46
+ */
47
+ function configureMetroForMockifyer(config) {
48
+ // Get path to empty module stub
49
+ // Resolve using the package export path, which points to metro-polyfills/empty-module.js
50
+ let emptyModulePath;
51
+ try {
52
+ // Try to resolve via package exports (works when installed)
53
+ emptyModulePath = require.resolve('@sgedda/mockifyer-fetch/metro-polyfills/empty-module');
54
+ }
55
+ catch (e) {
56
+ // Fallback: resolve relative to this file (works in monorepo/development)
57
+ const path = require('path');
58
+ emptyModulePath = path.join(__dirname, '..', 'metro-polyfills', 'empty-module.js');
59
+ }
60
+ // Get existing resolver or create new one
61
+ const existingResolver = config.resolver || {};
62
+ const existingResolveRequest = existingResolver.resolveRequest;
63
+ // Create new resolveRequest function that handles Node.js built-ins
64
+ const newResolveRequest = (context, moduleName, platform) => {
65
+ // Handle Node.js built-in modules - return empty module stub
66
+ if (NODE_BUILTINS.includes(moduleName)) {
67
+ return {
68
+ filePath: emptyModulePath,
69
+ type: 'sourceFile',
70
+ };
71
+ }
72
+ // Call existing resolver if present
73
+ if (existingResolveRequest) {
74
+ const result = existingResolveRequest(context, moduleName, platform);
75
+ if (result) {
76
+ return result;
77
+ }
78
+ }
79
+ // Fallback to default Metro resolution
80
+ return context.resolveRequest(context, moduleName, platform);
81
+ };
82
+ // Merge config with new resolver
83
+ return {
84
+ ...config,
85
+ resolver: {
86
+ ...existingResolver,
87
+ resolveRequest: newResolveRequest,
88
+ },
89
+ };
90
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Metro middleware for mock file synchronization
3
+ *
4
+ * Provides two sync mechanisms:
5
+ * 1. POST /mockifyer-save - Direct save endpoint (used by Hybrid Provider for instant sync)
6
+ * 2. GET /mockifyer-sync - Legacy polling-based sync endpoint (for manual sync)
7
+ *
8
+ * The Hybrid Provider (recommended) uses POST /mockifyer-save for instant file sync.
9
+ * Legacy polling-based sync is still available for backward compatibility.
10
+ *
11
+ * Usage: Add to metro.config.js middleware array
12
+ */
13
+ export interface MetroSyncMiddlewareOptions {
14
+ /** Project root directory (default: process.cwd()) */
15
+ projectRoot?: string;
16
+ /** Path to mock data directory relative to project root (default: 'mock-data') */
17
+ mockDataPath?: string;
18
+ /** Test generation configuration - tests are generated when mocks are saved to project folder */
19
+ testGeneration?: {
20
+ /** Enable automatic test generation when mocks are saved */
21
+ enabled?: boolean;
22
+ /** Test framework to use: 'jest' (default), 'vitest', or 'mocha' */
23
+ framework?: 'jest' | 'vitest' | 'mocha';
24
+ /** Output path for generated tests (default: './tests/generated') */
25
+ outputPath?: string;
26
+ /** Test file naming pattern with placeholders: {endpoint}, {method}, {scenario} (default: '{endpoint}.test.ts') */
27
+ testPattern?: string;
28
+ /** Include setup code in generated tests (default: true) */
29
+ includeSetup?: boolean;
30
+ /** Group tests by: 'endpoint', 'scenario', or 'file' (default: 'endpoint') */
31
+ groupBy?: 'endpoint' | 'scenario' | 'file';
32
+ /** If true, only generate one test per endpoint (method + pathname), ignoring query parameters (default: false) */
33
+ uniqueTestsPerEndpoint?: boolean;
34
+ };
35
+ }
36
+ /**
37
+ * Sync mock files from iOS simulator to project folder
38
+ */
39
+ declare function syncFromIOSSimulator(projectRoot: string, mockDataPath: string): {
40
+ success: boolean;
41
+ filesSynced?: number;
42
+ syncedFiles?: string[];
43
+ error?: string;
44
+ };
45
+ /**
46
+ * Metro middleware function
47
+ */
48
+ export declare function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions): (req: any, res: any, next: any) => void;
49
+ /**
50
+ * Start auto-sync from iOS Simulator
51
+ */
52
+ export declare function startAutoSync(intervalMs?: number, options?: MetroSyncMiddlewareOptions): void;
53
+ /**
54
+ * Stop auto-sync
55
+ */
56
+ export declare function stopAutoSync(): void;
57
+ export { syncFromIOSSimulator };
@@ -0,0 +1,483 @@
1
+ "use strict";
2
+ /**
3
+ * Metro middleware for mock file synchronization
4
+ *
5
+ * Provides two sync mechanisms:
6
+ * 1. POST /mockifyer-save - Direct save endpoint (used by Hybrid Provider for instant sync)
7
+ * 2. GET /mockifyer-sync - Legacy polling-based sync endpoint (for manual sync)
8
+ *
9
+ * The Hybrid Provider (recommended) uses POST /mockifyer-save for instant file sync.
10
+ * Legacy polling-based sync is still available for backward compatibility.
11
+ *
12
+ * Usage: Add to metro.config.js middleware array
13
+ */
14
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ var desc = Object.getOwnPropertyDescriptor(m, k);
17
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
18
+ desc = { enumerable: true, get: function() { return m[k]; } };
19
+ }
20
+ Object.defineProperty(o, k2, desc);
21
+ }) : (function(o, m, k, k2) {
22
+ if (k2 === undefined) k2 = k;
23
+ o[k2] = m[k];
24
+ }));
25
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
26
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
27
+ }) : function(o, v) {
28
+ o["default"] = v;
29
+ });
30
+ var __importStar = (this && this.__importStar) || (function () {
31
+ var ownKeys = function(o) {
32
+ ownKeys = Object.getOwnPropertyNames || function (o) {
33
+ var ar = [];
34
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
35
+ return ar;
36
+ };
37
+ return ownKeys(o);
38
+ };
39
+ return function (mod) {
40
+ if (mod && mod.__esModule) return mod;
41
+ var result = {};
42
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
43
+ __setModuleDefault(result, mod);
44
+ return result;
45
+ };
46
+ })();
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.createMockSyncMiddleware = createMockSyncMiddleware;
49
+ exports.startAutoSync = startAutoSync;
50
+ exports.stopAutoSync = stopAutoSync;
51
+ exports.syncFromIOSSimulator = syncFromIOSSimulator;
52
+ const fs = __importStar(require("fs"));
53
+ const path = __importStar(require("path"));
54
+ const DEFAULT_SCENARIO = 'default';
55
+ let autoSyncInterval = null;
56
+ /**
57
+ * Get current scenario from scenario-config.json
58
+ */
59
+ function getCurrentScenario(mockDataPath) {
60
+ // Check environment variable first
61
+ if (process.env.MOCKIFYER_SCENARIO) {
62
+ return process.env.MOCKIFYER_SCENARIO;
63
+ }
64
+ // Try to load from scenario-config.json
65
+ try {
66
+ const configPath = path.join(mockDataPath, 'scenario-config.json');
67
+ if (fs.existsSync(configPath)) {
68
+ const fileContent = fs.readFileSync(configPath, 'utf-8');
69
+ const config = JSON.parse(fileContent);
70
+ if (config.currentScenario) {
71
+ return config.currentScenario;
72
+ }
73
+ }
74
+ }
75
+ catch (error) {
76
+ // Silently fail - file might not exist or be invalid
77
+ }
78
+ return DEFAULT_SCENARIO;
79
+ }
80
+ /**
81
+ * Get scenario folder path
82
+ */
83
+ function getScenarioPath(scenario, mockDataPath) {
84
+ // Always create scenario subfolder, even for 'default'
85
+ return path.join(mockDataPath, scenario);
86
+ }
87
+ /**
88
+ * Get test generation config from options or environment variables
89
+ * Options take precedence, then fall back to environment variables (for backward compatibility)
90
+ */
91
+ function getTestGenerationConfig(options) {
92
+ // Check if enabled via options or environment variables
93
+ const enabled = options?.testGeneration?.enabled === true ||
94
+ process.env.MOCKIFYER_GENERATE_TESTS === 'true' ||
95
+ process.env.MOCKIFYER_GENERATE_TESTS === '1';
96
+ if (!enabled) {
97
+ return null;
98
+ }
99
+ // Use options if provided, otherwise fall back to environment variables
100
+ return {
101
+ framework: options?.testGeneration?.framework || process.env.MOCKIFYER_TEST_FRAMEWORK || 'jest',
102
+ outputPath: options?.testGeneration?.outputPath || process.env.MOCKIFYER_TEST_OUTPUT_PATH || './tests/generated',
103
+ testPattern: options?.testGeneration?.testPattern || process.env.MOCKIFYER_TEST_PATTERN || '{endpoint}.test.ts',
104
+ includeSetup: options?.testGeneration?.includeSetup !== false && process.env.MOCKIFYER_TEST_INCLUDE_SETUP !== 'false',
105
+ groupBy: options?.testGeneration?.groupBy || process.env.MOCKIFYER_TEST_GROUP_BY || 'endpoint',
106
+ httpClientType: 'fetch',
107
+ uniqueTestsPerEndpoint: options?.testGeneration?.uniqueTestsPerEndpoint || process.env.MOCKIFYER_UNIQUE_TESTS_PER_ENDPOINT === 'true',
108
+ };
109
+ }
110
+ /**
111
+ * Generate test file for a mock (runs in Metro/Node.js where fs is available)
112
+ */
113
+ function generateTestForMock(mockData, testConfig, projectRoot) {
114
+ try {
115
+ // Try to require TestGenerator from mockifyer-core
116
+ let TestGeneratorClass;
117
+ try {
118
+ let mockifyerCore;
119
+ try {
120
+ mockifyerCore = require('@sgedda/mockifyer-core');
121
+ }
122
+ catch (e) {
123
+ // Fallback: try relative path (for local file: dependencies)
124
+ const corePath = path.join(projectRoot, '../../packages/mockifyer-core/dist/index.js');
125
+ if (fs.existsSync(corePath)) {
126
+ mockifyerCore = require(corePath);
127
+ }
128
+ else {
129
+ throw new Error(`Could not find mockifyer-core at ${corePath}`);
130
+ }
131
+ }
132
+ TestGeneratorClass = mockifyerCore?.TestGenerator;
133
+ if (!TestGeneratorClass) {
134
+ const testGeneratorPath = path.join(projectRoot, '../../packages/mockifyer-core/dist/utils/test-generator.js');
135
+ if (fs.existsSync(testGeneratorPath)) {
136
+ const testGeneratorModule = require(testGeneratorPath);
137
+ TestGeneratorClass = testGeneratorModule.TestGenerator;
138
+ }
139
+ }
140
+ }
141
+ catch (e) {
142
+ console.log(`[MockSync] ⚠️ Could not load TestGenerator: ${e.message}`);
143
+ return false;
144
+ }
145
+ if (!TestGeneratorClass) {
146
+ console.log('[MockSync] ⚠️ TestGenerator not available');
147
+ return false;
148
+ }
149
+ const generator = new TestGeneratorClass();
150
+ const options = {
151
+ framework: testConfig.framework,
152
+ outputPath: testConfig.outputPath,
153
+ testPattern: testConfig.testPattern,
154
+ includeSetup: testConfig.includeSetup,
155
+ groupBy: testConfig.groupBy,
156
+ httpClientType: testConfig.httpClientType,
157
+ uniqueTestsPerEndpoint: testConfig.uniqueTestsPerEndpoint,
158
+ };
159
+ const testInfo = generator.analyzeMock(mockData, options.httpClientType || 'fetch');
160
+ const testFilePath = generator.determineTestFilePath(mockData, options);
161
+ const absoluteTestPath = path.resolve(projectRoot, testFilePath);
162
+ const testDir = path.dirname(absoluteTestPath);
163
+ // If uniqueTestsPerEndpoint is enabled, check if a test file already exists
164
+ if (options.uniqueTestsPerEndpoint && fs.existsSync(absoluteTestPath)) {
165
+ console.log(`[MockSync] ✅ Test file already exists for endpoint ${testInfo.method} ${testInfo.endpoint}, skipping generation`);
166
+ return true;
167
+ }
168
+ // Ensure test directory exists
169
+ if (!fs.existsSync(testDir)) {
170
+ fs.mkdirSync(testDir, { recursive: true });
171
+ }
172
+ const testCode = generator.generateTest(mockData, options);
173
+ // Check if test file already exists
174
+ if (fs.existsSync(absoluteTestPath)) {
175
+ const testName = `${testInfo.method} ${testInfo.endpoint}`;
176
+ const existingContent = fs.readFileSync(absoluteTestPath, 'utf-8');
177
+ if (existingContent.includes(`it('${testName}'`) || existingContent.includes(`it("${testName}"`)) {
178
+ console.log(`[MockSync] ✅ Test already exists in ${absoluteTestPath}, skipping generation`);
179
+ return true;
180
+ }
181
+ // Append test to existing file
182
+ const testMatch = testCode.match(/it\('.*?', async \(\) => \{[\s\S]*?\}\);?/);
183
+ if (testMatch) {
184
+ const newTest = testMatch[0];
185
+ const updatedContent = existingContent.replace(/(\s+)(\}\);?\s*)$/, `$1${newTest}\n$1$2`);
186
+ fs.writeFileSync(absoluteTestPath, updatedContent);
187
+ console.log(`[MockSync] ✅ Appended test to existing file: ${absoluteTestPath}`);
188
+ return true;
189
+ }
190
+ }
191
+ else {
192
+ // Create new test file
193
+ fs.writeFileSync(absoluteTestPath, testCode);
194
+ console.log(`[MockSync] ✅ Generated test: ${absoluteTestPath}`);
195
+ }
196
+ return true;
197
+ }
198
+ catch (error) {
199
+ console.error(`[MockSync] ❌ Error generating test:`, error);
200
+ return false;
201
+ }
202
+ }
203
+ /**
204
+ * Save mock data directly to project folder
205
+ * Called by HybridProvider when saving mocks
206
+ */
207
+ function saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig) {
208
+ try {
209
+ // CRITICAL: Never save Mockifyer sync endpoint requests to prevent infinite loops
210
+ const url = mockData?.request?.url || '';
211
+ if (url.includes('/mockifyer-save') || url.includes('/mockifyer-clear') || url.includes('/mockifyer-sync')) {
212
+ console.warn(`[MockSync] ⚠️ Rejecting save - Mockifyer sync endpoint detected: ${url}`);
213
+ return { success: false, error: 'Cannot save Mockifyer sync endpoint requests' };
214
+ }
215
+ // Also check if the mockData string contains nested sync requests
216
+ const mockDataStr = JSON.stringify(mockData);
217
+ if (mockDataStr.includes('/mockifyer-save') || mockDataStr.includes('/mockifyer-clear') || mockDataStr.includes('/mockifyer-sync')) {
218
+ console.warn(`[MockSync] ⚠️ Rejecting save - Mock data contains nested Mockifyer sync requests`);
219
+ return { success: false, error: 'Mock data contains nested Mockifyer sync requests' };
220
+ }
221
+ // Get current scenario and ensure scenario folder exists
222
+ const currentScenario = getCurrentScenario(mockDataPath);
223
+ const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
224
+ fs.mkdirSync(scenarioPath, { recursive: true });
225
+ // Format the datetime to be readable
226
+ const now = new Date();
227
+ const dateStr = now.toISOString()
228
+ .replace(/T/, '_')
229
+ .replace(/\..+/, '')
230
+ .replace(/:/g, '-');
231
+ // Create a safe filename from the URL
232
+ const urlSafe = mockData.request.url
233
+ .replace(/^https?:\/\//, '')
234
+ .replace(/[^a-zA-Z0-9]/g, '_');
235
+ const filename = `${dateStr}_${mockData.request.method}_${urlSafe}.json`;
236
+ const filePath = path.join(scenarioPath, filename);
237
+ // Check if file already exists - skip saving if it does
238
+ if (fs.existsSync(filePath)) {
239
+ console.log(`[MockSync] ⚠️ File already exists, skipping save: ${filename}`);
240
+ return { success: true, filename, skipped: true, reason: 'File already exists' };
241
+ }
242
+ // Write to file
243
+ fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
244
+ console.log(`[MockSync] ✅ Saved mock to project folder: ${currentScenario}/${filename}`);
245
+ // Generate test file if enabled
246
+ if (testConfig) {
247
+ generateTestForMock(mockData, testConfig, projectRoot);
248
+ }
249
+ return { success: true, filename, scenario: currentScenario };
250
+ }
251
+ catch (error) {
252
+ console.error(`[MockSync] ❌ Error saving mock to project folder:`, error);
253
+ return { success: false, error: error.message };
254
+ }
255
+ }
256
+ /**
257
+ * Clear all mock files from project folder (current scenario)
258
+ */
259
+ function clearMockFiles(mockDataPath) {
260
+ try {
261
+ const currentScenario = getCurrentScenario(mockDataPath);
262
+ const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
263
+ if (!fs.existsSync(scenarioPath)) {
264
+ return { success: true, filesDeleted: 0 };
265
+ }
266
+ const files = fs.readdirSync(scenarioPath);
267
+ let deleted = 0;
268
+ files.forEach(file => {
269
+ if (file.endsWith('.json')) {
270
+ const filePath = path.join(scenarioPath, file);
271
+ fs.unlinkSync(filePath);
272
+ deleted++;
273
+ }
274
+ });
275
+ console.log(`[MockSync] ✅ Cleared ${deleted} mock files from ${currentScenario}`);
276
+ return { success: true, filesDeleted: deleted };
277
+ }
278
+ catch (error) {
279
+ console.error(`[MockSync] ❌ Error clearing mock files:`, error);
280
+ return { success: false, error: error.message };
281
+ }
282
+ }
283
+ /**
284
+ * Sync mock files from iOS simulator to project folder
285
+ */
286
+ function syncFromIOSSimulator(projectRoot, mockDataPath) {
287
+ try {
288
+ // Get iOS simulator path
289
+ const homeDir = process.env.HOME || process.env.USERPROFILE || '';
290
+ const simulatorPath = path.join(homeDir, 'Library/Developer/CoreSimulator/Devices');
291
+ if (!fs.existsSync(simulatorPath)) {
292
+ return { success: false, error: 'iOS Simulator path not found' };
293
+ }
294
+ // Find the most recent simulator device
295
+ const devices = fs.readdirSync(simulatorPath);
296
+ let latestDevice = '';
297
+ let latestTime = 0;
298
+ devices.forEach(device => {
299
+ const devicePath = path.join(simulatorPath, device);
300
+ const stat = fs.statSync(devicePath);
301
+ if (stat.mtimeMs > latestTime) {
302
+ latestTime = stat.mtimeMs;
303
+ latestDevice = device;
304
+ }
305
+ });
306
+ if (!latestDevice) {
307
+ return { success: false, error: 'No iOS Simulator device found' };
308
+ }
309
+ // Look for mock-data directory in the simulator
310
+ const appDataPath = path.join(simulatorPath, latestDevice, 'data/Containers/Data/Application');
311
+ if (!fs.existsSync(appDataPath)) {
312
+ return { success: false, error: 'iOS Simulator app data path not found' };
313
+ }
314
+ const apps = fs.readdirSync(appDataPath);
315
+ let found = false;
316
+ let filesSynced = 0;
317
+ const syncedFiles = [];
318
+ for (const app of apps) {
319
+ const appPath = path.join(appDataPath, app);
320
+ const mockDataSimPath = path.join(appPath, 'Documents/mock-data');
321
+ if (fs.existsSync(mockDataSimPath)) {
322
+ found = true;
323
+ const currentScenario = getCurrentScenario(mockDataPath);
324
+ const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
325
+ fs.mkdirSync(scenarioPath, { recursive: true });
326
+ const files = fs.readdirSync(mockDataSimPath);
327
+ files.forEach(file => {
328
+ if (file.endsWith('.json')) {
329
+ const sourcePath = path.join(mockDataSimPath, file);
330
+ const destPath = path.join(scenarioPath, file);
331
+ fs.copyFileSync(sourcePath, destPath);
332
+ filesSynced++;
333
+ syncedFiles.push(file);
334
+ }
335
+ });
336
+ console.log(`[MockSync] ✅ Synced ${filesSynced} files from iOS Simulator to ${currentScenario}`);
337
+ break;
338
+ }
339
+ }
340
+ if (!found) {
341
+ return { success: false, filesSynced: 0, error: 'mock-data directory not found in simulator' };
342
+ }
343
+ return { success: true, filesSynced, syncedFiles };
344
+ }
345
+ catch (error) {
346
+ return { success: false, filesSynced: 0, error: error.message };
347
+ }
348
+ }
349
+ /**
350
+ * Metro middleware function
351
+ */
352
+ function createMockSyncMiddleware(options) {
353
+ const projectRoot = options?.projectRoot || process.cwd();
354
+ const mockDataPath = path.resolve(projectRoot, options?.mockDataPath || 'mock-data');
355
+ const testConfig = getTestGenerationConfig(options);
356
+ return function mockSyncMiddleware(req, res, next) {
357
+ const url = req.url.split('?')[0]; // Remove query params
358
+ // Handle POST endpoint for clearing mocks
359
+ if (url === '/mockifyer-clear' && req.method === 'POST') {
360
+ const result = clearMockFiles(mockDataPath);
361
+ res.setHeader('Content-Type', 'application/json');
362
+ res.end(JSON.stringify(result));
363
+ return;
364
+ }
365
+ // Handle POST endpoint for direct save (HybridProvider)
366
+ if (url === '/mockifyer-save' && req.method === 'POST') {
367
+ let body = '';
368
+ req.on('data', (chunk) => {
369
+ body += chunk.toString();
370
+ });
371
+ req.on('end', () => {
372
+ try {
373
+ const mockData = JSON.parse(body);
374
+ const result = saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig);
375
+ res.setHeader('Content-Type', 'application/json');
376
+ res.end(JSON.stringify(result));
377
+ }
378
+ catch (error) {
379
+ res.statusCode = 400;
380
+ res.setHeader('Content-Type', 'application/json');
381
+ res.end(JSON.stringify({
382
+ success: false,
383
+ error: `Invalid JSON: ${error.message}`,
384
+ }));
385
+ }
386
+ });
387
+ return;
388
+ }
389
+ // Handle GET endpoint for sync status
390
+ if (url === '/mockifyer-sync/status' && req.method === 'GET') {
391
+ const currentScenario = getCurrentScenario(mockDataPath);
392
+ const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
393
+ const files = fs.existsSync(scenarioPath)
394
+ ? fs.readdirSync(scenarioPath).filter((f) => f.endsWith('.json'))
395
+ : [];
396
+ res.setHeader('Content-Type', 'application/json');
397
+ res.end(JSON.stringify({
398
+ success: true,
399
+ scenario: currentScenario,
400
+ fileCount: files.length,
401
+ files: files.slice(0, 10), // Return first 10 files
402
+ }));
403
+ return;
404
+ }
405
+ // Handle GET endpoint for sync (legacy polling-based sync)
406
+ if (url === '/mockifyer-sync' && req.method === 'GET') {
407
+ const result = syncFromIOSSimulator(projectRoot, mockDataPath);
408
+ res.setHeader('Content-Type', 'application/json');
409
+ res.end(JSON.stringify(result));
410
+ return;
411
+ }
412
+ // Handle GET endpoint for scenario config
413
+ if (url === '/mockifyer-scenario-config' && req.method === 'GET') {
414
+ try {
415
+ const configPath = path.join(mockDataPath, 'scenario-config.json');
416
+ if (fs.existsSync(configPath)) {
417
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
418
+ res.setHeader('Content-Type', 'application/json');
419
+ res.end(JSON.stringify(config));
420
+ }
421
+ else {
422
+ res.setHeader('Content-Type', 'application/json');
423
+ res.end(JSON.stringify({ currentScenario: DEFAULT_SCENARIO }));
424
+ }
425
+ }
426
+ catch (error) {
427
+ res.statusCode = 500;
428
+ res.setHeader('Content-Type', 'application/json');
429
+ res.end(JSON.stringify({ success: false, error: error.message }));
430
+ }
431
+ return;
432
+ }
433
+ // Handle POST endpoint for scenario config sync
434
+ if (url === '/mockifyer-scenario-config' && req.method === 'POST') {
435
+ let body = '';
436
+ req.on('data', (chunk) => {
437
+ body += chunk.toString();
438
+ });
439
+ req.on('end', () => {
440
+ try {
441
+ const config = JSON.parse(body);
442
+ const configPath = path.join(mockDataPath, 'scenario-config.json');
443
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
444
+ res.setHeader('Content-Type', 'application/json');
445
+ res.end(JSON.stringify({ success: true }));
446
+ }
447
+ catch (error) {
448
+ res.statusCode = 400;
449
+ res.setHeader('Content-Type', 'application/json');
450
+ res.end(JSON.stringify({ success: false, error: error.message }));
451
+ }
452
+ });
453
+ return;
454
+ }
455
+ // Continue to next middleware if not handled
456
+ next();
457
+ };
458
+ }
459
+ /**
460
+ * Start auto-sync from iOS Simulator
461
+ */
462
+ function startAutoSync(intervalMs = 5000, options) {
463
+ if (autoSyncInterval) {
464
+ console.log('[MockSync] Auto-sync already running');
465
+ return;
466
+ }
467
+ const projectRoot = options?.projectRoot || process.cwd();
468
+ const mockDataPath = path.resolve(projectRoot, options?.mockDataPath || 'mock-data');
469
+ console.log(`[MockSync] Starting auto-sync every ${intervalMs}ms`);
470
+ autoSyncInterval = setInterval(() => {
471
+ syncFromIOSSimulator(projectRoot, mockDataPath);
472
+ }, intervalMs);
473
+ }
474
+ /**
475
+ * Stop auto-sync
476
+ */
477
+ function stopAutoSync() {
478
+ if (autoSyncInterval) {
479
+ clearInterval(autoSyncInterval);
480
+ autoSyncInterval = null;
481
+ console.log('[MockSync] Auto-sync disabled');
482
+ }
483
+ }