@sgedda/mockifyer-fetch 1.8.25 → 1.8.32
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/clients/fetch-client.d.ts +12 -3
- package/dist/clients/fetch-client.js +73 -17
- package/dist/index.d.ts +59 -1
- package/dist/index.js +484 -66
- package/dist/metro-config.js +24 -5
- package/dist/metro-sync-middleware.js +51 -1
- package/dist/react-native.d.ts +35 -0
- package/dist/react-native.js +119 -44
- package/dist/utils/dashboard-redis-health.d.ts +19 -0
- package/dist/utils/dashboard-redis-health.js +49 -0
- package/package.json +14 -2
- package/src/clients/fetch-client.ts +142 -27
- package/src/index.ts +691 -86
- package/src/metro-config.ts +28 -5
- package/src/metro-sync-middleware.ts +67 -1
- package/src/react-native.ts +181 -60
- package/src/utils/dashboard-redis-health.ts +58 -0
package/src/metro-config.ts
CHANGED
|
@@ -69,10 +69,33 @@ export interface MetroConfig {
|
|
|
69
69
|
* Node.js built-in modules that need to be stubbed for React Native
|
|
70
70
|
* Includes modules used by Mockifyer packages and their dependencies:
|
|
71
71
|
* - fs, path: Used by FilesystemProvider
|
|
72
|
-
* - assert: Used by @sinonjs/fake-timers
|
|
73
|
-
* -
|
|
72
|
+
* - assert, util: Used by @sinonjs/fake-timers
|
|
73
|
+
* - http, https, async_hooks: request-correlation (Node inbound capture; stubbed on RN)
|
|
74
|
+
* - crypto: crypto-digest optional Node fast path (pure JS fallback on RN)
|
|
74
75
|
*/
|
|
75
|
-
const NODE_BUILTINS = [
|
|
76
|
+
const NODE_BUILTINS = [
|
|
77
|
+
'fs',
|
|
78
|
+
'path',
|
|
79
|
+
'assert',
|
|
80
|
+
'util',
|
|
81
|
+
'http',
|
|
82
|
+
'https',
|
|
83
|
+
'async_hooks',
|
|
84
|
+
'crypto',
|
|
85
|
+
] as const;
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Optional React Native peer dependencies — stubbed when not installed so
|
|
89
|
+
* `tryGetClientIdFromLaunchArguments` and similar helpers no-op instead of crashing Metro.
|
|
90
|
+
*/
|
|
91
|
+
const OPTIONAL_RN_PEER_MODULES = ['react-native-launch-arguments'] as const;
|
|
92
|
+
|
|
93
|
+
function isMockifyerStubbedModule(moduleName: string): boolean {
|
|
94
|
+
return (
|
|
95
|
+
(NODE_BUILTINS as readonly string[]).includes(moduleName) ||
|
|
96
|
+
(OPTIONAL_RN_PEER_MODULES as readonly string[]).includes(moduleName)
|
|
97
|
+
);
|
|
98
|
+
}
|
|
76
99
|
|
|
77
100
|
/**
|
|
78
101
|
* Options for configuring Metro for Mockifyer
|
|
@@ -170,8 +193,8 @@ export function configureMetroForMockifyer(
|
|
|
170
193
|
moduleName: string,
|
|
171
194
|
platform: string | null
|
|
172
195
|
): { filePath: string; type: string } | null | undefined => {
|
|
173
|
-
// Handle Node
|
|
174
|
-
if (
|
|
196
|
+
// Handle Node built-ins and optional RN peers - return empty module stub
|
|
197
|
+
if (isMockifyerStubbedModule(moduleName)) {
|
|
175
198
|
return {
|
|
176
199
|
filePath: emptyModulePath,
|
|
177
200
|
type: 'sourceFile',
|
|
@@ -312,6 +312,51 @@ function saveMockToProjectFolder(
|
|
|
312
312
|
}
|
|
313
313
|
}
|
|
314
314
|
|
|
315
|
+
/**
|
|
316
|
+
* Save a proxy-mirrored mock to an explicit scenario subpath (e.g. `redis/<hash>.json`).
|
|
317
|
+
* Used when the dashboard records to Redis and the RN app POSTs an envelope to `/mockifyer-save`.
|
|
318
|
+
*/
|
|
319
|
+
function saveProxyMirrorMockToProject(
|
|
320
|
+
mockData: MockData,
|
|
321
|
+
projectRoot: string,
|
|
322
|
+
mockDataPath: string,
|
|
323
|
+
scenarioName: string,
|
|
324
|
+
relativePath: string,
|
|
325
|
+
testConfig: TestGenerationOptions | null
|
|
326
|
+
): { success: boolean; filename?: string; scenario?: string; error?: string } {
|
|
327
|
+
try {
|
|
328
|
+
const url = mockData?.request?.url || '';
|
|
329
|
+
if (url.includes('/mockifyer-save') || url.includes('/mockifyer-clear') || url.includes('/mockifyer-sync')) {
|
|
330
|
+
console.warn(`[MockSync] ⚠️ Rejecting save - Mockifyer sync endpoint detected: ${url}`);
|
|
331
|
+
return { success: false, error: 'Cannot save Mockifyer sync endpoint requests' };
|
|
332
|
+
}
|
|
333
|
+
const mockDataStr = JSON.stringify(mockData);
|
|
334
|
+
if (mockDataStr.includes('/mockifyer-save') || mockDataStr.includes('/mockifyer-clear')) {
|
|
335
|
+
return { success: false, error: 'Mock data contains nested Mockifyer sync requests' };
|
|
336
|
+
}
|
|
337
|
+
const id = scenarioName.trim();
|
|
338
|
+
if (!id) {
|
|
339
|
+
return { success: false, error: 'scenarioName is required' };
|
|
340
|
+
}
|
|
341
|
+
const normalized = relativePath.replace(/\\/g, '/').replace(/^\//, '');
|
|
342
|
+
if (!normalized) {
|
|
343
|
+
return { success: false, error: 'relativePath is required' };
|
|
344
|
+
}
|
|
345
|
+
const scenarioPath = getScenarioPath(id, mockDataPath);
|
|
346
|
+
fs.mkdirSync(scenarioPath, { recursive: true });
|
|
347
|
+
const filePath = path.join(scenarioPath, normalized);
|
|
348
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
349
|
+
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
350
|
+
if (testConfig) {
|
|
351
|
+
generateTestForMock(mockData, testConfig, projectRoot);
|
|
352
|
+
}
|
|
353
|
+
return { success: true, filename: normalized, scenario: id };
|
|
354
|
+
} catch (error) {
|
|
355
|
+
console.error(`[MockSync] ❌ Error saving proxy mirror mock:`, error);
|
|
356
|
+
return { success: false, error: (error as Error).message };
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
315
360
|
/**
|
|
316
361
|
* Clear all mock files from project folder (current scenario)
|
|
317
362
|
*/
|
|
@@ -646,7 +691,28 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
646
691
|
|
|
647
692
|
req.on('end', () => {
|
|
648
693
|
try {
|
|
649
|
-
const
|
|
694
|
+
const parsed = JSON.parse(body);
|
|
695
|
+
if (
|
|
696
|
+
parsed &&
|
|
697
|
+
typeof parsed === 'object' &&
|
|
698
|
+
parsed.__mockifyerProxyMirror === true &&
|
|
699
|
+
parsed.mockData
|
|
700
|
+
) {
|
|
701
|
+
const scenarioName = typeof parsed.scenarioName === 'string' ? parsed.scenarioName : '';
|
|
702
|
+
const relativePath = typeof parsed.relativePath === 'string' ? parsed.relativePath : '';
|
|
703
|
+
const result = saveProxyMirrorMockToProject(
|
|
704
|
+
parsed.mockData,
|
|
705
|
+
projectRoot,
|
|
706
|
+
mockDataPath,
|
|
707
|
+
scenarioName,
|
|
708
|
+
relativePath,
|
|
709
|
+
testConfig
|
|
710
|
+
);
|
|
711
|
+
res.setHeader('Content-Type', 'application/json');
|
|
712
|
+
res.end(JSON.stringify(result));
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
const mockData = parsed;
|
|
650
716
|
const result = saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig);
|
|
651
717
|
|
|
652
718
|
res.setHeader('Content-Type', 'application/json');
|
package/src/react-native.ts
CHANGED
|
@@ -5,14 +5,17 @@
|
|
|
5
5
|
* conditional provider selection (FileSystem in dev, Memory in prod)
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import {
|
|
8
|
+
import { canUseDashboardRedisProxy } from './utils/dashboard-redis-health';
|
|
9
9
|
import { setupMockifyer } from './index';
|
|
10
|
-
import { MemoryProvider, ExpoFileSystemProvider, MockData, HTTPClient } from '@sgedda/mockifyer-core';
|
|
10
|
+
import { MemoryProvider, ExpoFileSystemProvider, MockData, HTTPClient, setScenarioLaunchOverride } from '@sgedda/mockifyer-core';
|
|
11
11
|
import {
|
|
12
12
|
logger,
|
|
13
13
|
MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
|
|
14
14
|
tryGetClientIdFromLaunchArguments,
|
|
15
15
|
resolveMockifyerRuntimeMode,
|
|
16
|
+
logMockifyerNotActivated,
|
|
17
|
+
resolveRecordResponses,
|
|
18
|
+
resolveStrictScenarioResolution,
|
|
16
19
|
type MockifyerRuntimeMode,
|
|
17
20
|
} from '@sgedda/mockifyer-core';
|
|
18
21
|
|
|
@@ -61,6 +64,16 @@ export interface ReactNativeMockifyerConfig {
|
|
|
61
64
|
bundledDataPath?: string;
|
|
62
65
|
/** Enable recording mode (development only) */
|
|
63
66
|
recordMode?: boolean;
|
|
67
|
+
/**
|
|
68
|
+
* When true, reads `scenario` from `react-native-launch-arguments` (optional peer).
|
|
69
|
+
* Highest priority over MOCKIFYER_SCENARIO, config.scenarios, Metro scenario sync, and scenario-config.json.
|
|
70
|
+
*/
|
|
71
|
+
useLaunchArgumentsScenario?: boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Sets the same highest-priority scenario as {@link useLaunchArgumentsScenario} when you pass the value yourself
|
|
74
|
+
* (e.g. after reading launch args). Ignored if empty after trim.
|
|
75
|
+
*/
|
|
76
|
+
defaultScenario?: string;
|
|
64
77
|
/** Additional Mockifyer config options */
|
|
65
78
|
config?: Partial<Parameters<typeof setupMockifyer>[0]>;
|
|
66
79
|
/** Optional: route real network calls through a proxy service (e.g. mockifyer-dashboard in Redis mode) */
|
|
@@ -72,6 +85,15 @@ export interface ReactNativeMockifyerConfig {
|
|
|
72
85
|
* Deprecated: prefer using `recordMode` when `proxyBaseUrl` is provided.
|
|
73
86
|
*/
|
|
74
87
|
proxyRecordOnMiss?: boolean;
|
|
88
|
+
/**
|
|
89
|
+
* When false, dashboard proxy stores request-only stubs on cache miss (Responses: Off).
|
|
90
|
+
* Defaults to `false`. Env **`MOCKIFYER_RECORD_RESPONSES`** overrides when set.
|
|
91
|
+
*/
|
|
92
|
+
proxyRecordResponses?: boolean;
|
|
93
|
+
/**
|
|
94
|
+
* When true, skip `GET /api/health` and always wire dashboard proxy (same as Node preset).
|
|
95
|
+
*/
|
|
96
|
+
skipDashboardRedisHealthCheck?: boolean;
|
|
75
97
|
/**
|
|
76
98
|
* When true, read `clientId` from Maestro/native launch arguments (optional peer `react-native-launch-arguments`).
|
|
77
99
|
* Prefer this over passing scenario from E2E if the dashboard/Redis should control scenario on the fly for that lane.
|
|
@@ -89,34 +111,42 @@ export interface ReactNativeMockifyerConfig {
|
|
|
89
111
|
runtimeMode?: MockifyerRuntimeMode;
|
|
90
112
|
}
|
|
91
113
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
114
|
+
/**
|
|
115
|
+
* Apply scenario from launch arguments and/or defaultScenario (highest priority in getCurrentScenario).
|
|
116
|
+
*/
|
|
117
|
+
function applyReactNativeScenarioOptions(options: ReactNativeMockifyerConfig): void {
|
|
118
|
+
let applied = false;
|
|
119
|
+
if (options.useLaunchArgumentsScenario) {
|
|
120
|
+
try {
|
|
121
|
+
// Optional dependency — install `react-native-launch-arguments` in the app when using this flag
|
|
122
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
123
|
+
const mod = require(/* webpackIgnore: true */ 'react-native-launch-arguments') as { LaunchArguments?: { value?: () => Record<string, unknown> } };
|
|
124
|
+
const LaunchArguments = mod.LaunchArguments;
|
|
125
|
+
const raw =
|
|
126
|
+
LaunchArguments && typeof LaunchArguments.value === 'function' ? LaunchArguments.value() : undefined;
|
|
127
|
+
const scenario = raw?.scenario;
|
|
128
|
+
if (scenario !== undefined && scenario !== null && String(scenario).trim() !== '') {
|
|
129
|
+
setScenarioLaunchOverride(String(scenario).trim());
|
|
130
|
+
applied = true;
|
|
131
|
+
}
|
|
132
|
+
} catch {
|
|
133
|
+
// Package not installed or native module unavailable
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (!applied && options.defaultScenario !== undefined && options.defaultScenario !== null) {
|
|
137
|
+
const t = String(options.defaultScenario).trim();
|
|
138
|
+
if (t !== '') {
|
|
139
|
+
setScenarioLaunchOverride(t);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
97
143
|
|
|
98
144
|
// Lazy load bundled data (only used in production builds)
|
|
99
145
|
let bundledMockData: MockData[] | null = null;
|
|
100
146
|
|
|
101
|
-
async function canUseStrictRedisProxy(proxyBaseUrl?: string): Promise<boolean> {
|
|
102
|
-
if (!proxyBaseUrl) return false;
|
|
103
|
-
try {
|
|
104
|
-
const controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined;
|
|
105
|
-
const timeout = setTimeout(() => controller?.abort(), 800);
|
|
106
|
-
const url = joinProxyDashboardApiUrl(proxyBaseUrl, 'api/health');
|
|
107
|
-
const res = await fetch(url, { signal: controller?.signal });
|
|
108
|
-
clearTimeout(timeout);
|
|
109
|
-
if (!res.ok) return false;
|
|
110
|
-
const data = (await res.json()) as DashboardHealth;
|
|
111
|
-
return data?.provider === 'redis' && data?.redisOk === true;
|
|
112
|
-
} catch {
|
|
113
|
-
return false;
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
147
|
/**
|
|
118
148
|
* Load bundled mock data from a TypeScript/JavaScript module
|
|
119
|
-
*
|
|
149
|
+
*
|
|
120
150
|
* Note: For React Native/Metro, we need to handle dynamic imports differently
|
|
121
151
|
* Metro doesn't support dynamic require() with variables, so we use a workaround
|
|
122
152
|
*/
|
|
@@ -166,6 +196,7 @@ async function loadBundledMockData(bundledDataPath: string): Promise<MockData[]>
|
|
|
166
196
|
* mockDataPath: 'mock-data',
|
|
167
197
|
* bundledDataPath: './assets/mock-data',
|
|
168
198
|
* recordMode: process.env.MOCKIFYER_RECORD === 'true',
|
|
199
|
+
* useLaunchArgumentsScenario: true, // optional: scenario from react-native-launch-arguments (highest priority)
|
|
169
200
|
* });
|
|
170
201
|
* // result.status: 'not_activated' | 'active' | 'failed_no_bundled_mocks'
|
|
171
202
|
* ```
|
|
@@ -182,12 +213,17 @@ export async function setupMockifyerForReactNative(
|
|
|
182
213
|
proxyBaseUrl,
|
|
183
214
|
proxyScenario,
|
|
184
215
|
proxyRecordOnMiss,
|
|
216
|
+
proxyRecordResponses,
|
|
217
|
+
skipDashboardRedisHealthCheck,
|
|
185
218
|
useLaunchArgumentsClientId = false,
|
|
186
219
|
launchArgumentClientIdKey = MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
|
|
187
220
|
runtimeMode: runtimeModeOption,
|
|
188
221
|
} = options;
|
|
189
222
|
|
|
190
223
|
const proxyShouldRecordOnMiss = proxyRecordOnMiss ?? recordMode;
|
|
224
|
+
const proxyShouldRecordResponses = resolveRecordResponses(
|
|
225
|
+
proxyRecordResponses ?? userConfig.proxy?.recordResponses
|
|
226
|
+
);
|
|
191
227
|
|
|
192
228
|
const launchClientIdKey =
|
|
193
229
|
launchArgumentClientIdKey ?? MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY;
|
|
@@ -210,28 +246,45 @@ export async function setupMockifyerForReactNative(
|
|
|
210
246
|
: {}),
|
|
211
247
|
};
|
|
212
248
|
|
|
249
|
+
const devInitHeadline = (strictProxy: boolean, strictProxyOnlyFallback: boolean) => {
|
|
250
|
+
if (strictProxy) return 'React Native dev · dashboard Redis proxy';
|
|
251
|
+
if (strictProxyOnlyFallback) {
|
|
252
|
+
return 'React Native dev · strict proxy-only (dashboard unhealthy — local recording disabled)';
|
|
253
|
+
}
|
|
254
|
+
return 'React Native dev · hybrid (device + Metro)';
|
|
255
|
+
};
|
|
256
|
+
|
|
213
257
|
const isEnabled =
|
|
214
258
|
resolvedRuntimeMode === 'on' ||
|
|
215
259
|
(resolvedRuntimeMode === 'launch_client' && Boolean(clientIdFromLaunchArgs));
|
|
216
260
|
if (!isEnabled) {
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
? 'MOCKIFYER_MODE=launch_client — pass mockifyerClientId via launch args, or set MOCKIFYER_MODE=on for always-on dev.'
|
|
222
|
-
: 'Adjust MOCKIFYER_MODE / runtimeMode.';
|
|
223
|
-
logger.info(`[Mockifyer] Not activated (${hint})`);
|
|
261
|
+
logMockifyerNotActivated(resolvedRuntimeMode, {
|
|
262
|
+
launchClientIdKey,
|
|
263
|
+
hadLaunchClientId: Boolean(clientIdFromLaunchArgs),
|
|
264
|
+
});
|
|
224
265
|
return { status: 'not_activated', instance: null } as const;
|
|
225
266
|
}
|
|
226
267
|
|
|
227
|
-
|
|
228
|
-
logger.info(
|
|
229
|
-
`[Mockifyer] Enabled via launch argument "${launchClientIdKey}" (E2E lane "${clientIdFromLaunchArgs}")`
|
|
230
|
-
);
|
|
231
|
-
}
|
|
268
|
+
applyReactNativeScenarioOptions(options);
|
|
232
269
|
|
|
233
270
|
if (isDev === true) {
|
|
234
|
-
const strictProxyEnabled =
|
|
271
|
+
const strictProxyEnabled = proxyBaseUrl
|
|
272
|
+
? skipDashboardRedisHealthCheck === true ||
|
|
273
|
+
(await canUseDashboardRedisProxy(proxyBaseUrl))
|
|
274
|
+
: false;
|
|
275
|
+
|
|
276
|
+
const strictProxyOnlyFallback =
|
|
277
|
+
Boolean(proxyBaseUrl?.trim()) &&
|
|
278
|
+
!strictProxyEnabled &&
|
|
279
|
+
resolveStrictScenarioResolution(mergedConfig);
|
|
280
|
+
|
|
281
|
+
if (strictProxyOnlyFallback) {
|
|
282
|
+
logger.warn(
|
|
283
|
+
`[Mockifyer] Strict proxy-only: "${proxyBaseUrl}" did not report healthy Redis. ` +
|
|
284
|
+
'Using memory provider without local recording. Start mockifyer-dashboard --provider redis ' +
|
|
285
|
+
'or set skipDashboardRedisHealthCheck: true to force proxy.'
|
|
286
|
+
);
|
|
287
|
+
}
|
|
235
288
|
|
|
236
289
|
// DEVELOPMENT MODE (React Native app running in dev)
|
|
237
290
|
// Use Hybrid provider - saves to both device AND project folder simultaneously
|
|
@@ -263,34 +316,48 @@ export async function setupMockifyerForReactNative(
|
|
|
263
316
|
|
|
264
317
|
const instance = setupMockifyer({
|
|
265
318
|
mockDataPath,
|
|
266
|
-
databaseProvider:
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
319
|
+
databaseProvider:
|
|
320
|
+
strictProxyEnabled || strictProxyOnlyFallback
|
|
321
|
+
? {
|
|
322
|
+
// Strict proxy source of truth: disable local mock lookup so all requests go through the dashboard proxy.
|
|
323
|
+
type: 'memory',
|
|
324
|
+
}
|
|
325
|
+
: databaseProviderConfig,
|
|
272
326
|
recordMode,
|
|
273
327
|
useGlobalFetch: true,
|
|
274
|
-
proxy:
|
|
275
|
-
|
|
276
|
-
|
|
328
|
+
proxy:
|
|
329
|
+
strictProxyEnabled && proxyBaseUrl
|
|
330
|
+
? {
|
|
331
|
+
baseUrl: proxyBaseUrl,
|
|
332
|
+
scenario: proxyScenario,
|
|
333
|
+
recordOnMiss: proxyShouldRecordOnMiss,
|
|
334
|
+
recordResponses: proxyShouldRecordResponses,
|
|
335
|
+
}
|
|
336
|
+
: undefined,
|
|
337
|
+
...(strictProxyEnabled
|
|
338
|
+
? {
|
|
339
|
+
strictScenarioResolution: mergedConfig.strictScenarioResolution ?? true,
|
|
340
|
+
}
|
|
341
|
+
: {}),
|
|
277
342
|
...mergedConfig,
|
|
343
|
+
...(strictProxyOnlyFallback
|
|
344
|
+
? {
|
|
345
|
+
databaseProvider: { type: 'memory' as const },
|
|
346
|
+
intendedProxyBaseUrl: proxyBaseUrl!.trim(),
|
|
347
|
+
}
|
|
348
|
+
: {}),
|
|
349
|
+
initLog: {
|
|
350
|
+
headline:
|
|
351
|
+
mergedConfig.initLog?.headline ??
|
|
352
|
+
devInitHeadline(strictProxyEnabled, strictProxyOnlyFallback),
|
|
353
|
+
},
|
|
278
354
|
});
|
|
279
355
|
|
|
280
|
-
if (strictProxyEnabled) {
|
|
281
|
-
logger.info(
|
|
282
|
-
} else {
|
|
283
|
-
logger.info('[Mockifyer] Development mode: Using Hybrid provider (device + project folder)');
|
|
284
|
-
logger.info(`[Mockifyer] Metro endpoint: http://localhost:${metroPort}/mockifyer-save`);
|
|
285
|
-
logger.info(
|
|
286
|
-
`[Mockifyer] Project→device sync: /mockifyer-sync-to-device-manifest + per-file fetch (on reloadMockData); Metro port ${metroPort}`
|
|
287
|
-
);
|
|
288
|
-
}
|
|
289
|
-
if (recordMode) {
|
|
290
|
-
logger.info('[Mockifyer] Recording mode enabled - new API responses will be saved');
|
|
356
|
+
if (!strictProxyEnabled && !strictProxyOnlyFallback) {
|
|
357
|
+
logger.info(`[Mockifyer] Metro: http://localhost:${metroPort}/mockifyer-save · scenario: /mockifyer-scenario-config`);
|
|
291
358
|
}
|
|
292
359
|
|
|
293
|
-
if (!strictProxyEnabled) {
|
|
360
|
+
if (!strictProxyEnabled && !strictProxyOnlyFallback) {
|
|
294
361
|
// Pull repo mock-data onto device once Metro + provider are ready (HybridProvider.reload)
|
|
295
362
|
try {
|
|
296
363
|
await instance.reloadMockData(true);
|
|
@@ -329,16 +396,70 @@ export async function setupMockifyerForReactNative(
|
|
|
329
396
|
recordMode: false, // Can't record in production builds
|
|
330
397
|
useGlobalFetch: true,
|
|
331
398
|
proxy: proxyBaseUrl
|
|
332
|
-
? {
|
|
399
|
+
? {
|
|
400
|
+
baseUrl: proxyBaseUrl,
|
|
401
|
+
scenario: proxyScenario,
|
|
402
|
+
recordOnMiss: proxyShouldRecordOnMiss,
|
|
403
|
+
recordResponses: proxyShouldRecordResponses,
|
|
404
|
+
}
|
|
333
405
|
: undefined,
|
|
406
|
+
...(proxyBaseUrl
|
|
407
|
+
? {
|
|
408
|
+
strictScenarioResolution: mergedConfig.strictScenarioResolution ?? true,
|
|
409
|
+
}
|
|
410
|
+
: {}),
|
|
334
411
|
...mergedConfig,
|
|
412
|
+
initLog: {
|
|
413
|
+
headline:
|
|
414
|
+
mergedConfig.initLog?.headline ??
|
|
415
|
+
`React Native production · ${mockDataArray.length} bundled mock(s)`,
|
|
416
|
+
},
|
|
335
417
|
});
|
|
336
418
|
|
|
337
|
-
logger.info(`[Mockifyer] Production mode: Loaded ${mockDataArray.length} mocks from bundle`);
|
|
338
419
|
return { status: 'active', instance } as const;
|
|
339
420
|
}
|
|
340
421
|
}
|
|
341
422
|
|
|
423
|
+
/** React Native options with an explicit dashboard alias (see {@link initMockifyerForReactNativeDashboard}). */
|
|
424
|
+
export interface InitMockifyerForReactNativeDashboardOptions extends ReactNativeMockifyerConfig {
|
|
425
|
+
/**
|
|
426
|
+
* mockifyer-dashboard origin — same role as {@link ReactNativeMockifyerConfig.proxyBaseUrl}.
|
|
427
|
+
* Useful when you prefer naming that matches the Node preset {@link initMockifyerForDashboardProxy}.
|
|
428
|
+
*/
|
|
429
|
+
dashboardBaseUrl?: string;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Preset: point the app at **mockifyer-dashboard** for `/api/proxy` (typically **`--provider redis`**).
|
|
434
|
+
*
|
|
435
|
+
* Resolves URL in order: **`proxyBaseUrl`** → **`dashboardBaseUrl`** → **`MOCKIFYER_PROXY_URL`** env.
|
|
436
|
+
* Then delegates to {@link setupMockifyerForReactNative}. For bespoke wiring, call that helper directly.
|
|
437
|
+
*/
|
|
438
|
+
export async function initMockifyerForReactNativeDashboard(
|
|
439
|
+
options: InitMockifyerForReactNativeDashboardOptions
|
|
440
|
+
): Promise<SetupMockifyerForReactNativeResult> {
|
|
441
|
+
const fromEnv =
|
|
442
|
+
typeof process !== 'undefined' && process.env?.MOCKIFYER_PROXY_URL
|
|
443
|
+
? process.env.MOCKIFYER_PROXY_URL.trim()
|
|
444
|
+
: '';
|
|
445
|
+
|
|
446
|
+
const resolved =
|
|
447
|
+
String(options.proxyBaseUrl ?? '').trim() ||
|
|
448
|
+
String(options.dashboardBaseUrl ?? '').trim() ||
|
|
449
|
+
fromEnv;
|
|
450
|
+
|
|
451
|
+
if (!resolved) {
|
|
452
|
+
throw new Error(
|
|
453
|
+
'initMockifyerForReactNativeDashboard: set proxyBaseUrl, dashboardBaseUrl, or MOCKIFYER_PROXY_URL'
|
|
454
|
+
);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
return setupMockifyerForReactNative({
|
|
458
|
+
...options,
|
|
459
|
+
proxyBaseUrl: resolved,
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
|
|
342
463
|
export {
|
|
343
464
|
tryGetClientIdFromLaunchArguments,
|
|
344
465
|
MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { joinProxyDashboardApiUrl } from './join-proxy-dashboard-api-url';
|
|
2
|
+
|
|
3
|
+
const HEALTH_TIMEOUT_MS = 800;
|
|
4
|
+
|
|
5
|
+
/** Body shape returned by mockifyer-dashboard `GET /api/health` (subset). */
|
|
6
|
+
export interface DashboardHealthPayload {
|
|
7
|
+
status?: string;
|
|
8
|
+
provider?: string;
|
|
9
|
+
redisOk?: boolean | null;
|
|
10
|
+
sqliteOk?: boolean | null;
|
|
11
|
+
/** When true, dashboard central store (redis or sqlite) is ready for `/api/proxy`. */
|
|
12
|
+
centralStoreOk?: boolean | null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function centralStoreHealthy(data: DashboardHealthPayload): boolean {
|
|
16
|
+
if (data.centralStoreOk === true) {
|
|
17
|
+
return true;
|
|
18
|
+
}
|
|
19
|
+
if (data.provider === 'redis' && data.redisOk === true) {
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
if (data.provider === 'sqlite' && data.sqliteOk === true) {
|
|
23
|
+
return true;
|
|
24
|
+
}
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* True when mockifyer-dashboard responds to **`GET /api/health`** with a healthy central store
|
|
30
|
+
* (**`provider === 'redis'`** and **`redisOk`**, or **`provider === 'sqlite'`** and **`sqliteOk`**,
|
|
31
|
+
* or **`centralStoreOk === true`**). Same gate as React Native strict proxy / **`initMockifyerForDashboardProxy`**.
|
|
32
|
+
*/
|
|
33
|
+
export async function canUseDashboardCentralProxy(proxyBaseUrl: string | undefined): Promise<boolean> {
|
|
34
|
+
if (!proxyBaseUrl?.trim()) {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
try {
|
|
38
|
+
const controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined;
|
|
39
|
+
const timeout = setTimeout(() => controller?.abort(), HEALTH_TIMEOUT_MS);
|
|
40
|
+
const url = joinProxyDashboardApiUrl(proxyBaseUrl.trim(), 'api/health');
|
|
41
|
+
const res = await fetch(url, { signal: controller?.signal });
|
|
42
|
+
clearTimeout(timeout);
|
|
43
|
+
if (!res.ok) {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
const data = (await res.json()) as DashboardHealthPayload;
|
|
47
|
+
return centralStoreHealthy(data);
|
|
48
|
+
} catch {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @deprecated Use {@link canUseDashboardCentralProxy}. Kept for existing imports.
|
|
55
|
+
*/
|
|
56
|
+
export async function canUseDashboardRedisProxy(proxyBaseUrl: string | undefined): Promise<boolean> {
|
|
57
|
+
return canUseDashboardCentralProxy(proxyBaseUrl);
|
|
58
|
+
}
|