@sgedda/mockifyer-fetch 1.7.0 → 1.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -1
- package/dist/index.js +27 -174
- package/dist/metro-config.d.ts +89 -8
- package/dist/metro-config.js +126 -8
- package/dist/metro-sync-middleware.d.ts +4 -2
- package/dist/metro-sync-middleware.js +292 -36
- package/dist/react-native.d.ts +1 -1
- package/dist/react-native.js +16 -7
- package/package.json +8 -3
- package/src/index.ts +33 -179
- package/src/metro-config.ts +153 -9
- package/src/metro-sync-middleware.ts +319 -41
- package/src/react-native.ts +19 -8
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Metro middleware for mock file synchronization
|
|
3
3
|
*
|
|
4
|
-
* Provides
|
|
4
|
+
* Provides sync mechanisms:
|
|
5
5
|
* 1. POST /mockifyer-save - Direct save endpoint (used by Hybrid Provider for instant sync)
|
|
6
|
-
* 2. GET /mockifyer-sync
|
|
6
|
+
* 2. GET /mockifyer-sync-to-device-manifest + /mockifyer-sync-to-device-file - Project → app (HybridProvider; avoids huge single JSON)
|
|
7
|
+
* 3. GET /mockifyer-sync-to-device - Legacy: all files in one response (may fail on large scenarios)
|
|
8
|
+
* 4. GET /mockifyer-sync - Legacy: iOS simulator mock-data → project folder
|
|
7
9
|
*
|
|
8
10
|
* The Hybrid Provider (recommended) uses POST /mockifyer-save for instant file sync.
|
|
9
11
|
* Legacy polling-based sync is still available for backward compatibility.
|
|
@@ -15,6 +17,7 @@ import * as fs from 'fs';
|
|
|
15
17
|
import * as path from 'path';
|
|
16
18
|
import { execSync } from 'child_process';
|
|
17
19
|
import { MockData, TestGenerator, TestGenerationOptions } from '@sgedda/mockifyer-core';
|
|
20
|
+
import { logger } from '@sgedda/mockifyer-core';
|
|
18
21
|
|
|
19
22
|
export interface MetroSyncMiddlewareOptions {
|
|
20
23
|
/** Project root directory (default: process.cwd()) */
|
|
@@ -44,6 +47,49 @@ const DEFAULT_SCENARIO = 'default';
|
|
|
44
47
|
|
|
45
48
|
let autoSyncInterval: NodeJS.Timeout | null = null;
|
|
46
49
|
|
|
50
|
+
function getMockFilePathLocal(mockData: MockData, dateStr: string): { dir: string; filename: string } {
|
|
51
|
+
const url = mockData.request.url || '';
|
|
52
|
+
const method = (mockData.request.method || 'GET').toUpperCase();
|
|
53
|
+
let host = 'unknown';
|
|
54
|
+
let pathSegments: string[] = [];
|
|
55
|
+
try {
|
|
56
|
+
const parsed = new URL(url);
|
|
57
|
+
host = parsed.hostname;
|
|
58
|
+
pathSegments = parsed.pathname.split('/').filter(Boolean);
|
|
59
|
+
} catch {
|
|
60
|
+
return { dir: 'unknown', filename: `${method}_${dateStr}.json` };
|
|
61
|
+
}
|
|
62
|
+
const hostSafe = host.replace(/[^a-zA-Z0-9.-]/g, '_');
|
|
63
|
+
const graphqlIdx = pathSegments.lastIndexOf('graphql');
|
|
64
|
+
const restIdx = pathSegments.indexOf('rest');
|
|
65
|
+
let type: string;
|
|
66
|
+
let remainingSegments: string[];
|
|
67
|
+
if (graphqlIdx >= 0) {
|
|
68
|
+
type = 'graphql';
|
|
69
|
+
remainingSegments = pathSegments.slice(graphqlIdx + 1);
|
|
70
|
+
} else if (restIdx >= 0) {
|
|
71
|
+
type = 'rest';
|
|
72
|
+
remainingSegments = pathSegments.slice(restIdx + 1);
|
|
73
|
+
} else {
|
|
74
|
+
type = '';
|
|
75
|
+
remainingSegments = pathSegments;
|
|
76
|
+
}
|
|
77
|
+
let identifier = '';
|
|
78
|
+
if (mockData.request.data) {
|
|
79
|
+
try {
|
|
80
|
+
const body = typeof mockData.request.data === 'string'
|
|
81
|
+
? JSON.parse(mockData.request.data) : mockData.request.data;
|
|
82
|
+
if (body.operationName) identifier = body.operationName;
|
|
83
|
+
else if (body.path) identifier = body.path;
|
|
84
|
+
else if (body.webAppName) identifier = body.webAppName;
|
|
85
|
+
} catch { /* ignore */ }
|
|
86
|
+
}
|
|
87
|
+
identifier = identifier.replace(/[^a-zA-Z0-9_-]/g, '_').substring(0, 60);
|
|
88
|
+
const dir = [hostSafe, type, ...remainingSegments].filter(Boolean).join('/');
|
|
89
|
+
const filename = identifier ? `${method}_${identifier}_${dateStr}.json` : `${method}_${dateStr}.json`;
|
|
90
|
+
return { dir, filename };
|
|
91
|
+
}
|
|
92
|
+
|
|
47
93
|
/**
|
|
48
94
|
* Get current scenario from scenario-config.json
|
|
49
95
|
*/
|
|
@@ -141,12 +187,10 @@ function generateTestForMock(
|
|
|
141
187
|
}
|
|
142
188
|
}
|
|
143
189
|
} catch (e) {
|
|
144
|
-
console.log(`[MockSync] ⚠️ Could not load TestGenerator: ${(e as Error).message}`);
|
|
145
190
|
return false;
|
|
146
191
|
}
|
|
147
192
|
|
|
148
193
|
if (!TestGeneratorClass) {
|
|
149
|
-
console.log('[MockSync] ⚠️ TestGenerator not available');
|
|
150
194
|
return false;
|
|
151
195
|
}
|
|
152
196
|
|
|
@@ -170,7 +214,6 @@ function generateTestForMock(
|
|
|
170
214
|
|
|
171
215
|
// If uniqueTestsPerEndpoint is enabled, check if a test file already exists
|
|
172
216
|
if (options.uniqueTestsPerEndpoint && fs.existsSync(absoluteTestPath)) {
|
|
173
|
-
console.log(`[MockSync] ✅ Test file already exists for endpoint ${testInfo.method} ${testInfo.endpoint}, skipping generation`);
|
|
174
217
|
return true;
|
|
175
218
|
}
|
|
176
219
|
|
|
@@ -187,7 +230,6 @@ function generateTestForMock(
|
|
|
187
230
|
|
|
188
231
|
const existingContent = fs.readFileSync(absoluteTestPath, 'utf-8');
|
|
189
232
|
if (existingContent.includes(`it('${testName}'`) || existingContent.includes(`it("${testName}"`)) {
|
|
190
|
-
console.log(`[MockSync] ✅ Test already exists in ${absoluteTestPath}, skipping generation`);
|
|
191
233
|
return true;
|
|
192
234
|
}
|
|
193
235
|
|
|
@@ -200,18 +242,16 @@ function generateTestForMock(
|
|
|
200
242
|
`$1${newTest}\n$1$2`
|
|
201
243
|
);
|
|
202
244
|
fs.writeFileSync(absoluteTestPath, updatedContent);
|
|
203
|
-
console.log(`[MockSync] ✅ Appended test to existing file: ${absoluteTestPath}`);
|
|
204
245
|
return true;
|
|
205
246
|
}
|
|
206
247
|
} else {
|
|
207
248
|
// Create new test file
|
|
208
249
|
fs.writeFileSync(absoluteTestPath, testCode);
|
|
209
|
-
console.log(`[MockSync] ✅ Generated test: ${absoluteTestPath}`);
|
|
210
250
|
}
|
|
211
251
|
|
|
212
252
|
return true;
|
|
213
253
|
} catch (error) {
|
|
214
|
-
|
|
254
|
+
logger.error(`[MockSync] ❌ Error generating test:`, error);
|
|
215
255
|
return false;
|
|
216
256
|
}
|
|
217
257
|
}
|
|
@@ -237,7 +277,7 @@ function saveMockToProjectFolder(
|
|
|
237
277
|
// Also check if the mockData string contains nested sync requests
|
|
238
278
|
const mockDataStr = JSON.stringify(mockData);
|
|
239
279
|
if (mockDataStr.includes('/mockifyer-save') || mockDataStr.includes('/mockifyer-clear') || mockDataStr.includes('/mockifyer-sync')) {
|
|
240
|
-
|
|
280
|
+
logger.warn(`[MockSync] ⚠️ Rejecting save - Mock data contains nested Mockifyer sync requests`);
|
|
241
281
|
return { success: false, error: 'Mock data contains nested Mockifyer sync requests' };
|
|
242
282
|
}
|
|
243
283
|
|
|
@@ -246,38 +286,26 @@ function saveMockToProjectFolder(
|
|
|
246
286
|
const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
|
|
247
287
|
fs.mkdirSync(scenarioPath, { recursive: true });
|
|
248
288
|
|
|
249
|
-
|
|
250
|
-
const
|
|
251
|
-
const
|
|
252
|
-
|
|
253
|
-
.replace(/\..+/, '')
|
|
254
|
-
.replace(/:/g, '-');
|
|
255
|
-
|
|
256
|
-
// Create a safe filename from the URL
|
|
257
|
-
const urlSafe = mockData.request.url
|
|
258
|
-
.replace(/^https?:\/\//, '')
|
|
259
|
-
.replace(/[^a-zA-Z0-9]/g, '_');
|
|
260
|
-
|
|
261
|
-
const filename = `${dateStr}_${mockData.request.method}_${urlSafe}.json`;
|
|
262
|
-
const filePath = path.join(scenarioPath, filename);
|
|
289
|
+
const dateStr = new Date().toISOString().replace(/T/, '_').replace(/\..+/, '').replace(/:/g, '-');
|
|
290
|
+
const { dir, filename } = getMockFilePathLocal(mockData, dateStr);
|
|
291
|
+
const fullDir = path.join(scenarioPath, dir);
|
|
292
|
+
const filePath = path.join(fullDir, filename);
|
|
263
293
|
|
|
264
294
|
// Check if file already exists - skip saving if it does
|
|
265
295
|
if (fs.existsSync(filePath)) {
|
|
266
|
-
|
|
267
|
-
return { success: true, filename, skipped: true, reason: 'File already exists' };
|
|
296
|
+
return { success: true, filename: path.join(dir, filename), skipped: true, reason: 'File already exists' };
|
|
268
297
|
}
|
|
269
298
|
|
|
299
|
+
fs.mkdirSync(fullDir, { recursive: true });
|
|
270
300
|
// Write to file
|
|
271
301
|
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
272
|
-
|
|
273
|
-
console.log(`[MockSync] ✅ Saved mock to project folder: ${currentScenario}/${filename}`);
|
|
274
|
-
|
|
302
|
+
|
|
275
303
|
// Generate test file if enabled
|
|
276
304
|
if (testConfig) {
|
|
277
305
|
generateTestForMock(mockData, testConfig, projectRoot);
|
|
278
306
|
}
|
|
279
|
-
|
|
280
|
-
return { success: true, filename, scenario: currentScenario };
|
|
307
|
+
|
|
308
|
+
return { success: true, filename: path.join(dir, filename), scenario: currentScenario };
|
|
281
309
|
} catch (error) {
|
|
282
310
|
console.error(`[MockSync] ❌ Error saving mock to project folder:`, error);
|
|
283
311
|
return { success: false, error: (error as Error).message };
|
|
@@ -307,10 +335,9 @@ function clearMockFiles(mockDataPath: string): { success: boolean; filesDeleted?
|
|
|
307
335
|
}
|
|
308
336
|
});
|
|
309
337
|
|
|
310
|
-
console.log(`[MockSync] ✅ Cleared ${deleted} mock files from ${currentScenario}`);
|
|
311
338
|
return { success: true, filesDeleted: deleted };
|
|
312
339
|
} catch (error) {
|
|
313
|
-
|
|
340
|
+
logger.error(`[MockSync] ❌ Error clearing mock files:`, error);
|
|
314
341
|
return { success: false, error: (error as Error).message };
|
|
315
342
|
}
|
|
316
343
|
}
|
|
@@ -389,7 +416,6 @@ function syncFromIOSSimulator(
|
|
|
389
416
|
}
|
|
390
417
|
});
|
|
391
418
|
|
|
392
|
-
console.log(`[MockSync] ✅ Synced ${filesSynced} files from iOS Simulator to ${currentScenario}`);
|
|
393
419
|
break;
|
|
394
420
|
}
|
|
395
421
|
}
|
|
@@ -404,6 +430,190 @@ function syncFromIOSSimulator(
|
|
|
404
430
|
}
|
|
405
431
|
}
|
|
406
432
|
|
|
433
|
+
/**
|
|
434
|
+
* Recursive mock JSON files under scenario root (paths relative to scenario, POSIX slashes).
|
|
435
|
+
*/
|
|
436
|
+
function listScenarioMockJsonFiles(scenarioAbsPath: string): Array<{ relativePath: string; fullPath: string }> {
|
|
437
|
+
const out: Array<{ relativePath: string; fullPath: string }> = [];
|
|
438
|
+
if (!fs.existsSync(scenarioAbsPath)) {
|
|
439
|
+
return out;
|
|
440
|
+
}
|
|
441
|
+
const walk = (dir: string): void => {
|
|
442
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
443
|
+
const full = path.join(dir, entry.name);
|
|
444
|
+
if (entry.isDirectory()) {
|
|
445
|
+
walk(full);
|
|
446
|
+
} else if (entry.name.endsWith('.json')) {
|
|
447
|
+
const rel = path.relative(scenarioAbsPath, full);
|
|
448
|
+
const relativePath = rel.split(path.sep).join('/');
|
|
449
|
+
if (
|
|
450
|
+
relativePath === 'scenario-config.json' ||
|
|
451
|
+
relativePath === 'date-config.json'
|
|
452
|
+
) {
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
out.push({ relativePath, fullPath: full });
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
};
|
|
459
|
+
walk(scenarioAbsPath);
|
|
460
|
+
return out;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* Resolve a client-supplied path to a mock file under the scenario folder (blocks path traversal).
|
|
465
|
+
*/
|
|
466
|
+
function resolveScenarioRelativeMockPath(
|
|
467
|
+
rawQueryPath: string,
|
|
468
|
+
scenarioAbsPath: string
|
|
469
|
+
): { relativePath: string; fullPath: string } | null {
|
|
470
|
+
let decoded: string;
|
|
471
|
+
try {
|
|
472
|
+
decoded = decodeURIComponent(rawQueryPath);
|
|
473
|
+
} catch {
|
|
474
|
+
return null;
|
|
475
|
+
}
|
|
476
|
+
const normalized = decoded.replace(/\\/g, '/').replace(/^\//, '');
|
|
477
|
+
if (!normalized.endsWith('.json') || normalized.includes('..')) {
|
|
478
|
+
return null;
|
|
479
|
+
}
|
|
480
|
+
const fullPath = path.normalize(path.join(scenarioAbsPath, normalized));
|
|
481
|
+
const scenarioResolved = path.resolve(scenarioAbsPath);
|
|
482
|
+
const relativeToScenario = path.relative(scenarioResolved, fullPath);
|
|
483
|
+
if (relativeToScenario.startsWith('..') || path.isAbsolute(relativeToScenario)) {
|
|
484
|
+
return null;
|
|
485
|
+
}
|
|
486
|
+
const relativePath = relativeToScenario.split(path.sep).join('/');
|
|
487
|
+
return { relativePath, fullPath };
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Small manifest only (paths + mtimes) for GET /mockifyer-sync-to-device-manifest.
|
|
492
|
+
*/
|
|
493
|
+
function buildSyncToDeviceManifest(mockDataPath: string): {
|
|
494
|
+
success: boolean;
|
|
495
|
+
files?: Array<{ filename: string; modificationTime: number }>;
|
|
496
|
+
count?: number;
|
|
497
|
+
error?: string;
|
|
498
|
+
} {
|
|
499
|
+
try {
|
|
500
|
+
const currentScenario = getCurrentScenario(mockDataPath);
|
|
501
|
+
const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
|
|
502
|
+
const entries = listScenarioMockJsonFiles(scenarioPath);
|
|
503
|
+
const files: Array<{ filename: string; modificationTime: number }> = [];
|
|
504
|
+
for (const { relativePath, fullPath } of entries) {
|
|
505
|
+
try {
|
|
506
|
+
const stat = fs.statSync(fullPath);
|
|
507
|
+
files.push({ filename: relativePath, modificationTime: stat.mtimeMs });
|
|
508
|
+
} catch (e) {
|
|
509
|
+
logger.warn(`[MetroSyncMiddleware] Manifest: could not stat ${fullPath}:`, e);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
logger.info(
|
|
513
|
+
`[MetroSyncMiddleware] /mockifyer-sync-to-device-manifest: ${files.length} file(s), scenario "${currentScenario}"`
|
|
514
|
+
);
|
|
515
|
+
return { success: true, files, count: files.length };
|
|
516
|
+
} catch (error) {
|
|
517
|
+
return { success: false, error: (error as Error).message };
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* One mock file for GET /mockifyer-sync-to-device-file?path=
|
|
523
|
+
*/
|
|
524
|
+
function buildSyncToDeviceSingleFilePayload(mockDataPath: string, rawPathParam: string): {
|
|
525
|
+
success: boolean;
|
|
526
|
+
filename?: string;
|
|
527
|
+
content?: MockData;
|
|
528
|
+
modificationTime?: number;
|
|
529
|
+
error?: string;
|
|
530
|
+
} {
|
|
531
|
+
try {
|
|
532
|
+
const currentScenario = getCurrentScenario(mockDataPath);
|
|
533
|
+
const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
|
|
534
|
+
const resolved = resolveScenarioRelativeMockPath(rawPathParam, scenarioPath);
|
|
535
|
+
if (!resolved) {
|
|
536
|
+
return { success: false, error: 'Invalid or unsafe path' };
|
|
537
|
+
}
|
|
538
|
+
const { fullPath, relativePath } = resolved;
|
|
539
|
+
if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) {
|
|
540
|
+
return { success: false, error: 'Not found' };
|
|
541
|
+
}
|
|
542
|
+
const raw = fs.readFileSync(fullPath, 'utf-8');
|
|
543
|
+
const content = JSON.parse(raw) as MockData;
|
|
544
|
+
if (!content?.request || !content?.response) {
|
|
545
|
+
return { success: false, error: 'Invalid mock JSON (missing request/response)' };
|
|
546
|
+
}
|
|
547
|
+
const stat = fs.statSync(fullPath);
|
|
548
|
+
return {
|
|
549
|
+
success: true,
|
|
550
|
+
filename: relativePath,
|
|
551
|
+
content,
|
|
552
|
+
modificationTime: stat.mtimeMs,
|
|
553
|
+
};
|
|
554
|
+
} catch (error) {
|
|
555
|
+
return { success: false, error: (error as Error).message };
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* Build payload for GET /mockifyer-sync-to-device (project mock-data → native app via HybridProvider).
|
|
561
|
+
*/
|
|
562
|
+
function buildSyncToDevicePayload(mockDataPath: string): {
|
|
563
|
+
success: boolean;
|
|
564
|
+
files?: Array<{ filename: string; content: MockData; modificationTime: number }>;
|
|
565
|
+
count?: number;
|
|
566
|
+
error?: string;
|
|
567
|
+
} {
|
|
568
|
+
try {
|
|
569
|
+
const currentScenario = getCurrentScenario(mockDataPath);
|
|
570
|
+
const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
|
|
571
|
+
const entries = listScenarioMockJsonFiles(scenarioPath);
|
|
572
|
+
const files: Array<{ filename: string; content: MockData; modificationTime: number }> = [];
|
|
573
|
+
|
|
574
|
+
for (const { relativePath, fullPath } of entries) {
|
|
575
|
+
try {
|
|
576
|
+
const raw = fs.readFileSync(fullPath, 'utf-8');
|
|
577
|
+
const content = JSON.parse(raw) as MockData;
|
|
578
|
+
if (!content?.request || !content?.response) {
|
|
579
|
+
logger.debug(`[MetroSyncMiddleware] Skipping JSON without request/response: ${relativePath}`);
|
|
580
|
+
continue;
|
|
581
|
+
}
|
|
582
|
+
const stat = fs.statSync(fullPath);
|
|
583
|
+
files.push({
|
|
584
|
+
filename: relativePath,
|
|
585
|
+
content,
|
|
586
|
+
modificationTime: stat.mtimeMs,
|
|
587
|
+
});
|
|
588
|
+
} catch (e) {
|
|
589
|
+
logger.warn(`[MetroSyncMiddleware] Could not read ${fullPath}:`, e);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
logger.info(
|
|
594
|
+
`[MetroSyncMiddleware] /mockifyer-sync-to-device: ${files.length} mock file(s) from scenario "${getCurrentScenario(mockDataPath)}"`
|
|
595
|
+
);
|
|
596
|
+
return { success: true, files, count: files.length };
|
|
597
|
+
} catch (error) {
|
|
598
|
+
return { success: false, error: (error as Error).message };
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* Normalize URL pathname from Node/Metro `req.url` so `/mockifyer-sync-to-device/` matches `/mockifyer-sync-to-device`.
|
|
604
|
+
* Without this, trailing slashes fall through to Expo Web's SPA and Expo Router treats them as AppDun routes.
|
|
605
|
+
*/
|
|
606
|
+
function normalizeMiddlewarePathname(reqUrl: string): string {
|
|
607
|
+
if (!reqUrl || typeof reqUrl !== 'string') {
|
|
608
|
+
return '/';
|
|
609
|
+
}
|
|
610
|
+
let pathname = reqUrl.split('?')[0];
|
|
611
|
+
if (pathname.length > 1 && pathname.endsWith('/')) {
|
|
612
|
+
pathname = pathname.slice(0, -1);
|
|
613
|
+
}
|
|
614
|
+
return pathname;
|
|
615
|
+
}
|
|
616
|
+
|
|
407
617
|
/**
|
|
408
618
|
* Metro middleware function
|
|
409
619
|
*/
|
|
@@ -411,9 +621,12 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
411
621
|
const projectRoot = options?.projectRoot || process.cwd();
|
|
412
622
|
const mockDataPath = path.resolve(projectRoot, options?.mockDataPath || 'mock-data');
|
|
413
623
|
const testConfig = getTestGenerationConfig(options);
|
|
624
|
+
|
|
625
|
+
// Log the resolved paths for debugging
|
|
626
|
+
logger.info(`[MetroSyncMiddleware] Initialized with projectRoot: ${projectRoot}, mockDataPath: ${mockDataPath}`);
|
|
414
627
|
|
|
415
628
|
return function mockSyncMiddleware(req: any, res: any, next: any) {
|
|
416
|
-
const url = req.url
|
|
629
|
+
const url = normalizeMiddlewarePathname(req.url || '');
|
|
417
630
|
|
|
418
631
|
// Handle POST endpoint for clearing mocks
|
|
419
632
|
if (url === '/mockifyer-clear' && req.method === 'POST') {
|
|
@@ -449,6 +662,44 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
449
662
|
});
|
|
450
663
|
return;
|
|
451
664
|
}
|
|
665
|
+
|
|
666
|
+
// Project folder → device/simulator: manifest (small JSON)
|
|
667
|
+
if (url === '/mockifyer-sync-to-device-manifest' && req.method === 'GET') {
|
|
668
|
+
const payload = buildSyncToDeviceManifest(mockDataPath);
|
|
669
|
+
res.setHeader('Content-Type', 'application/json');
|
|
670
|
+
res.statusCode = payload.success ? 200 : 500;
|
|
671
|
+
res.end(JSON.stringify(payload));
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
// Single file for HybridProvider (avoids multi‑MB single response)
|
|
676
|
+
if (url === '/mockifyer-sync-to-device-file' && req.method === 'GET') {
|
|
677
|
+
const fullUrl = req.url || '';
|
|
678
|
+
const qIndex = fullUrl.indexOf('?');
|
|
679
|
+
const query = qIndex >= 0 ? fullUrl.slice(qIndex + 1) : '';
|
|
680
|
+
const params = new URLSearchParams(query);
|
|
681
|
+
const pathParam = params.get('path') || '';
|
|
682
|
+
const payload = buildSyncToDeviceSingleFilePayload(mockDataPath, pathParam);
|
|
683
|
+
res.setHeader('Content-Type', 'application/json');
|
|
684
|
+
if (payload.success) {
|
|
685
|
+
res.statusCode = 200;
|
|
686
|
+
} else if (payload.error === 'Not found') {
|
|
687
|
+
res.statusCode = 404;
|
|
688
|
+
} else {
|
|
689
|
+
res.statusCode = 400;
|
|
690
|
+
}
|
|
691
|
+
res.end(JSON.stringify(payload));
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
// Legacy: all files in one response (may OOM / timeout on large scenarios)
|
|
696
|
+
if (url === '/mockifyer-sync-to-device' && req.method === 'GET') {
|
|
697
|
+
const payload = buildSyncToDevicePayload(mockDataPath);
|
|
698
|
+
res.setHeader('Content-Type', 'application/json');
|
|
699
|
+
res.statusCode = payload.success ? 200 : 500;
|
|
700
|
+
res.end(JSON.stringify(payload));
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
452
703
|
|
|
453
704
|
// Handle GET endpoint for sync status
|
|
454
705
|
if (url === '/mockifyer-sync/status' && req.method === 'GET') {
|
|
@@ -479,16 +730,45 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
479
730
|
// Handle GET endpoint for scenario config
|
|
480
731
|
if (url === '/mockifyer-scenario-config' && req.method === 'GET') {
|
|
481
732
|
try {
|
|
733
|
+
// Check environment variable first (highest priority)
|
|
734
|
+
if (process.env.MOCKIFYER_SCENARIO) {
|
|
735
|
+
logger.info(`[MetroSyncMiddleware] Using scenario from MOCKIFYER_SCENARIO env var: ${process.env.MOCKIFYER_SCENARIO}`);
|
|
736
|
+
res.setHeader('Content-Type', 'application/json');
|
|
737
|
+
res.end(JSON.stringify({
|
|
738
|
+
success: true,
|
|
739
|
+
currentScenario: process.env.MOCKIFYER_SCENARIO
|
|
740
|
+
}));
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
|
|
482
744
|
const configPath = path.join(mockDataPath, 'scenario-config.json');
|
|
745
|
+
const resolvedPath = path.resolve(configPath);
|
|
746
|
+
logger.info(`[MetroSyncMiddleware] Reading scenario config from: ${resolvedPath}`);
|
|
747
|
+
logger.info(`[MetroSyncMiddleware] mockDataPath: ${mockDataPath}, projectRoot: ${projectRoot}`);
|
|
748
|
+
|
|
483
749
|
if (fs.existsSync(configPath)) {
|
|
484
|
-
const
|
|
750
|
+
const fileContent = fs.readFileSync(configPath, 'utf-8');
|
|
751
|
+
logger.info(`[MetroSyncMiddleware] File content: ${fileContent}`);
|
|
752
|
+
const config = JSON.parse(fileContent);
|
|
753
|
+
const scenario = config.currentScenario || DEFAULT_SCENARIO;
|
|
754
|
+
logger.info(`[MetroSyncMiddleware] Found scenario in config: ${scenario} (from file: ${JSON.stringify(config)})`);
|
|
755
|
+
|
|
485
756
|
res.setHeader('Content-Type', 'application/json');
|
|
486
|
-
|
|
757
|
+
// Return format expected by ExpoFileSystemProvider: { success: true, currentScenario: ... }
|
|
758
|
+
res.end(JSON.stringify({
|
|
759
|
+
success: true,
|
|
760
|
+
currentScenario: scenario
|
|
761
|
+
}));
|
|
487
762
|
} else {
|
|
763
|
+
logger.info(`[MetroSyncMiddleware] Config file not found at ${resolvedPath}, returning default scenario`);
|
|
488
764
|
res.setHeader('Content-Type', 'application/json');
|
|
489
|
-
res.end(JSON.stringify({
|
|
765
|
+
res.end(JSON.stringify({
|
|
766
|
+
success: true,
|
|
767
|
+
currentScenario: DEFAULT_SCENARIO
|
|
768
|
+
}));
|
|
490
769
|
}
|
|
491
770
|
} catch (error) {
|
|
771
|
+
logger.error(`[MetroSyncMiddleware] Error reading scenario config:`, error);
|
|
492
772
|
res.statusCode = 500;
|
|
493
773
|
res.setHeader('Content-Type', 'application/json');
|
|
494
774
|
res.end(JSON.stringify({ success: false, error: (error as Error).message }));
|
|
@@ -531,14 +811,13 @@ export function startAutoSync(
|
|
|
531
811
|
options?: MetroSyncMiddlewareOptions
|
|
532
812
|
): void {
|
|
533
813
|
if (autoSyncInterval) {
|
|
534
|
-
console.log('[MockSync] Auto-sync already running');
|
|
535
814
|
return;
|
|
536
815
|
}
|
|
537
816
|
|
|
538
817
|
const projectRoot = options?.projectRoot || process.cwd();
|
|
539
818
|
const mockDataPath = path.resolve(projectRoot, options?.mockDataPath || 'mock-data');
|
|
540
819
|
|
|
541
|
-
|
|
820
|
+
logger.info(`[MockSync] Starting auto-sync every ${intervalMs}ms`);
|
|
542
821
|
autoSyncInterval = setInterval(() => {
|
|
543
822
|
syncFromIOSSimulator(projectRoot, mockDataPath);
|
|
544
823
|
}, intervalMs);
|
|
@@ -551,7 +830,6 @@ export function stopAutoSync(): void {
|
|
|
551
830
|
if (autoSyncInterval) {
|
|
552
831
|
clearInterval(autoSyncInterval);
|
|
553
832
|
autoSyncInterval = null;
|
|
554
|
-
console.log('[MockSync] Auto-sync disabled');
|
|
555
833
|
}
|
|
556
834
|
}
|
|
557
835
|
|
package/src/react-native.ts
CHANGED
|
@@ -8,10 +8,11 @@
|
|
|
8
8
|
import { setupMockifyer } from './index';
|
|
9
9
|
import { MemoryProvider, ExpoFileSystemProvider, MockData, HTTPClient } from '@sgedda/mockifyer-core';
|
|
10
10
|
import type { MockifyerConfig } from '@sgedda/mockifyer-core';
|
|
11
|
+
import { logger } from '@sgedda/mockifyer-core';
|
|
11
12
|
|
|
12
13
|
// Re-export MockifyerInstance type to avoid circular dependency
|
|
13
14
|
export interface MockifyerInstance extends HTTPClient {
|
|
14
|
-
reloadMockData: () => void
|
|
15
|
+
reloadMockData: (syncFromProject?: boolean) => Promise<void>;
|
|
15
16
|
clearStaleCacheEntries: () => number;
|
|
16
17
|
clearAllMocks: () => Promise<void>;
|
|
17
18
|
}
|
|
@@ -63,7 +64,7 @@ async function loadBundledMockData(bundledDataPath: string): Promise<MockData[]>
|
|
|
63
64
|
bundledMockData = data;
|
|
64
65
|
return data;
|
|
65
66
|
} catch (error) {
|
|
66
|
-
|
|
67
|
+
logger.warn('[Mockifyer] Could not load bundled mock data:', error);
|
|
67
68
|
return [];
|
|
68
69
|
}
|
|
69
70
|
}
|
|
@@ -100,7 +101,7 @@ export async function setupMockifyerForReactNative(
|
|
|
100
101
|
// Check if Mockifyer is enabled
|
|
101
102
|
const isEnabled = process.env.MOCKIFYER_ENABLED === 'true' || isDev;
|
|
102
103
|
if (!isEnabled) {
|
|
103
|
-
|
|
104
|
+
logger.info('[Mockifyer] Disabled');
|
|
104
105
|
return null;
|
|
105
106
|
}
|
|
106
107
|
|
|
@@ -141,10 +142,20 @@ export async function setupMockifyerForReactNative(
|
|
|
141
142
|
...config,
|
|
142
143
|
});
|
|
143
144
|
|
|
144
|
-
|
|
145
|
-
|
|
145
|
+
logger.info('[Mockifyer] Development mode: Using Hybrid provider (device + project folder)');
|
|
146
|
+
logger.info(`[Mockifyer] Metro endpoint: http://localhost:${metroPort}/mockifyer-save`);
|
|
147
|
+
logger.info(
|
|
148
|
+
`[Mockifyer] Project→device sync: /mockifyer-sync-to-device-manifest + per-file fetch (on reloadMockData); Metro port ${metroPort}`
|
|
149
|
+
);
|
|
146
150
|
if (recordMode) {
|
|
147
|
-
|
|
151
|
+
logger.info('[Mockifyer] Recording mode enabled - new API responses will be saved');
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Pull repo mock-data onto device once Metro + provider are ready (HybridProvider.reload)
|
|
155
|
+
try {
|
|
156
|
+
await instance.reloadMockData(true);
|
|
157
|
+
} catch (error) {
|
|
158
|
+
logger.warn('[Mockifyer] Initial project→device sync failed (Metro running with built mockifyer-fetch?):', error);
|
|
148
159
|
}
|
|
149
160
|
|
|
150
161
|
return instance;
|
|
@@ -158,7 +169,7 @@ export async function setupMockifyerForReactNative(
|
|
|
158
169
|
const mockDataArray = await loadBundledMockData(bundledDataPath);
|
|
159
170
|
|
|
160
171
|
if (mockDataArray.length === 0) {
|
|
161
|
-
|
|
172
|
+
logger.warn('[Mockifyer] No bundled mock data found. Make sure to run the build script first.');
|
|
162
173
|
return null;
|
|
163
174
|
}
|
|
164
175
|
|
|
@@ -177,7 +188,7 @@ export async function setupMockifyerForReactNative(
|
|
|
177
188
|
...config,
|
|
178
189
|
});
|
|
179
190
|
|
|
180
|
-
|
|
191
|
+
logger.info(`[Mockifyer] Production mode: Loaded ${mockDataArray.length} mocks from bundle`);
|
|
181
192
|
return instance;
|
|
182
193
|
}
|
|
183
194
|
}
|