@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.
@@ -52,10 +52,29 @@ const mockifyer_core_1 = require("@sgedda/mockifyer-core");
52
52
  * Node.js built-in modules that need to be stubbed for React Native
53
53
  * Includes modules used by Mockifyer packages and their dependencies:
54
54
  * - fs, path: Used by FilesystemProvider
55
- * - assert: Used by @sinonjs/fake-timers
56
- * - util: Used by @sinonjs/fake-timers
55
+ * - assert, util: Used by @sinonjs/fake-timers
56
+ * - http, https, async_hooks: request-correlation (Node inbound capture; stubbed on RN)
57
+ * - crypto: crypto-digest optional Node fast path (pure JS fallback on RN)
57
58
  */
58
- const NODE_BUILTINS = ['fs', 'path', 'assert', 'util'];
59
+ const NODE_BUILTINS = [
60
+ 'fs',
61
+ 'path',
62
+ 'assert',
63
+ 'util',
64
+ 'http',
65
+ 'https',
66
+ 'async_hooks',
67
+ 'crypto',
68
+ ];
69
+ /**
70
+ * Optional React Native peer dependencies — stubbed when not installed so
71
+ * `tryGetClientIdFromLaunchArguments` and similar helpers no-op instead of crashing Metro.
72
+ */
73
+ const OPTIONAL_RN_PEER_MODULES = ['react-native-launch-arguments'];
74
+ function isMockifyerStubbedModule(moduleName) {
75
+ return (NODE_BUILTINS.includes(moduleName) ||
76
+ OPTIONAL_RN_PEER_MODULES.includes(moduleName));
77
+ }
59
78
  /**
60
79
  * Configure Metro bundler for Mockifyer
61
80
  *
@@ -125,8 +144,8 @@ function configureMetroForMockifyer(config, options) {
125
144
  const existingResolveRequest = existingResolver.resolveRequest;
126
145
  // Create new resolveRequest function that handles Node.js built-ins
127
146
  const newResolveRequest = (context, moduleName, platform) => {
128
- // Handle Node.js built-in modules - return empty module stub
129
- if (NODE_BUILTINS.includes(moduleName)) {
147
+ // Handle Node built-ins and optional RN peers - return empty module stub
148
+ if (isMockifyerStubbedModule(moduleName)) {
130
149
  return {
131
150
  filePath: emptyModulePath,
132
151
  type: 'sourceFile',
@@ -290,6 +290,44 @@ function saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig
290
290
  return { success: false, error: error.message };
291
291
  }
292
292
  }
293
+ /**
294
+ * Save a proxy-mirrored mock to an explicit scenario subpath (e.g. `redis/<hash>.json`).
295
+ * Used when the dashboard records to Redis and the RN app POSTs an envelope to `/mockifyer-save`.
296
+ */
297
+ function saveProxyMirrorMockToProject(mockData, projectRoot, mockDataPath, scenarioName, relativePath, testConfig) {
298
+ try {
299
+ const url = mockData?.request?.url || '';
300
+ if (url.includes('/mockifyer-save') || url.includes('/mockifyer-clear') || url.includes('/mockifyer-sync')) {
301
+ console.warn(`[MockSync] ⚠️ Rejecting save - Mockifyer sync endpoint detected: ${url}`);
302
+ return { success: false, error: 'Cannot save Mockifyer sync endpoint requests' };
303
+ }
304
+ const mockDataStr = JSON.stringify(mockData);
305
+ if (mockDataStr.includes('/mockifyer-save') || mockDataStr.includes('/mockifyer-clear')) {
306
+ return { success: false, error: 'Mock data contains nested Mockifyer sync requests' };
307
+ }
308
+ const id = scenarioName.trim();
309
+ if (!id) {
310
+ return { success: false, error: 'scenarioName is required' };
311
+ }
312
+ const normalized = relativePath.replace(/\\/g, '/').replace(/^\//, '');
313
+ if (!normalized) {
314
+ return { success: false, error: 'relativePath is required' };
315
+ }
316
+ const scenarioPath = getScenarioPath(id, mockDataPath);
317
+ fs.mkdirSync(scenarioPath, { recursive: true });
318
+ const filePath = path.join(scenarioPath, normalized);
319
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
320
+ fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
321
+ if (testConfig) {
322
+ generateTestForMock(mockData, testConfig, projectRoot);
323
+ }
324
+ return { success: true, filename: normalized, scenario: id };
325
+ }
326
+ catch (error) {
327
+ console.error(`[MockSync] ❌ Error saving proxy mirror mock:`, error);
328
+ return { success: false, error: error.message };
329
+ }
330
+ }
293
331
  /**
294
332
  * Clear all mock files from project folder (current scenario)
295
333
  */
@@ -565,7 +603,19 @@ function createMockSyncMiddleware(options) {
565
603
  });
566
604
  req.on('end', () => {
567
605
  try {
568
- const mockData = JSON.parse(body);
606
+ const parsed = JSON.parse(body);
607
+ if (parsed &&
608
+ typeof parsed === 'object' &&
609
+ parsed.__mockifyerProxyMirror === true &&
610
+ parsed.mockData) {
611
+ const scenarioName = typeof parsed.scenarioName === 'string' ? parsed.scenarioName : '';
612
+ const relativePath = typeof parsed.relativePath === 'string' ? parsed.relativePath : '';
613
+ const result = saveProxyMirrorMockToProject(parsed.mockData, projectRoot, mockDataPath, scenarioName, relativePath, testConfig);
614
+ res.setHeader('Content-Type', 'application/json');
615
+ res.end(JSON.stringify(result));
616
+ return;
617
+ }
618
+ const mockData = parsed;
569
619
  const result = saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig);
570
620
  res.setHeader('Content-Type', 'application/json');
571
621
  res.end(JSON.stringify(result));
@@ -49,6 +49,16 @@ export interface ReactNativeMockifyerConfig {
49
49
  bundledDataPath?: string;
50
50
  /** Enable recording mode (development only) */
51
51
  recordMode?: boolean;
52
+ /**
53
+ * When true, reads `scenario` from `react-native-launch-arguments` (optional peer).
54
+ * Highest priority over MOCKIFYER_SCENARIO, config.scenarios, Metro scenario sync, and scenario-config.json.
55
+ */
56
+ useLaunchArgumentsScenario?: boolean;
57
+ /**
58
+ * Sets the same highest-priority scenario as {@link useLaunchArgumentsScenario} when you pass the value yourself
59
+ * (e.g. after reading launch args). Ignored if empty after trim.
60
+ */
61
+ defaultScenario?: string;
52
62
  /** Additional Mockifyer config options */
53
63
  config?: Partial<Parameters<typeof setupMockifyer>[0]>;
54
64
  /** Optional: route real network calls through a proxy service (e.g. mockifyer-dashboard in Redis mode) */
@@ -60,6 +70,15 @@ export interface ReactNativeMockifyerConfig {
60
70
  * Deprecated: prefer using `recordMode` when `proxyBaseUrl` is provided.
61
71
  */
62
72
  proxyRecordOnMiss?: boolean;
73
+ /**
74
+ * When false, dashboard proxy stores request-only stubs on cache miss (Responses: Off).
75
+ * Defaults to `false`. Env **`MOCKIFYER_RECORD_RESPONSES`** overrides when set.
76
+ */
77
+ proxyRecordResponses?: boolean;
78
+ /**
79
+ * When true, skip `GET /api/health` and always wire dashboard proxy (same as Node preset).
80
+ */
81
+ skipDashboardRedisHealthCheck?: boolean;
63
82
  /**
64
83
  * When true, read `clientId` from Maestro/native launch arguments (optional peer `react-native-launch-arguments`).
65
84
  * Prefer this over passing scenario from E2E if the dashboard/Redis should control scenario on the fly for that lane.
@@ -92,9 +111,25 @@ export interface ReactNativeMockifyerConfig {
92
111
  * mockDataPath: 'mock-data',
93
112
  * bundledDataPath: './assets/mock-data',
94
113
  * recordMode: process.env.MOCKIFYER_RECORD === 'true',
114
+ * useLaunchArgumentsScenario: true, // optional: scenario from react-native-launch-arguments (highest priority)
95
115
  * });
96
116
  * // result.status: 'not_activated' | 'active' | 'failed_no_bundled_mocks'
97
117
  * ```
98
118
  */
99
119
  export declare function setupMockifyerForReactNative(options: ReactNativeMockifyerConfig): Promise<SetupMockifyerForReactNativeResult>;
120
+ /** React Native options with an explicit dashboard alias (see {@link initMockifyerForReactNativeDashboard}). */
121
+ export interface InitMockifyerForReactNativeDashboardOptions extends ReactNativeMockifyerConfig {
122
+ /**
123
+ * mockifyer-dashboard origin — same role as {@link ReactNativeMockifyerConfig.proxyBaseUrl}.
124
+ * Useful when you prefer naming that matches the Node preset {@link initMockifyerForDashboardProxy}.
125
+ */
126
+ dashboardBaseUrl?: string;
127
+ }
128
+ /**
129
+ * Preset: point the app at **mockifyer-dashboard** for `/api/proxy` (typically **`--provider redis`**).
130
+ *
131
+ * Resolves URL in order: **`proxyBaseUrl`** → **`dashboardBaseUrl`** → **`MOCKIFYER_PROXY_URL`** env.
132
+ * Then delegates to {@link setupMockifyerForReactNative}. For bespoke wiring, call that helper directly.
133
+ */
134
+ export declare function initMockifyerForReactNativeDashboard(options: InitMockifyerForReactNativeDashboardOptions): Promise<SetupMockifyerForReactNativeResult>;
100
135
  export { tryGetClientIdFromLaunchArguments, MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY, getClientId, setClientId, registerMockifyerInstance, clearMockifyerClientIdRuntime, } from '@sgedda/mockifyer-core';
@@ -9,7 +9,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.clearMockifyerClientIdRuntime = exports.registerMockifyerInstance = exports.setClientId = exports.getClientId = exports.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY = exports.tryGetClientIdFromLaunchArguments = void 0;
10
10
  exports.isMockifyerReactNativeActive = isMockifyerReactNativeActive;
11
11
  exports.setupMockifyerForReactNative = setupMockifyerForReactNative;
12
- const join_proxy_dashboard_api_url_1 = require("./utils/join-proxy-dashboard-api-url");
12
+ exports.initMockifyerForReactNativeDashboard = initMockifyerForReactNativeDashboard;
13
+ const dashboard_redis_health_1 = require("./utils/dashboard-redis-health");
13
14
  const index_1 = require("./index");
14
15
  const mockifyer_core_1 = require("@sgedda/mockifyer-core");
15
16
  const mockifyer_core_2 = require("@sgedda/mockifyer-core");
@@ -19,26 +20,37 @@ const mockifyer_core_2 = require("@sgedda/mockifyer-core");
19
20
  function isMockifyerReactNativeActive(result) {
20
21
  return result.status === 'active';
21
22
  }
22
- // Lazy load bundled data (only used in production builds)
23
- let bundledMockData = null;
24
- async function canUseStrictRedisProxy(proxyBaseUrl) {
25
- if (!proxyBaseUrl)
26
- return false;
27
- try {
28
- const controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined;
29
- const timeout = setTimeout(() => controller?.abort(), 800);
30
- const url = (0, join_proxy_dashboard_api_url_1.joinProxyDashboardApiUrl)(proxyBaseUrl, 'api/health');
31
- const res = await fetch(url, { signal: controller?.signal });
32
- clearTimeout(timeout);
33
- if (!res.ok)
34
- return false;
35
- const data = (await res.json());
36
- return data?.provider === 'redis' && data?.redisOk === true;
23
+ /**
24
+ * Apply scenario from launch arguments and/or defaultScenario (highest priority in getCurrentScenario).
25
+ */
26
+ function applyReactNativeScenarioOptions(options) {
27
+ let applied = false;
28
+ if (options.useLaunchArgumentsScenario) {
29
+ try {
30
+ // Optional dependency — install `react-native-launch-arguments` in the app when using this flag
31
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
32
+ const mod = require(/* webpackIgnore: true */ 'react-native-launch-arguments');
33
+ const LaunchArguments = mod.LaunchArguments;
34
+ const raw = LaunchArguments && typeof LaunchArguments.value === 'function' ? LaunchArguments.value() : undefined;
35
+ const scenario = raw?.scenario;
36
+ if (scenario !== undefined && scenario !== null && String(scenario).trim() !== '') {
37
+ (0, mockifyer_core_1.setScenarioLaunchOverride)(String(scenario).trim());
38
+ applied = true;
39
+ }
40
+ }
41
+ catch {
42
+ // Package not installed or native module unavailable
43
+ }
37
44
  }
38
- catch {
39
- return false;
45
+ if (!applied && options.defaultScenario !== undefined && options.defaultScenario !== null) {
46
+ const t = String(options.defaultScenario).trim();
47
+ if (t !== '') {
48
+ (0, mockifyer_core_1.setScenarioLaunchOverride)(t);
49
+ }
40
50
  }
41
51
  }
52
+ // Lazy load bundled data (only used in production builds)
53
+ let bundledMockData = null;
42
54
  /**
43
55
  * Load bundled mock data from a TypeScript/JavaScript module
44
56
  *
@@ -88,13 +100,15 @@ async function loadBundledMockData(bundledDataPath) {
88
100
  * mockDataPath: 'mock-data',
89
101
  * bundledDataPath: './assets/mock-data',
90
102
  * recordMode: process.env.MOCKIFYER_RECORD === 'true',
103
+ * useLaunchArgumentsScenario: true, // optional: scenario from react-native-launch-arguments (highest priority)
91
104
  * });
92
105
  * // result.status: 'not_activated' | 'active' | 'failed_no_bundled_mocks'
93
106
  * ```
94
107
  */
95
108
  async function setupMockifyerForReactNative(options) {
96
- const { isDev, mockDataPath = 'mock-data', bundledDataPath = './assets/mock-data', recordMode = false, config: userConfig = {}, proxyBaseUrl, proxyScenario, proxyRecordOnMiss, useLaunchArgumentsClientId = false, launchArgumentClientIdKey = mockifyer_core_2.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY, runtimeMode: runtimeModeOption, } = options;
109
+ const { isDev, mockDataPath = 'mock-data', bundledDataPath = './assets/mock-data', recordMode = false, config: userConfig = {}, proxyBaseUrl, proxyScenario, proxyRecordOnMiss, proxyRecordResponses, skipDashboardRedisHealthCheck, useLaunchArgumentsClientId = false, launchArgumentClientIdKey = mockifyer_core_2.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY, runtimeMode: runtimeModeOption, } = options;
97
110
  const proxyShouldRecordOnMiss = proxyRecordOnMiss ?? recordMode;
111
+ const proxyShouldRecordResponses = (0, mockifyer_core_2.resolveRecordResponses)(proxyRecordResponses ?? userConfig.proxy?.recordResponses);
98
112
  const launchClientIdKey = launchArgumentClientIdKey ?? mockifyer_core_2.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY;
99
113
  const clientIdFromLaunchArgs = (0, mockifyer_core_2.tryGetClientIdFromLaunchArguments)(launchClientIdKey);
100
114
  const shouldApplyLaunchClientId = useLaunchArgumentsClientId || Boolean(clientIdFromLaunchArgs);
@@ -111,22 +125,37 @@ async function setupMockifyerForReactNative(options) {
111
125
  }
112
126
  : {}),
113
127
  };
128
+ const devInitHeadline = (strictProxy, strictProxyOnlyFallback) => {
129
+ if (strictProxy)
130
+ return 'React Native dev · dashboard Redis proxy';
131
+ if (strictProxyOnlyFallback) {
132
+ return 'React Native dev · strict proxy-only (dashboard unhealthy — local recording disabled)';
133
+ }
134
+ return 'React Native dev · hybrid (device + Metro)';
135
+ };
114
136
  const isEnabled = resolvedRuntimeMode === 'on' ||
115
137
  (resolvedRuntimeMode === 'launch_client' && Boolean(clientIdFromLaunchArgs));
116
138
  if (!isEnabled) {
117
- const hint = resolvedRuntimeMode === 'off'
118
- ? 'MOCKIFYER_MODE=off (or runtimeMode off) — launch args are ignored.'
119
- : resolvedRuntimeMode === 'launch_client'
120
- ? 'MOCKIFYER_MODE=launch_client — pass mockifyerClientId via launch args, or set MOCKIFYER_MODE=on for always-on dev.'
121
- : 'Adjust MOCKIFYER_MODE / runtimeMode.';
122
- mockifyer_core_2.logger.info(`[Mockifyer] Not activated (${hint})`);
139
+ (0, mockifyer_core_2.logMockifyerNotActivated)(resolvedRuntimeMode, {
140
+ launchClientIdKey,
141
+ hadLaunchClientId: Boolean(clientIdFromLaunchArgs),
142
+ });
123
143
  return { status: 'not_activated', instance: null };
124
144
  }
125
- if (clientIdFromLaunchArgs && !useLaunchArgumentsClientId) {
126
- mockifyer_core_2.logger.info(`[Mockifyer] Enabled via launch argument "${launchClientIdKey}" (E2E lane "${clientIdFromLaunchArgs}")`);
127
- }
145
+ applyReactNativeScenarioOptions(options);
128
146
  if (isDev === true) {
129
- const strictProxyEnabled = await canUseStrictRedisProxy(proxyBaseUrl);
147
+ const strictProxyEnabled = proxyBaseUrl
148
+ ? skipDashboardRedisHealthCheck === true ||
149
+ (await (0, dashboard_redis_health_1.canUseDashboardRedisProxy)(proxyBaseUrl))
150
+ : false;
151
+ const strictProxyOnlyFallback = Boolean(proxyBaseUrl?.trim()) &&
152
+ !strictProxyEnabled &&
153
+ (0, mockifyer_core_2.resolveStrictScenarioResolution)(mergedConfig);
154
+ if (strictProxyOnlyFallback) {
155
+ mockifyer_core_2.logger.warn(`[Mockifyer] Strict proxy-only: "${proxyBaseUrl}" did not report healthy Redis. ` +
156
+ 'Using memory provider without local recording. Start mockifyer-dashboard --provider redis ' +
157
+ 'or set skipDashboardRedisHealthCheck: true to force proxy.');
158
+ }
130
159
  // DEVELOPMENT MODE (React Native app running in dev)
131
160
  // Use Hybrid provider - saves to both device AND project folder simultaneously
132
161
  // Files are immediately available in project folder (no polling needed)
@@ -154,7 +183,7 @@ async function setupMockifyerForReactNative(options) {
154
183
  : baseDatabaseProvider;
155
184
  const instance = (0, index_1.setupMockifyer)({
156
185
  mockDataPath,
157
- databaseProvider: strictProxyEnabled
186
+ databaseProvider: strictProxyEnabled || strictProxyOnlyFallback
158
187
  ? {
159
188
  // Strict proxy source of truth: disable local mock lookup so all requests go through the dashboard proxy.
160
189
  type: 'memory',
@@ -163,22 +192,34 @@ async function setupMockifyerForReactNative(options) {
163
192
  recordMode,
164
193
  useGlobalFetch: true,
165
194
  proxy: strictProxyEnabled && proxyBaseUrl
166
- ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyShouldRecordOnMiss }
195
+ ? {
196
+ baseUrl: proxyBaseUrl,
197
+ scenario: proxyScenario,
198
+ recordOnMiss: proxyShouldRecordOnMiss,
199
+ recordResponses: proxyShouldRecordResponses,
200
+ }
167
201
  : undefined,
202
+ ...(strictProxyEnabled
203
+ ? {
204
+ strictScenarioResolution: mergedConfig.strictScenarioResolution ?? true,
205
+ }
206
+ : {}),
168
207
  ...mergedConfig,
208
+ ...(strictProxyOnlyFallback
209
+ ? {
210
+ databaseProvider: { type: 'memory' },
211
+ intendedProxyBaseUrl: proxyBaseUrl.trim(),
212
+ }
213
+ : {}),
214
+ initLog: {
215
+ headline: mergedConfig.initLog?.headline ??
216
+ devInitHeadline(strictProxyEnabled, strictProxyOnlyFallback),
217
+ },
169
218
  });
170
- if (strictProxyEnabled) {
171
- mockifyer_core_2.logger.info('[Mockifyer] Development mode: Strict proxy enabled (dashboard Redis is healthy) — local mocks disabled');
219
+ if (!strictProxyEnabled && !strictProxyOnlyFallback) {
220
+ mockifyer_core_2.logger.info(`[Mockifyer] Metro: http://localhost:${metroPort}/mockifyer-save · scenario: /mockifyer-scenario-config`);
172
221
  }
173
- else {
174
- mockifyer_core_2.logger.info('[Mockifyer] Development mode: Using Hybrid provider (device + project folder)');
175
- mockifyer_core_2.logger.info(`[Mockifyer] Metro endpoint: http://localhost:${metroPort}/mockifyer-save`);
176
- mockifyer_core_2.logger.info(`[Mockifyer] Project→device sync: /mockifyer-sync-to-device-manifest + per-file fetch (on reloadMockData); Metro port ${metroPort}`);
177
- }
178
- if (recordMode) {
179
- mockifyer_core_2.logger.info('[Mockifyer] Recording mode enabled - new API responses will be saved');
180
- }
181
- if (!strictProxyEnabled) {
222
+ if (!strictProxyEnabled && !strictProxyOnlyFallback) {
182
223
  // Pull repo mock-data onto device once Metro + provider are ready (HybridProvider.reload)
183
224
  try {
184
225
  await instance.reloadMockData(true);
@@ -212,14 +253,48 @@ async function setupMockifyerForReactNative(options) {
212
253
  recordMode: false, // Can't record in production builds
213
254
  useGlobalFetch: true,
214
255
  proxy: proxyBaseUrl
215
- ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyShouldRecordOnMiss }
256
+ ? {
257
+ baseUrl: proxyBaseUrl,
258
+ scenario: proxyScenario,
259
+ recordOnMiss: proxyShouldRecordOnMiss,
260
+ recordResponses: proxyShouldRecordResponses,
261
+ }
216
262
  : undefined,
263
+ ...(proxyBaseUrl
264
+ ? {
265
+ strictScenarioResolution: mergedConfig.strictScenarioResolution ?? true,
266
+ }
267
+ : {}),
217
268
  ...mergedConfig,
269
+ initLog: {
270
+ headline: mergedConfig.initLog?.headline ??
271
+ `React Native production · ${mockDataArray.length} bundled mock(s)`,
272
+ },
218
273
  });
219
- mockifyer_core_2.logger.info(`[Mockifyer] Production mode: Loaded ${mockDataArray.length} mocks from bundle`);
220
274
  return { status: 'active', instance };
221
275
  }
222
276
  }
277
+ /**
278
+ * Preset: point the app at **mockifyer-dashboard** for `/api/proxy` (typically **`--provider redis`**).
279
+ *
280
+ * Resolves URL in order: **`proxyBaseUrl`** → **`dashboardBaseUrl`** → **`MOCKIFYER_PROXY_URL`** env.
281
+ * Then delegates to {@link setupMockifyerForReactNative}. For bespoke wiring, call that helper directly.
282
+ */
283
+ async function initMockifyerForReactNativeDashboard(options) {
284
+ const fromEnv = typeof process !== 'undefined' && process.env?.MOCKIFYER_PROXY_URL
285
+ ? process.env.MOCKIFYER_PROXY_URL.trim()
286
+ : '';
287
+ const resolved = String(options.proxyBaseUrl ?? '').trim() ||
288
+ String(options.dashboardBaseUrl ?? '').trim() ||
289
+ fromEnv;
290
+ if (!resolved) {
291
+ throw new Error('initMockifyerForReactNativeDashboard: set proxyBaseUrl, dashboardBaseUrl, or MOCKIFYER_PROXY_URL');
292
+ }
293
+ return setupMockifyerForReactNative({
294
+ ...options,
295
+ proxyBaseUrl: resolved,
296
+ });
297
+ }
223
298
  var mockifyer_core_3 = require("@sgedda/mockifyer-core");
224
299
  Object.defineProperty(exports, "tryGetClientIdFromLaunchArguments", { enumerable: true, get: function () { return mockifyer_core_3.tryGetClientIdFromLaunchArguments; } });
225
300
  Object.defineProperty(exports, "MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY", { enumerable: true, get: function () { return mockifyer_core_3.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY; } });
@@ -0,0 +1,19 @@
1
+ /** Body shape returned by mockifyer-dashboard `GET /api/health` (subset). */
2
+ export interface DashboardHealthPayload {
3
+ status?: string;
4
+ provider?: string;
5
+ redisOk?: boolean | null;
6
+ sqliteOk?: boolean | null;
7
+ /** When true, dashboard central store (redis or sqlite) is ready for `/api/proxy`. */
8
+ centralStoreOk?: boolean | null;
9
+ }
10
+ /**
11
+ * True when mockifyer-dashboard responds to **`GET /api/health`** with a healthy central store
12
+ * (**`provider === 'redis'`** and **`redisOk`**, or **`provider === 'sqlite'`** and **`sqliteOk`**,
13
+ * or **`centralStoreOk === true`**). Same gate as React Native strict proxy / **`initMockifyerForDashboardProxy`**.
14
+ */
15
+ export declare function canUseDashboardCentralProxy(proxyBaseUrl: string | undefined): Promise<boolean>;
16
+ /**
17
+ * @deprecated Use {@link canUseDashboardCentralProxy}. Kept for existing imports.
18
+ */
19
+ export declare function canUseDashboardRedisProxy(proxyBaseUrl: string | undefined): Promise<boolean>;
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.canUseDashboardCentralProxy = canUseDashboardCentralProxy;
4
+ exports.canUseDashboardRedisProxy = canUseDashboardRedisProxy;
5
+ const join_proxy_dashboard_api_url_1 = require("./join-proxy-dashboard-api-url");
6
+ const HEALTH_TIMEOUT_MS = 800;
7
+ function centralStoreHealthy(data) {
8
+ if (data.centralStoreOk === true) {
9
+ return true;
10
+ }
11
+ if (data.provider === 'redis' && data.redisOk === true) {
12
+ return true;
13
+ }
14
+ if (data.provider === 'sqlite' && data.sqliteOk === true) {
15
+ return true;
16
+ }
17
+ return false;
18
+ }
19
+ /**
20
+ * True when mockifyer-dashboard responds to **`GET /api/health`** with a healthy central store
21
+ * (**`provider === 'redis'`** and **`redisOk`**, or **`provider === 'sqlite'`** and **`sqliteOk`**,
22
+ * or **`centralStoreOk === true`**). Same gate as React Native strict proxy / **`initMockifyerForDashboardProxy`**.
23
+ */
24
+ async function canUseDashboardCentralProxy(proxyBaseUrl) {
25
+ if (!proxyBaseUrl?.trim()) {
26
+ return false;
27
+ }
28
+ try {
29
+ const controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined;
30
+ const timeout = setTimeout(() => controller?.abort(), HEALTH_TIMEOUT_MS);
31
+ const url = (0, join_proxy_dashboard_api_url_1.joinProxyDashboardApiUrl)(proxyBaseUrl.trim(), 'api/health');
32
+ const res = await fetch(url, { signal: controller?.signal });
33
+ clearTimeout(timeout);
34
+ if (!res.ok) {
35
+ return false;
36
+ }
37
+ const data = (await res.json());
38
+ return centralStoreHealthy(data);
39
+ }
40
+ catch {
41
+ return false;
42
+ }
43
+ }
44
+ /**
45
+ * @deprecated Use {@link canUseDashboardCentralProxy}. Kept for existing imports.
46
+ */
47
+ async function canUseDashboardRedisProxy(proxyBaseUrl) {
48
+ return canUseDashboardCentralProxy(proxyBaseUrl);
49
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sgedda/mockifyer-fetch",
3
- "version": "1.8.25",
3
+ "version": "1.8.32",
4
4
  "description": "Mockifyer for Fetch - API mocking and logging utility for storing and replaying API responses",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -49,15 +49,27 @@
49
49
  },
50
50
  "license": "MIT",
51
51
  "dependencies": {
52
- "@sgedda/mockifyer-core": "^1.8.30"
52
+ "@sgedda/mockifyer-core": "^1.9.0"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@types/node": "^20.11.24",
56
56
  "typescript": "^5.3.3"
57
57
  },
58
+ "peerDependencies": {
59
+ "react-native-launch-arguments": ">=4.0.0"
60
+ },
61
+ "peerDependenciesMeta": {
62
+ "react-native-launch-arguments": {
63
+ "optional": true
64
+ }
65
+ },
58
66
  "publishConfig": {
59
67
  "access": "public"
60
68
  },
69
+ "homepage": "https://mockifyer.dev",
70
+ "bugs": {
71
+ "url": "https://github.com/sgedda/mockifyer/issues"
72
+ },
61
73
  "repository": {
62
74
  "type": "git",
63
75
  "url": "git+https://github.com/sgedda/mockifyer.git"