@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.
@@ -15,6 +15,7 @@ import * as fs from 'fs';
15
15
  import * as path from 'path';
16
16
  import { execSync } from 'child_process';
17
17
  import { MockData, TestGenerator, TestGenerationOptions } from '@sgedda/mockifyer-core';
18
+ import { logger } from '@sgedda/mockifyer-core';
18
19
 
19
20
  export interface MetroSyncMiddlewareOptions {
20
21
  /** Project root directory (default: process.cwd()) */
@@ -141,12 +142,10 @@ function generateTestForMock(
141
142
  }
142
143
  }
143
144
  } catch (e) {
144
- console.log(`[MockSync] ⚠️ Could not load TestGenerator: ${(e as Error).message}`);
145
145
  return false;
146
146
  }
147
147
 
148
148
  if (!TestGeneratorClass) {
149
- console.log('[MockSync] ⚠️ TestGenerator not available');
150
149
  return false;
151
150
  }
152
151
 
@@ -170,7 +169,6 @@ function generateTestForMock(
170
169
 
171
170
  // If uniqueTestsPerEndpoint is enabled, check if a test file already exists
172
171
  if (options.uniqueTestsPerEndpoint && fs.existsSync(absoluteTestPath)) {
173
- console.log(`[MockSync] ✅ Test file already exists for endpoint ${testInfo.method} ${testInfo.endpoint}, skipping generation`);
174
172
  return true;
175
173
  }
176
174
 
@@ -187,7 +185,6 @@ function generateTestForMock(
187
185
 
188
186
  const existingContent = fs.readFileSync(absoluteTestPath, 'utf-8');
189
187
  if (existingContent.includes(`it('${testName}'`) || existingContent.includes(`it("${testName}"`)) {
190
- console.log(`[MockSync] ✅ Test already exists in ${absoluteTestPath}, skipping generation`);
191
188
  return true;
192
189
  }
193
190
 
@@ -200,18 +197,16 @@ function generateTestForMock(
200
197
  `$1${newTest}\n$1$2`
201
198
  );
202
199
  fs.writeFileSync(absoluteTestPath, updatedContent);
203
- console.log(`[MockSync] ✅ Appended test to existing file: ${absoluteTestPath}`);
204
200
  return true;
205
201
  }
206
202
  } else {
207
203
  // Create new test file
208
204
  fs.writeFileSync(absoluteTestPath, testCode);
209
- console.log(`[MockSync] ✅ Generated test: ${absoluteTestPath}`);
210
205
  }
211
206
 
212
207
  return true;
213
208
  } catch (error) {
214
- console.error(`[MockSync] ❌ Error generating test:`, error);
209
+ logger.error(`[MockSync] ❌ Error generating test:`, error);
215
210
  return false;
216
211
  }
217
212
  }
@@ -237,7 +232,7 @@ function saveMockToProjectFolder(
237
232
  // Also check if the mockData string contains nested sync requests
238
233
  const mockDataStr = JSON.stringify(mockData);
239
234
  if (mockDataStr.includes('/mockifyer-save') || mockDataStr.includes('/mockifyer-clear') || mockDataStr.includes('/mockifyer-sync')) {
240
- console.warn(`[MockSync] ⚠️ Rejecting save - Mock data contains nested Mockifyer sync requests`);
235
+ logger.warn(`[MockSync] ⚠️ Rejecting save - Mock data contains nested Mockifyer sync requests`);
241
236
  return { success: false, error: 'Mock data contains nested Mockifyer sync requests' };
242
237
  }
243
238
 
@@ -263,15 +258,12 @@ function saveMockToProjectFolder(
263
258
 
264
259
  // Check if file already exists - skip saving if it does
265
260
  if (fs.existsSync(filePath)) {
266
- console.log(`[MockSync] ⚠️ File already exists, skipping save: ${filename}`);
267
261
  return { success: true, filename, skipped: true, reason: 'File already exists' };
268
262
  }
269
263
 
270
264
  // Write to file
271
265
  fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
272
266
 
273
- console.log(`[MockSync] ✅ Saved mock to project folder: ${currentScenario}/${filename}`);
274
-
275
267
  // Generate test file if enabled
276
268
  if (testConfig) {
277
269
  generateTestForMock(mockData, testConfig, projectRoot);
@@ -307,10 +299,9 @@ function clearMockFiles(mockDataPath: string): { success: boolean; filesDeleted?
307
299
  }
308
300
  });
309
301
 
310
- console.log(`[MockSync] ✅ Cleared ${deleted} mock files from ${currentScenario}`);
311
302
  return { success: true, filesDeleted: deleted };
312
303
  } catch (error) {
313
- console.error(`[MockSync] ❌ Error clearing mock files:`, error);
304
+ logger.error(`[MockSync] ❌ Error clearing mock files:`, error);
314
305
  return { success: false, error: (error as Error).message };
315
306
  }
316
307
  }
@@ -389,7 +380,6 @@ function syncFromIOSSimulator(
389
380
  }
390
381
  });
391
382
 
392
- console.log(`[MockSync] ✅ Synced ${filesSynced} files from iOS Simulator to ${currentScenario}`);
393
383
  break;
394
384
  }
395
385
  }
@@ -411,6 +401,9 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
411
401
  const projectRoot = options?.projectRoot || process.cwd();
412
402
  const mockDataPath = path.resolve(projectRoot, options?.mockDataPath || 'mock-data');
413
403
  const testConfig = getTestGenerationConfig(options);
404
+
405
+ // Log the resolved paths for debugging
406
+ logger.info(`[MetroSyncMiddleware] Initialized with projectRoot: ${projectRoot}, mockDataPath: ${mockDataPath}`);
414
407
 
415
408
  return function mockSyncMiddleware(req: any, res: any, next: any) {
416
409
  const url = req.url.split('?')[0]; // Remove query params
@@ -479,16 +472,45 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
479
472
  // Handle GET endpoint for scenario config
480
473
  if (url === '/mockifyer-scenario-config' && req.method === 'GET') {
481
474
  try {
475
+ // Check environment variable first (highest priority)
476
+ if (process.env.MOCKIFYER_SCENARIO) {
477
+ logger.info(`[MetroSyncMiddleware] Using scenario from MOCKIFYER_SCENARIO env var: ${process.env.MOCKIFYER_SCENARIO}`);
478
+ res.setHeader('Content-Type', 'application/json');
479
+ res.end(JSON.stringify({
480
+ success: true,
481
+ currentScenario: process.env.MOCKIFYER_SCENARIO
482
+ }));
483
+ return;
484
+ }
485
+
482
486
  const configPath = path.join(mockDataPath, 'scenario-config.json');
487
+ const resolvedPath = path.resolve(configPath);
488
+ logger.info(`[MetroSyncMiddleware] Reading scenario config from: ${resolvedPath}`);
489
+ logger.info(`[MetroSyncMiddleware] mockDataPath: ${mockDataPath}, projectRoot: ${projectRoot}`);
490
+
483
491
  if (fs.existsSync(configPath)) {
484
- const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
492
+ const fileContent = fs.readFileSync(configPath, 'utf-8');
493
+ logger.info(`[MetroSyncMiddleware] File content: ${fileContent}`);
494
+ const config = JSON.parse(fileContent);
495
+ const scenario = config.currentScenario || DEFAULT_SCENARIO;
496
+ logger.info(`[MetroSyncMiddleware] Found scenario in config: ${scenario} (from file: ${JSON.stringify(config)})`);
497
+
485
498
  res.setHeader('Content-Type', 'application/json');
486
- res.end(JSON.stringify(config));
499
+ // Return format expected by ExpoFileSystemProvider: { success: true, currentScenario: ... }
500
+ res.end(JSON.stringify({
501
+ success: true,
502
+ currentScenario: scenario
503
+ }));
487
504
  } else {
505
+ logger.info(`[MetroSyncMiddleware] Config file not found at ${resolvedPath}, returning default scenario`);
488
506
  res.setHeader('Content-Type', 'application/json');
489
- res.end(JSON.stringify({ currentScenario: DEFAULT_SCENARIO }));
507
+ res.end(JSON.stringify({
508
+ success: true,
509
+ currentScenario: DEFAULT_SCENARIO
510
+ }));
490
511
  }
491
512
  } catch (error) {
513
+ logger.error(`[MetroSyncMiddleware] Error reading scenario config:`, error);
492
514
  res.statusCode = 500;
493
515
  res.setHeader('Content-Type', 'application/json');
494
516
  res.end(JSON.stringify({ success: false, error: (error as Error).message }));
@@ -531,14 +553,13 @@ export function startAutoSync(
531
553
  options?: MetroSyncMiddlewareOptions
532
554
  ): void {
533
555
  if (autoSyncInterval) {
534
- console.log('[MockSync] Auto-sync already running');
535
556
  return;
536
557
  }
537
558
 
538
559
  const projectRoot = options?.projectRoot || process.cwd();
539
560
  const mockDataPath = path.resolve(projectRoot, options?.mockDataPath || 'mock-data');
540
561
 
541
- console.log(`[MockSync] Starting auto-sync every ${intervalMs}ms`);
562
+ logger.info(`[MockSync] Starting auto-sync every ${intervalMs}ms`);
542
563
  autoSyncInterval = setInterval(() => {
543
564
  syncFromIOSSimulator(projectRoot, mockDataPath);
544
565
  }, intervalMs);
@@ -551,7 +572,6 @@ export function stopAutoSync(): void {
551
572
  if (autoSyncInterval) {
552
573
  clearInterval(autoSyncInterval);
553
574
  autoSyncInterval = null;
554
- console.log('[MockSync] Auto-sync disabled');
555
575
  }
556
576
  }
557
577
 
@@ -0,0 +1,45 @@
1
+ /**
2
+ * React Native/Expo Helper Functions
3
+ *
4
+ * Simplified setup for React Native applications with automatic
5
+ * conditional provider selection (FileSystem in dev, Memory in prod)
6
+ */
7
+ import { setupMockifyer } from './index';
8
+ import { HTTPClient } from '@sgedda/mockifyer-core';
9
+ export interface MockifyerInstance extends HTTPClient {
10
+ reloadMockData: () => void;
11
+ clearStaleCacheEntries: () => number;
12
+ clearAllMocks: () => Promise<void>;
13
+ }
14
+ export interface ReactNativeMockifyerConfig {
15
+ /** Whether we're in development mode (determines which provider to use) */
16
+ isDev: boolean;
17
+ /** Path to mock data directory (used in development) */
18
+ mockDataPath?: string;
19
+ /** Path to bundled mock data file (used in production) */
20
+ bundledDataPath?: string;
21
+ /** Enable recording mode (development only) */
22
+ recordMode?: boolean;
23
+ /** Additional Mockifyer config options */
24
+ config?: Partial<Parameters<typeof setupMockifyer>[0]>;
25
+ }
26
+ /**
27
+ * Setup Mockifyer for React Native/Expo with automatic conditional provider selection
28
+ *
29
+ * - Development (isDev === true): Uses Expo FileSystem provider - can record mocks
30
+ * - Production (isDev === false): Uses Memory provider with bundled TypeScript file
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * import { setupMockifyerForReactNative } from '@sgedda/mockifyer-fetch/react-native';
35
+ *
36
+ * await setupMockifyerForReactNative({
37
+ * isDev: __DEV__, // Pass React Native's __DEV__ variable
38
+ * mockDataPath: 'mock-data',
39
+ * bundledDataPath: './assets/mock-data',
40
+ * recordMode: process.env.MOCKIFYER_RECORD === 'true',
41
+ * });
42
+ * ```
43
+ */
44
+ export declare function setupMockifyerForReactNative(options: ReactNativeMockifyerConfig): Promise<MockifyerInstance | null>;
45
+ //# sourceMappingURL=react-native.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"react-native.d.ts","sourceRoot":"","sources":["react-native.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAoD,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAKtG,MAAM,WAAW,iBAAkB,SAAQ,UAAU;IACnD,cAAc,EAAE,MAAM,IAAI,CAAC;IAC3B,sBAAsB,EAAE,MAAM,MAAM,CAAC;IACrC,aAAa,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CACpC;AAED,MAAM,WAAW,0BAA0B;IACzC,2EAA2E;IAC3E,KAAK,EAAE,OAAO,CAAC;IACf,wDAAwD;IACxD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,0DAA0D;IAC1D,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,+CAA+C;IAC/C,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,0CAA0C;IAC1C,MAAM,CAAC,EAAE,OAAO,CAAC,UAAU,CAAC,OAAO,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CACxD;AAyCD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,4BAA4B,CAChD,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC,CA4FnC"}
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+ /**
3
+ * React Native/Expo Helper Functions
4
+ *
5
+ * Simplified setup for React Native applications with automatic
6
+ * conditional provider selection (FileSystem in dev, Memory in prod)
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.setupMockifyerForReactNative = setupMockifyerForReactNative;
10
+ const index_1 = require("./index");
11
+ const mockifyer_core_1 = require("@sgedda/mockifyer-core");
12
+ const mockifyer_core_2 = require("@sgedda/mockifyer-core");
13
+ // Lazy load bundled data (only used in production builds)
14
+ let bundledMockData = null;
15
+ /**
16
+ * Load bundled mock data from a TypeScript/JavaScript module
17
+ *
18
+ * Note: For React Native/Metro, we need to handle dynamic imports differently
19
+ * Metro doesn't support dynamic require() with variables, so we use a workaround
20
+ */
21
+ async function loadBundledMockData(bundledDataPath) {
22
+ if (bundledMockData) {
23
+ return bundledMockData;
24
+ }
25
+ try {
26
+ // Metro bundler doesn't support dynamic require() with variables
27
+ // We use eval with a fully constructed string to avoid Metro's static analysis
28
+ // This bypasses Metro's static analysis completely
29
+ const r = 'r';
30
+ const e = 'e';
31
+ const q = 'q';
32
+ const u = 'u';
33
+ const i = 'i';
34
+ const req = r + e + q + u + i + r + e;
35
+ // eslint-disable-next-line no-eval
36
+ const module = eval(`${req}(${JSON.stringify(bundledDataPath)})`);
37
+ const data = Array.isArray(module.mockData)
38
+ ? module.mockData
39
+ : [module.mockData];
40
+ bundledMockData = data;
41
+ return data;
42
+ }
43
+ catch (error) {
44
+ mockifyer_core_2.logger.warn('[Mockifyer] Could not load bundled mock data:', error);
45
+ return [];
46
+ }
47
+ }
48
+ /**
49
+ * Setup Mockifyer for React Native/Expo with automatic conditional provider selection
50
+ *
51
+ * - Development (isDev === true): Uses Expo FileSystem provider - can record mocks
52
+ * - Production (isDev === false): Uses Memory provider with bundled TypeScript file
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * import { setupMockifyerForReactNative } from '@sgedda/mockifyer-fetch/react-native';
57
+ *
58
+ * await setupMockifyerForReactNative({
59
+ * isDev: __DEV__, // Pass React Native's __DEV__ variable
60
+ * mockDataPath: 'mock-data',
61
+ * bundledDataPath: './assets/mock-data',
62
+ * recordMode: process.env.MOCKIFYER_RECORD === 'true',
63
+ * });
64
+ * ```
65
+ */
66
+ async function setupMockifyerForReactNative(options) {
67
+ const { isDev, mockDataPath = 'mock-data', bundledDataPath = './assets/mock-data', recordMode = false, config = {}, } = options;
68
+ // Check if Mockifyer is enabled
69
+ const isEnabled = process.env.MOCKIFYER_ENABLED === 'true' || isDev;
70
+ if (!isEnabled) {
71
+ mockifyer_core_2.logger.info('[Mockifyer] Disabled');
72
+ return null;
73
+ }
74
+ if (isDev === true) {
75
+ // DEVELOPMENT MODE (React Native app running in dev)
76
+ // Use Hybrid provider - saves to both device AND project folder simultaneously
77
+ // Files are immediately available in project folder (no polling needed)
78
+ // Note: The provider's initialize() is async and will be handled by the provider methods
79
+ const metroPort = process.env.METRO_PORT ? parseInt(process.env.METRO_PORT, 10) : 8081;
80
+ // Merge database provider config from options if provided
81
+ const baseDatabaseProvider = {
82
+ type: 'hybrid',
83
+ path: mockDataPath,
84
+ options: {
85
+ metroPort,
86
+ },
87
+ };
88
+ // Merge with config.databaseProvider if provided
89
+ const databaseProviderConfig = config.databaseProvider
90
+ ? {
91
+ ...baseDatabaseProvider,
92
+ ...config.databaseProvider,
93
+ options: {
94
+ ...baseDatabaseProvider.options,
95
+ ...(config.databaseProvider.options || {}),
96
+ metroPort, // Always ensure metroPort is set
97
+ },
98
+ }
99
+ : baseDatabaseProvider;
100
+ const instance = (0, index_1.setupMockifyer)({
101
+ mockDataPath,
102
+ databaseProvider: databaseProviderConfig,
103
+ recordMode,
104
+ useGlobalFetch: true,
105
+ ...config,
106
+ });
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`);
109
+ if (recordMode) {
110
+ mockifyer_core_2.logger.info('[Mockifyer] Recording mode enabled - new API responses will be saved');
111
+ }
112
+ return instance;
113
+ }
114
+ else {
115
+ // PRODUCTION BUILD MODE
116
+ // Use Memory provider with bundled TypeScript file
117
+ const provider = new mockifyer_core_1.MemoryProvider({});
118
+ provider.initialize();
119
+ // Load bundled mock data
120
+ const mockDataArray = await loadBundledMockData(bundledDataPath);
121
+ if (mockDataArray.length === 0) {
122
+ mockifyer_core_2.logger.warn('[Mockifyer] No bundled mock data found. Make sure to run the build script first.');
123
+ return null;
124
+ }
125
+ // Pre-load all mocks into memory
126
+ for (const mockData of mockDataArray) {
127
+ provider.save(mockData);
128
+ }
129
+ const instance = (0, index_1.setupMockifyer)({
130
+ mockDataPath: './mock-data', // Not used with memory provider
131
+ databaseProvider: {
132
+ type: 'memory',
133
+ },
134
+ recordMode: false, // Can't record in production builds
135
+ useGlobalFetch: true,
136
+ ...config,
137
+ });
138
+ mockifyer_core_2.logger.info(`[Mockifyer] Production mode: Loaded ${mockDataArray.length} mocks from bundle`);
139
+ return instance;
140
+ }
141
+ }
@@ -8,6 +8,7 @@
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 {
@@ -63,7 +64,7 @@ async function loadBundledMockData(bundledDataPath: string): Promise<MockData[]>
63
64
  bundledMockData = data;
64
65
  return data;
65
66
  } catch (error) {
66
- console.warn('[Mockifyer] Could not load bundled mock data:', error);
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
- console.log('[Mockifyer] Disabled');
104
+ logger.info('[Mockifyer] Disabled');
104
105
  return null;
105
106
  }
106
107
 
@@ -141,10 +142,10 @@ export async function setupMockifyerForReactNative(
141
142
  ...config,
142
143
  });
143
144
 
144
- console.log('[Mockifyer] Development mode: Using Hybrid provider (device + project folder)');
145
- console.log(`[Mockifyer] Metro endpoint: http://localhost:${metroPort}/mockifyer-save`);
145
+ logger.info('[Mockifyer] Development mode: Using Hybrid provider (device + project folder)');
146
+ logger.info(`[Mockifyer] Metro endpoint: http://localhost:${metroPort}/mockifyer-save`);
146
147
  if (recordMode) {
147
- console.log('[Mockifyer] Recording mode enabled - new API responses will be saved');
148
+ logger.info('[Mockifyer] Recording mode enabled - new API responses will be saved');
148
149
  }
149
150
 
150
151
  return instance;
@@ -158,7 +159,7 @@ export async function setupMockifyerForReactNative(
158
159
  const mockDataArray = await loadBundledMockData(bundledDataPath);
159
160
 
160
161
  if (mockDataArray.length === 0) {
161
- console.warn('[Mockifyer] No bundled mock data found. Make sure to run the build script first.');
162
+ logger.warn('[Mockifyer] No bundled mock data found. Make sure to run the build script first.');
162
163
  return null;
163
164
  }
164
165
 
@@ -177,7 +178,7 @@ export async function setupMockifyerForReactNative(
177
178
  ...config,
178
179
  });
179
180
 
180
- console.log(`[Mockifyer] Production mode: Loaded ${mockDataArray.length} mocks from bundle`);
181
+ logger.info(`[Mockifyer] Production mode: Loaded ${mockDataArray.length} mocks from bundle`);
181
182
  return instance;
182
183
  }
183
184
  }