@sgedda/mockifyer-fetch 1.7.2 → 1.8.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 +0 -60
- package/dist/index.d.ts +1 -1
- package/dist/index.js +9 -9
- package/dist/metro-sync-middleware.d.ts +4 -2
- package/dist/metro-sync-middleware.js +256 -17
- package/dist/react-native.d.ts +1 -1
- package/dist/react-native.js +8 -0
- package/package.json +6 -2
- package/src/index.ts +15 -13
- package/src/metro-sync-middleware.ts +279 -21
- package/src/react-native.ts +11 -1
- package/src/clients/fetch-client.d.ts +0 -14
- package/src/clients/fetch-client.d.ts.map +0 -1
- package/src/clients/fetch-client.js +0 -75
- package/src/index.d.ts +0 -10
- package/src/index.d.ts.map +0 -1
- package/src/index.js +0 -966
- package/src/react-native.d.ts +0 -45
- package/src/react-native.d.ts.map +0 -1
- package/src/react-native.js +0 -141
|
@@ -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.
|
|
@@ -45,6 +47,49 @@ const DEFAULT_SCENARIO = 'default';
|
|
|
45
47
|
|
|
46
48
|
let autoSyncInterval: NodeJS.Timeout | null = null;
|
|
47
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
|
+
|
|
48
93
|
/**
|
|
49
94
|
* Get current scenario from scenario-config.json
|
|
50
95
|
*/
|
|
@@ -241,35 +286,26 @@ function saveMockToProjectFolder(
|
|
|
241
286
|
const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
|
|
242
287
|
fs.mkdirSync(scenarioPath, { recursive: true });
|
|
243
288
|
|
|
244
|
-
|
|
245
|
-
const
|
|
246
|
-
const
|
|
247
|
-
|
|
248
|
-
.replace(/\..+/, '')
|
|
249
|
-
.replace(/:/g, '-');
|
|
250
|
-
|
|
251
|
-
// Create a safe filename from the URL
|
|
252
|
-
const urlSafe = mockData.request.url
|
|
253
|
-
.replace(/^https?:\/\//, '')
|
|
254
|
-
.replace(/[^a-zA-Z0-9]/g, '_');
|
|
255
|
-
|
|
256
|
-
const filename = `${dateStr}_${mockData.request.method}_${urlSafe}.json`;
|
|
257
|
-
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);
|
|
258
293
|
|
|
259
294
|
// Check if file already exists - skip saving if it does
|
|
260
295
|
if (fs.existsSync(filePath)) {
|
|
261
|
-
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' };
|
|
262
297
|
}
|
|
263
298
|
|
|
299
|
+
fs.mkdirSync(fullDir, { recursive: true });
|
|
264
300
|
// Write to file
|
|
265
301
|
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
266
|
-
|
|
302
|
+
|
|
267
303
|
// Generate test file if enabled
|
|
268
304
|
if (testConfig) {
|
|
269
305
|
generateTestForMock(mockData, testConfig, projectRoot);
|
|
270
306
|
}
|
|
271
|
-
|
|
272
|
-
return { success: true, filename, scenario: currentScenario };
|
|
307
|
+
|
|
308
|
+
return { success: true, filename: path.join(dir, filename), scenario: currentScenario };
|
|
273
309
|
} catch (error) {
|
|
274
310
|
console.error(`[MockSync] ❌ Error saving mock to project folder:`, error);
|
|
275
311
|
return { success: false, error: (error as Error).message };
|
|
@@ -394,6 +430,190 @@ function syncFromIOSSimulator(
|
|
|
394
430
|
}
|
|
395
431
|
}
|
|
396
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
|
+
|
|
397
617
|
/**
|
|
398
618
|
* Metro middleware function
|
|
399
619
|
*/
|
|
@@ -406,7 +626,7 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
406
626
|
logger.info(`[MetroSyncMiddleware] Initialized with projectRoot: ${projectRoot}, mockDataPath: ${mockDataPath}`);
|
|
407
627
|
|
|
408
628
|
return function mockSyncMiddleware(req: any, res: any, next: any) {
|
|
409
|
-
const url = req.url
|
|
629
|
+
const url = normalizeMiddlewarePathname(req.url || '');
|
|
410
630
|
|
|
411
631
|
// Handle POST endpoint for clearing mocks
|
|
412
632
|
if (url === '/mockifyer-clear' && req.method === 'POST') {
|
|
@@ -442,6 +662,44 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
442
662
|
});
|
|
443
663
|
return;
|
|
444
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
|
+
}
|
|
445
703
|
|
|
446
704
|
// Handle GET endpoint for sync status
|
|
447
705
|
if (url === '/mockifyer-sync/status' && req.method === 'GET') {
|
package/src/react-native.ts
CHANGED
|
@@ -12,7 +12,7 @@ import { logger } from '@sgedda/mockifyer-core';
|
|
|
12
12
|
|
|
13
13
|
// Re-export MockifyerInstance type to avoid circular dependency
|
|
14
14
|
export interface MockifyerInstance extends HTTPClient {
|
|
15
|
-
reloadMockData: () => void
|
|
15
|
+
reloadMockData: (syncFromProject?: boolean) => Promise<void>;
|
|
16
16
|
clearStaleCacheEntries: () => number;
|
|
17
17
|
clearAllMocks: () => Promise<void>;
|
|
18
18
|
}
|
|
@@ -144,10 +144,20 @@ export async function setupMockifyerForReactNative(
|
|
|
144
144
|
|
|
145
145
|
logger.info('[Mockifyer] Development mode: Using Hybrid provider (device + project folder)');
|
|
146
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
|
+
);
|
|
147
150
|
if (recordMode) {
|
|
148
151
|
logger.info('[Mockifyer] Recording mode enabled - new API responses will be saved');
|
|
149
152
|
}
|
|
150
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);
|
|
159
|
+
}
|
|
160
|
+
|
|
151
161
|
return instance;
|
|
152
162
|
} else {
|
|
153
163
|
// PRODUCTION BUILD MODE
|
|
@@ -1,14 +0,0 @@
|
|
|
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
|
|
@@ -1 +0,0 @@
|
|
|
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"}
|
|
@@ -1,75 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
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
|
package/src/index.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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"}
|