@sgedda/mockifyer-fetch 1.8.18 → 1.8.21

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.
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FetchHTTPClient = void 0;
4
4
  const mockifyer_core_1 = require("@sgedda/mockifyer-core");
5
+ const mockifyer_core_2 = require("@sgedda/mockifyer-core");
5
6
  class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
6
7
  constructor(config) {
7
8
  super();
@@ -60,8 +61,8 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
60
61
  method: 'POST',
61
62
  headers: {
62
63
  'content-type': 'application/json',
63
- ...(this.clientId ? { 'x-mockifyer-client-id': this.clientId } : {}),
64
- ...(this.deviceId ? { 'x-mockifyer-device-id': this.deviceId } : {}),
64
+ ...(this.clientId ? { [mockifyer_core_2.MOCKIFYER_CLIENT_ID_HEADER]: this.clientId } : {}),
65
+ ...(this.deviceId ? { [mockifyer_core_2.MOCKIFYER_DEVICE_ID_HEADER]: this.deviceId } : {}),
65
66
  },
66
67
  body: JSON.stringify({
67
68
  url,
@@ -109,6 +110,12 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
109
110
  config,
110
111
  };
111
112
  }
113
+ if (this.clientId && String(this.clientId).trim() && !(0, mockifyer_core_2.getOutboundMockifyerClientIdHeader)(headers)) {
114
+ headers.set(mockifyer_core_2.MOCKIFYER_CLIENT_ID_HEADER, String(this.clientId).trim());
115
+ }
116
+ if (this.deviceId && String(this.deviceId).trim() && !(0, mockifyer_core_2.getOutboundMockifyerDeviceIdHeader)(headers)) {
117
+ headers.set(mockifyer_core_2.MOCKIFYER_DEVICE_ID_HEADER, String(this.deviceId).trim());
118
+ }
112
119
  const response = await fetchFn(url, requestConfig);
113
120
  const contentType = response.headers.get('content-type') || '';
114
121
  const rawText = await response.text();
package/dist/index.js CHANGED
@@ -80,11 +80,28 @@ class MockifyerClass {
80
80
  config.useSimilarMatch = true;
81
81
  }
82
82
  }
83
+ let launchClientId;
84
+ if (config.useLaunchArgumentsClientId) {
85
+ const key = config.launchArgumentClientIdKey ?? mockifyer_core_1.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY;
86
+ launchClientId = (0, mockifyer_core_1.tryGetClientIdFromLaunchArguments)(key);
87
+ if (launchClientId) {
88
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] clientId from launch arguments (${key}): ${launchClientId}`);
89
+ }
90
+ }
83
91
  // Store config BEFORE any modifications
84
92
  this.config = { ...config }; // Create a copy to avoid mutations
85
- // Resolve client lane id (env/config/fallback); used for Redis per-client scenario overrides and proxy headers.
86
- this.config.clientId = (0, mockifyer_core_1.resolveClientId)(this.config);
93
+ // Launch arg wins over MOCKIFYER_CLIENT_ID / config.clientId when present (E2E).
94
+ if (launchClientId) {
95
+ this.config.clientId = launchClientId;
96
+ }
97
+ else {
98
+ this.config.clientId = (0, mockifyer_core_1.resolveClientId)(this.config);
99
+ }
87
100
  mockifyer_core_2.logger.info(`[Mockifyer-Fetch] clientId: ${this.config.clientId}`);
101
+ this.activationMode = (0, mockifyer_core_1.resolveActivationMode)(this.config);
102
+ if (this.activationMode !== 'always') {
103
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] activationMode: ${this.activationMode}`);
104
+ }
88
105
  // Initialize test generator if test generation is enabled
89
106
  if (config.generateTests?.enabled) {
90
107
  this.testGenerator = new mockifyer_core_1.TestGenerator();
@@ -334,6 +351,12 @@ class MockifyerClass {
334
351
  config.__mockifyer_bypass = true;
335
352
  return config;
336
353
  }
354
+ if (!(0, mockifyer_core_1.shouldApplyMockifyer)(this.activationMode, config.headers, {
355
+ useProxyLane: { proxyBaseUrl: this.config.proxy?.baseUrl, resolvedClientId: this.config.clientId },
356
+ })) {
357
+ config.__mockifyer_bypass = true;
358
+ return config;
359
+ }
337
360
  // Normalize empty params: treat {} the same as undefined for consistent matching
338
361
  const rawParams = config.params || {};
339
362
  const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
@@ -6,11 +6,38 @@
6
6
  */
7
7
  import { setupMockifyer } from './index';
8
8
  import { HTTPClient } from '@sgedda/mockifyer-core';
9
+ import { type MockifyerRuntimeMode } from '@sgedda/mockifyer-core';
9
10
  export interface MockifyerInstance extends HTTPClient {
10
11
  reloadMockData: (syncFromProject?: boolean) => Promise<void>;
11
12
  clearStaleCacheEntries: () => number;
12
13
  clearAllMocks: () => Promise<void>;
13
14
  }
15
+ /**
16
+ * Outcome of {@link setupMockifyerForReactNative}.
17
+ *
18
+ * - **`not_activated`** — `fetch` was not patched this run (see **`MOCKIFYER_MODE`** / `runtimeMode`: `off`, or `launch_client` without a launch-arg lane).
19
+ * Not the same as “permanently off” unless mode is **`off`** (then launch args do not activate).
20
+ * - **`active`** — Mockifyer initialized and patched `global.fetch`.
21
+ * - **`failed_no_bundled_mocks`** — Activation criteria were met and `isDev` was false, but bundled mock data was missing or empty.
22
+ */
23
+ export type MockifyerReactNativeInitStatus = 'not_activated' | 'active' | 'failed_no_bundled_mocks';
24
+ export type SetupMockifyerForReactNativeResult = {
25
+ readonly status: 'not_activated';
26
+ readonly instance: null;
27
+ } | {
28
+ readonly status: 'failed_no_bundled_mocks';
29
+ readonly instance: null;
30
+ } | {
31
+ readonly status: 'active';
32
+ readonly instance: MockifyerInstance;
33
+ };
34
+ /**
35
+ * Type guard: `true` when {@link setupMockifyerForReactNative} patched `fetch` and returned an instance.
36
+ */
37
+ export declare function isMockifyerReactNativeActive(result: SetupMockifyerForReactNativeResult): result is {
38
+ readonly status: 'active';
39
+ readonly instance: MockifyerInstance;
40
+ };
14
41
  export interface ReactNativeMockifyerConfig {
15
42
  /** Whether we're in development mode (determines which provider to use) */
16
43
  isDev: boolean;
@@ -31,6 +58,21 @@ export interface ReactNativeMockifyerConfig {
31
58
  * Deprecated: prefer using `recordMode` when `proxyBaseUrl` is provided.
32
59
  */
33
60
  proxyRecordOnMiss?: boolean;
61
+ /**
62
+ * When true, read `clientId` from Maestro/native launch arguments (optional peer `react-native-launch-arguments`).
63
+ * Prefer this over passing scenario from E2E if the dashboard/Redis should control scenario on the fly for that lane.
64
+ * Forwards to {@link MockifyerConfig.useLaunchArgumentsClientId} on the merged config passed to `setupMockifyer`.
65
+ *
66
+ * If the launch argument is **set** (non-empty) for {@link launchArgumentClientIdKey}, the lane id is applied when Mockifyer activates (see **`runtimeMode`** / **`MOCKIFYER_MODE`**; with **`launch_client`**, a set arg is required to activate).
67
+ */
68
+ useLaunchArgumentsClientId?: boolean;
69
+ /** Launch-argument key for the client lane id (default: `mockifyerClientId`). */
70
+ launchArgumentClientIdKey?: string;
71
+ /**
72
+ * When Mockifyer may patch `fetch` at startup. Overrides **`MOCKIFYER_MODE`** env and `config.runtimeMode`.
73
+ * Prefer env **`MOCKIFYER_MODE`**: `off` | `on` | `launch_client` (aliases e.g. `e2e`, `maestro` → `launch_client`).
74
+ */
75
+ runtimeMode?: MockifyerRuntimeMode;
34
76
  }
35
77
  /**
36
78
  * Setup Mockifyer for React Native/Expo with automatic conditional provider selection
@@ -42,12 +84,15 @@ export interface ReactNativeMockifyerConfig {
42
84
  * ```typescript
43
85
  * import { setupMockifyerForReactNative } from '@sgedda/mockifyer-fetch/react-native';
44
86
  *
45
- * await setupMockifyerForReactNative({
46
- * isDev: __DEV__, // Pass React Native's __DEV__ variable
87
+ * // MOCKIFYER_MODE=on | launch_client | off — default when unset is on; use launch_client for Maestro-only activation.
88
+ * const result = await setupMockifyerForReactNative({
89
+ * isDev: __DEV__, // Selects Hybrid vs Memory provider once enabled
47
90
  * mockDataPath: 'mock-data',
48
91
  * bundledDataPath: './assets/mock-data',
49
92
  * recordMode: process.env.MOCKIFYER_RECORD === 'true',
50
93
  * });
94
+ * // result.status: 'not_activated' | 'active' | 'failed_no_bundled_mocks'
51
95
  * ```
52
96
  */
53
- export declare function setupMockifyerForReactNative(options: ReactNativeMockifyerConfig): Promise<MockifyerInstance | null>;
97
+ export declare function setupMockifyerForReactNative(options: ReactNativeMockifyerConfig): Promise<SetupMockifyerForReactNativeResult>;
98
+ export { tryGetClientIdFromLaunchArguments, MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY } from '@sgedda/mockifyer-core';
@@ -6,10 +6,18 @@
6
6
  * conditional provider selection (FileSystem in dev, Memory in prod)
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY = exports.tryGetClientIdFromLaunchArguments = void 0;
10
+ exports.isMockifyerReactNativeActive = isMockifyerReactNativeActive;
9
11
  exports.setupMockifyerForReactNative = setupMockifyerForReactNative;
10
12
  const index_1 = require("./index");
11
13
  const mockifyer_core_1 = require("@sgedda/mockifyer-core");
12
14
  const mockifyer_core_2 = require("@sgedda/mockifyer-core");
15
+ /**
16
+ * Type guard: `true` when {@link setupMockifyerForReactNative} patched `fetch` and returned an instance.
17
+ */
18
+ function isMockifyerReactNativeActive(result) {
19
+ return result.status === 'active';
20
+ }
13
21
  // Lazy load bundled data (only used in production builds)
14
22
  let bundledMockData = null;
15
23
  async function canUseStrictRedisProxy(proxyBaseUrl) {
@@ -73,22 +81,48 @@ async function loadBundledMockData(bundledDataPath) {
73
81
  * ```typescript
74
82
  * import { setupMockifyerForReactNative } from '@sgedda/mockifyer-fetch/react-native';
75
83
  *
76
- * await setupMockifyerForReactNative({
77
- * isDev: __DEV__, // Pass React Native's __DEV__ variable
84
+ * // MOCKIFYER_MODE=on | launch_client | off — default when unset is on; use launch_client for Maestro-only activation.
85
+ * const result = await setupMockifyerForReactNative({
86
+ * isDev: __DEV__, // Selects Hybrid vs Memory provider once enabled
78
87
  * mockDataPath: 'mock-data',
79
88
  * bundledDataPath: './assets/mock-data',
80
89
  * recordMode: process.env.MOCKIFYER_RECORD === 'true',
81
90
  * });
91
+ * // result.status: 'not_activated' | 'active' | 'failed_no_bundled_mocks'
82
92
  * ```
83
93
  */
84
94
  async function setupMockifyerForReactNative(options) {
85
- const { isDev, mockDataPath = 'mock-data', bundledDataPath = './assets/mock-data', recordMode = false, config = {}, proxyBaseUrl, proxyScenario, proxyRecordOnMiss, } = options;
95
+ 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;
86
96
  const proxyShouldRecordOnMiss = proxyRecordOnMiss ?? recordMode;
87
- // Check if Mockifyer is enabled
88
- const isEnabled = process.env.MOCKIFYER_ENABLED === 'true' || isDev;
97
+ const launchClientIdKey = launchArgumentClientIdKey ?? mockifyer_core_2.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY;
98
+ const clientIdFromLaunchArgs = (0, mockifyer_core_2.tryGetClientIdFromLaunchArguments)(launchClientIdKey);
99
+ const shouldApplyLaunchClientId = useLaunchArgumentsClientId || Boolean(clientIdFromLaunchArgs);
100
+ const resolvedRuntimeMode = (0, mockifyer_core_2.resolveMockifyerRuntimeMode)({
101
+ configMode: runtimeModeOption ?? userConfig.runtimeMode,
102
+ });
103
+ const mergedConfig = {
104
+ ...userConfig,
105
+ runtimeMode: resolvedRuntimeMode,
106
+ ...(shouldApplyLaunchClientId
107
+ ? {
108
+ useLaunchArgumentsClientId: true,
109
+ launchArgumentClientIdKey: launchClientIdKey,
110
+ }
111
+ : {}),
112
+ };
113
+ const isEnabled = resolvedRuntimeMode === 'on' ||
114
+ (resolvedRuntimeMode === 'launch_client' && Boolean(clientIdFromLaunchArgs));
89
115
  if (!isEnabled) {
90
- mockifyer_core_2.logger.info('[Mockifyer] Disabled');
91
- return null;
116
+ const hint = resolvedRuntimeMode === 'off'
117
+ ? 'MOCKIFYER_MODE=off (or runtimeMode off) — launch args are ignored.'
118
+ : resolvedRuntimeMode === 'launch_client'
119
+ ? 'MOCKIFYER_MODE=launch_client — pass mockifyerClientId via launch args, or set MOCKIFYER_MODE=on for always-on dev.'
120
+ : 'Adjust MOCKIFYER_MODE / runtimeMode.';
121
+ mockifyer_core_2.logger.info(`[Mockifyer] Not activated (${hint})`);
122
+ return { status: 'not_activated', instance: null };
123
+ }
124
+ if (clientIdFromLaunchArgs && !useLaunchArgumentsClientId) {
125
+ mockifyer_core_2.logger.info(`[Mockifyer] Enabled via launch argument "${launchClientIdKey}" (E2E lane "${clientIdFromLaunchArgs}")`);
92
126
  }
93
127
  if (isDev === true) {
94
128
  const strictProxyEnabled = await canUseStrictRedisProxy(proxyBaseUrl);
@@ -106,13 +140,13 @@ async function setupMockifyerForReactNative(options) {
106
140
  },
107
141
  };
108
142
  // Merge with config.databaseProvider if provided
109
- const databaseProviderConfig = config.databaseProvider
143
+ const databaseProviderConfig = mergedConfig.databaseProvider
110
144
  ? {
111
145
  ...baseDatabaseProvider,
112
- ...config.databaseProvider,
146
+ ...mergedConfig.databaseProvider,
113
147
  options: {
114
148
  ...baseDatabaseProvider.options,
115
- ...(config.databaseProvider.options || {}),
149
+ ...(mergedConfig.databaseProvider.options || {}),
116
150
  metroPort, // Always ensure metroPort is set
117
151
  },
118
152
  }
@@ -130,7 +164,7 @@ async function setupMockifyerForReactNative(options) {
130
164
  proxy: strictProxyEnabled && proxyBaseUrl
131
165
  ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyShouldRecordOnMiss }
132
166
  : undefined,
133
- ...config,
167
+ ...mergedConfig,
134
168
  });
135
169
  if (strictProxyEnabled) {
136
170
  mockifyer_core_2.logger.info('[Mockifyer] Development mode: Strict proxy enabled (dashboard Redis is healthy) — local mocks disabled');
@@ -152,7 +186,7 @@ async function setupMockifyerForReactNative(options) {
152
186
  mockifyer_core_2.logger.warn('[Mockifyer] Initial project→device sync failed (Metro running with built mockifyer-fetch?):', error);
153
187
  }
154
188
  }
155
- return instance;
189
+ return { status: 'active', instance };
156
190
  }
157
191
  else {
158
192
  // PRODUCTION BUILD MODE
@@ -162,8 +196,8 @@ async function setupMockifyerForReactNative(options) {
162
196
  // Load bundled mock data
163
197
  const mockDataArray = await loadBundledMockData(bundledDataPath);
164
198
  if (mockDataArray.length === 0) {
165
- mockifyer_core_2.logger.warn('[Mockifyer] No bundled mock data found. Make sure to run the build script first.');
166
- return null;
199
+ mockifyer_core_2.logger.warn('[Mockifyer] Activation requested but no bundled mock data found (status: failed_no_bundled_mocks). Run the bundle/generate step for your mocks.');
200
+ return { status: 'failed_no_bundled_mocks', instance: null };
167
201
  }
168
202
  // Pre-load all mocks into memory
169
203
  for (const mockData of mockDataArray) {
@@ -179,9 +213,12 @@ async function setupMockifyerForReactNative(options) {
179
213
  proxy: proxyBaseUrl
180
214
  ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyShouldRecordOnMiss }
181
215
  : undefined,
182
- ...config,
216
+ ...mergedConfig,
183
217
  });
184
218
  mockifyer_core_2.logger.info(`[Mockifyer] Production mode: Loaded ${mockDataArray.length} mocks from bundle`);
185
- return instance;
219
+ return { status: 'active', instance };
186
220
  }
187
221
  }
222
+ var mockifyer_core_3 = require("@sgedda/mockifyer-core");
223
+ Object.defineProperty(exports, "tryGetClientIdFromLaunchArguments", { enumerable: true, get: function () { return mockifyer_core_3.tryGetClientIdFromLaunchArguments; } });
224
+ Object.defineProperty(exports, "MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY", { enumerable: true, get: function () { return mockifyer_core_3.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sgedda/mockifyer-fetch",
3
- "version": "1.8.18",
3
+ "version": "1.8.21",
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",
@@ -46,7 +46,7 @@
46
46
  "author": "sgedda",
47
47
  "license": "MIT",
48
48
  "dependencies": {
49
- "@sgedda/mockifyer-core": "^1.8.23"
49
+ "@sgedda/mockifyer-core": "^1.8.26"
50
50
  },
51
51
  "devDependencies": {
52
52
  "@types/node": "^20.11.24",
@@ -1,5 +1,11 @@
1
1
  import { BaseHTTPClient } from '@sgedda/mockifyer-core';
2
2
  import { HTTPRequestConfig, HTTPResponse } from '@sgedda/mockifyer-core';
3
+ import {
4
+ getOutboundMockifyerClientIdHeader,
5
+ getOutboundMockifyerDeviceIdHeader,
6
+ MOCKIFYER_CLIENT_ID_HEADER,
7
+ MOCKIFYER_DEVICE_ID_HEADER,
8
+ } from '@sgedda/mockifyer-core';
3
9
 
4
10
  export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
5
11
  private baseUrl?: string;
@@ -79,8 +85,8 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
79
85
  method: 'POST',
80
86
  headers: {
81
87
  'content-type': 'application/json',
82
- ...(this.clientId ? { 'x-mockifyer-client-id': this.clientId } : {}),
83
- ...(this.deviceId ? { 'x-mockifyer-device-id': this.deviceId } : {}),
88
+ ...(this.clientId ? { [MOCKIFYER_CLIENT_ID_HEADER]: this.clientId } : {}),
89
+ ...(this.deviceId ? { [MOCKIFYER_DEVICE_ID_HEADER]: this.deviceId } : {}),
84
90
  },
85
91
  body: JSON.stringify({
86
92
  url,
@@ -133,6 +139,13 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
133
139
  };
134
140
  }
135
141
 
142
+ if (this.clientId && String(this.clientId).trim() && !getOutboundMockifyerClientIdHeader(headers)) {
143
+ headers.set(MOCKIFYER_CLIENT_ID_HEADER, String(this.clientId).trim());
144
+ }
145
+ if (this.deviceId && String(this.deviceId).trim() && !getOutboundMockifyerDeviceIdHeader(headers)) {
146
+ headers.set(MOCKIFYER_DEVICE_ID_HEADER, String(this.deviceId).trim());
147
+ }
148
+
136
149
  const response = await fetchFn(url, requestConfig);
137
150
  const contentType = response.headers.get('content-type') || '';
138
151
  const rawText = await response.text();
package/src/index.ts CHANGED
@@ -37,7 +37,12 @@ import {
37
37
  getCurrentDate,
38
38
  shouldExcludeUrl,
39
39
  mockPassesThroughToRealApi,
40
- resolveClientId
40
+ resolveClientId,
41
+ tryGetClientIdFromLaunchArguments,
42
+ MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
43
+ resolveActivationMode,
44
+ shouldApplyMockifyer,
45
+ type MockifyerActivationMode,
41
46
  } from '@sgedda/mockifyer-core';
42
47
  import { logger, setLogLevel } from '@sgedda/mockifyer-core';
43
48
 
@@ -55,6 +60,7 @@ class MockifyerClass {
55
60
  private sessionStartTime: number = 0;
56
61
  private readonly SESSION_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
57
62
  private testGenerator?: TestGenerator;
63
+ private readonly activationMode: MockifyerActivationMode;
58
64
 
59
65
  constructor(config: MockifyerConfig) {
60
66
  // Validate database provider - filesystem, expo-filesystem, hybrid, and memory are supported
@@ -106,13 +112,31 @@ class MockifyerClass {
106
112
  }
107
113
  }
108
114
 
115
+ let launchClientId: string | undefined;
116
+ if (config.useLaunchArgumentsClientId) {
117
+ const key = config.launchArgumentClientIdKey ?? MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY;
118
+ launchClientId = tryGetClientIdFromLaunchArguments(key);
119
+ if (launchClientId) {
120
+ logger.info(`[Mockifyer-Fetch] clientId from launch arguments (${key}): ${launchClientId}`);
121
+ }
122
+ }
123
+
109
124
  // Store config BEFORE any modifications
110
125
  this.config = { ...config }; // Create a copy to avoid mutations
111
126
 
112
- // Resolve client lane id (env/config/fallback); used for Redis per-client scenario overrides and proxy headers.
113
- this.config.clientId = resolveClientId(this.config);
127
+ // Launch arg wins over MOCKIFYER_CLIENT_ID / config.clientId when present (E2E).
128
+ if (launchClientId) {
129
+ this.config.clientId = launchClientId;
130
+ } else {
131
+ this.config.clientId = resolveClientId(this.config);
132
+ }
114
133
  logger.info(`[Mockifyer-Fetch] clientId: ${this.config.clientId}`);
115
-
134
+
135
+ this.activationMode = resolveActivationMode(this.config);
136
+ if (this.activationMode !== 'always') {
137
+ logger.info(`[Mockifyer-Fetch] activationMode: ${this.activationMode}`);
138
+ }
139
+
116
140
  // Initialize test generator if test generation is enabled
117
141
  if (config.generateTests?.enabled) {
118
142
  this.testGenerator = new TestGenerator();
@@ -401,7 +425,16 @@ class MockifyerClass {
401
425
  (config as any).__mockifyer_bypass = true;
402
426
  return config;
403
427
  }
404
-
428
+
429
+ if (
430
+ !shouldApplyMockifyer(this.activationMode, config.headers, {
431
+ useProxyLane: { proxyBaseUrl: this.config.proxy?.baseUrl, resolvedClientId: this.config.clientId },
432
+ })
433
+ ) {
434
+ (config as any).__mockifyer_bypass = true;
435
+ return config;
436
+ }
437
+
405
438
  // Normalize empty params: treat {} the same as undefined for consistent matching
406
439
  const rawParams = config.params || {};
407
440
  const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
@@ -509,7 +542,7 @@ class MockifyerClass {
509
542
  if ((response.config as any).__mockifyer_skip_save || (response.config as any).__mockifyer_bypass) {
510
543
  return response;
511
544
  }
512
-
545
+
513
546
  // CRITICAL: Skip Mockifyer sync endpoints to prevent infinite loops
514
547
  // Check multiple ways to get the URL in case response.config is undefined
515
548
  const url = response.config?.url || response.request?.responseURL || response.url || (response as any).config?.url || '';
@@ -7,8 +7,13 @@
7
7
 
8
8
  import { setupMockifyer } from './index';
9
9
  import { MemoryProvider, ExpoFileSystemProvider, MockData, HTTPClient } from '@sgedda/mockifyer-core';
10
- import type { MockifyerConfig } from '@sgedda/mockifyer-core';
11
- import { logger } from '@sgedda/mockifyer-core';
10
+ import {
11
+ logger,
12
+ MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
13
+ tryGetClientIdFromLaunchArguments,
14
+ resolveMockifyerRuntimeMode,
15
+ type MockifyerRuntimeMode,
16
+ } from '@sgedda/mockifyer-core';
12
17
 
13
18
  // Re-export MockifyerInstance type to avoid circular dependency
14
19
  export interface MockifyerInstance extends HTTPClient {
@@ -17,6 +22,33 @@ export interface MockifyerInstance extends HTTPClient {
17
22
  clearAllMocks: () => Promise<void>;
18
23
  }
19
24
 
25
+ /**
26
+ * Outcome of {@link setupMockifyerForReactNative}.
27
+ *
28
+ * - **`not_activated`** — `fetch` was not patched this run (see **`MOCKIFYER_MODE`** / `runtimeMode`: `off`, or `launch_client` without a launch-arg lane).
29
+ * Not the same as “permanently off” unless mode is **`off`** (then launch args do not activate).
30
+ * - **`active`** — Mockifyer initialized and patched `global.fetch`.
31
+ * - **`failed_no_bundled_mocks`** — Activation criteria were met and `isDev` was false, but bundled mock data was missing or empty.
32
+ */
33
+ export type MockifyerReactNativeInitStatus =
34
+ | 'not_activated'
35
+ | 'active'
36
+ | 'failed_no_bundled_mocks';
37
+
38
+ export type SetupMockifyerForReactNativeResult =
39
+ | { readonly status: 'not_activated'; readonly instance: null }
40
+ | { readonly status: 'failed_no_bundled_mocks'; readonly instance: null }
41
+ | { readonly status: 'active'; readonly instance: MockifyerInstance };
42
+
43
+ /**
44
+ * Type guard: `true` when {@link setupMockifyerForReactNative} patched `fetch` and returned an instance.
45
+ */
46
+ export function isMockifyerReactNativeActive(
47
+ result: SetupMockifyerForReactNativeResult
48
+ ): result is { readonly status: 'active'; readonly instance: MockifyerInstance } {
49
+ return result.status === 'active';
50
+ }
51
+
20
52
  export interface ReactNativeMockifyerConfig {
21
53
  /** Whether we're in development mode (determines which provider to use) */
22
54
  isDev: boolean;
@@ -37,6 +69,21 @@ export interface ReactNativeMockifyerConfig {
37
69
  * Deprecated: prefer using `recordMode` when `proxyBaseUrl` is provided.
38
70
  */
39
71
  proxyRecordOnMiss?: boolean;
72
+ /**
73
+ * When true, read `clientId` from Maestro/native launch arguments (optional peer `react-native-launch-arguments`).
74
+ * Prefer this over passing scenario from E2E if the dashboard/Redis should control scenario on the fly for that lane.
75
+ * Forwards to {@link MockifyerConfig.useLaunchArgumentsClientId} on the merged config passed to `setupMockifyer`.
76
+ *
77
+ * If the launch argument is **set** (non-empty) for {@link launchArgumentClientIdKey}, the lane id is applied when Mockifyer activates (see **`runtimeMode`** / **`MOCKIFYER_MODE`**; with **`launch_client`**, a set arg is required to activate).
78
+ */
79
+ useLaunchArgumentsClientId?: boolean;
80
+ /** Launch-argument key for the client lane id (default: `mockifyerClientId`). */
81
+ launchArgumentClientIdKey?: string;
82
+ /**
83
+ * When Mockifyer may patch `fetch` at startup. Overrides **`MOCKIFYER_MODE`** env and `config.runtimeMode`.
84
+ * Prefer env **`MOCKIFYER_MODE`**: `off` | `on` | `launch_client` (aliases e.g. `e2e`, `maestro` → `launch_client`).
85
+ */
86
+ runtimeMode?: MockifyerRuntimeMode;
40
87
  }
41
88
 
42
89
  type DashboardHealth = {
@@ -109,36 +156,75 @@ async function loadBundledMockData(bundledDataPath: string): Promise<MockData[]>
109
156
  * @example
110
157
  * ```typescript
111
158
  * import { setupMockifyerForReactNative } from '@sgedda/mockifyer-fetch/react-native';
112
- *
113
- * await setupMockifyerForReactNative({
114
- * isDev: __DEV__, // Pass React Native's __DEV__ variable
159
+ *
160
+ * // MOCKIFYER_MODE=on | launch_client | off — default when unset is on; use launch_client for Maestro-only activation.
161
+ * const result = await setupMockifyerForReactNative({
162
+ * isDev: __DEV__, // Selects Hybrid vs Memory provider once enabled
115
163
  * mockDataPath: 'mock-data',
116
164
  * bundledDataPath: './assets/mock-data',
117
165
  * recordMode: process.env.MOCKIFYER_RECORD === 'true',
118
166
  * });
167
+ * // result.status: 'not_activated' | 'active' | 'failed_no_bundled_mocks'
119
168
  * ```
120
169
  */
121
170
  export async function setupMockifyerForReactNative(
122
171
  options: ReactNativeMockifyerConfig
123
- ): Promise<MockifyerInstance | null> {
172
+ ): Promise<SetupMockifyerForReactNativeResult> {
124
173
  const {
125
174
  isDev,
126
175
  mockDataPath = 'mock-data',
127
176
  bundledDataPath = './assets/mock-data',
128
177
  recordMode = false,
129
- config = {},
178
+ config: userConfig = {},
130
179
  proxyBaseUrl,
131
180
  proxyScenario,
132
181
  proxyRecordOnMiss,
182
+ useLaunchArgumentsClientId = false,
183
+ launchArgumentClientIdKey = MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
184
+ runtimeMode: runtimeModeOption,
133
185
  } = options;
134
186
 
135
187
  const proxyShouldRecordOnMiss = proxyRecordOnMiss ?? recordMode;
136
188
 
137
- // Check if Mockifyer is enabled
138
- const isEnabled = process.env.MOCKIFYER_ENABLED === 'true' || isDev;
189
+ const launchClientIdKey =
190
+ launchArgumentClientIdKey ?? MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY;
191
+ const clientIdFromLaunchArgs = tryGetClientIdFromLaunchArguments(launchClientIdKey);
192
+ const shouldApplyLaunchClientId =
193
+ useLaunchArgumentsClientId || Boolean(clientIdFromLaunchArgs);
194
+
195
+ const resolvedRuntimeMode = resolveMockifyerRuntimeMode({
196
+ configMode: runtimeModeOption ?? userConfig.runtimeMode,
197
+ });
198
+
199
+ const mergedConfig: typeof userConfig = {
200
+ ...userConfig,
201
+ runtimeMode: resolvedRuntimeMode,
202
+ ...(shouldApplyLaunchClientId
203
+ ? {
204
+ useLaunchArgumentsClientId: true as const,
205
+ launchArgumentClientIdKey: launchClientIdKey,
206
+ }
207
+ : {}),
208
+ };
209
+
210
+ const isEnabled =
211
+ resolvedRuntimeMode === 'on' ||
212
+ (resolvedRuntimeMode === 'launch_client' && Boolean(clientIdFromLaunchArgs));
139
213
  if (!isEnabled) {
140
- logger.info('[Mockifyer] Disabled');
141
- return null;
214
+ const hint =
215
+ resolvedRuntimeMode === 'off'
216
+ ? 'MOCKIFYER_MODE=off (or runtimeMode off) — launch args are ignored.'
217
+ : resolvedRuntimeMode === 'launch_client'
218
+ ? 'MOCKIFYER_MODE=launch_client — pass mockifyerClientId via launch args, or set MOCKIFYER_MODE=on for always-on dev.'
219
+ : 'Adjust MOCKIFYER_MODE / runtimeMode.';
220
+ logger.info(`[Mockifyer] Not activated (${hint})`);
221
+ return { status: 'not_activated', instance: null } as const;
222
+ }
223
+
224
+ if (clientIdFromLaunchArgs && !useLaunchArgumentsClientId) {
225
+ logger.info(
226
+ `[Mockifyer] Enabled via launch argument "${launchClientIdKey}" (E2E lane "${clientIdFromLaunchArgs}")`
227
+ );
142
228
  }
143
229
 
144
230
  if (isDev === true) {
@@ -160,13 +246,13 @@ export async function setupMockifyerForReactNative(
160
246
  };
161
247
 
162
248
  // Merge with config.databaseProvider if provided
163
- const databaseProviderConfig = config.databaseProvider
249
+ const databaseProviderConfig = mergedConfig.databaseProvider
164
250
  ? {
165
251
  ...baseDatabaseProvider,
166
- ...config.databaseProvider,
252
+ ...mergedConfig.databaseProvider,
167
253
  options: {
168
254
  ...baseDatabaseProvider.options,
169
- ...(config.databaseProvider.options || {}),
255
+ ...(mergedConfig.databaseProvider.options || {}),
170
256
  metroPort, // Always ensure metroPort is set
171
257
  },
172
258
  }
@@ -185,7 +271,7 @@ export async function setupMockifyerForReactNative(
185
271
  proxy: strictProxyEnabled && proxyBaseUrl
186
272
  ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyShouldRecordOnMiss }
187
273
  : undefined,
188
- ...config,
274
+ ...mergedConfig,
189
275
  });
190
276
 
191
277
  if (strictProxyEnabled) {
@@ -210,7 +296,7 @@ export async function setupMockifyerForReactNative(
210
296
  }
211
297
  }
212
298
 
213
- return instance;
299
+ return { status: 'active', instance } as const;
214
300
  } else {
215
301
  // PRODUCTION BUILD MODE
216
302
  // Use Memory provider with bundled TypeScript file
@@ -221,8 +307,10 @@ export async function setupMockifyerForReactNative(
221
307
  const mockDataArray = await loadBundledMockData(bundledDataPath);
222
308
 
223
309
  if (mockDataArray.length === 0) {
224
- logger.warn('[Mockifyer] No bundled mock data found. Make sure to run the build script first.');
225
- return null;
310
+ logger.warn(
311
+ '[Mockifyer] Activation requested but no bundled mock data found (status: failed_no_bundled_mocks). Run the bundle/generate step for your mocks.'
312
+ );
313
+ return { status: 'failed_no_bundled_mocks', instance: null } as const;
226
314
  }
227
315
 
228
316
  // Pre-load all mocks into memory
@@ -240,11 +328,13 @@ export async function setupMockifyerForReactNative(
240
328
  proxy: proxyBaseUrl
241
329
  ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyShouldRecordOnMiss }
242
330
  : undefined,
243
- ...config,
331
+ ...mergedConfig,
244
332
  });
245
333
 
246
334
  logger.info(`[Mockifyer] Production mode: Loaded ${mockDataArray.length} mocks from bundle`);
247
- return instance;
335
+ return { status: 'active', instance } as const;
248
336
  }
249
337
  }
250
338
 
339
+ export { tryGetClientIdFromLaunchArguments, MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY } from '@sgedda/mockifyer-core';
340
+