@sgedda/mockifyer-fetch 1.8.19 → 1.8.22

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,8 @@
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");
6
+ const join_proxy_dashboard_api_url_1 = require("../utils/join-proxy-dashboard-api-url");
5
7
  class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
6
8
  constructor(config) {
7
9
  super();
@@ -55,13 +57,13 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
55
57
  }
56
58
  // Proxy mode (e.g. React Native → dashboard → Redis)
57
59
  if (this.proxyBaseUrl) {
58
- const proxyUrl = new URL('/api/proxy', this.proxyBaseUrl).toString();
60
+ const proxyUrl = (0, join_proxy_dashboard_api_url_1.joinProxyDashboardApiUrl)(this.proxyBaseUrl, 'api/proxy');
59
61
  const proxyResponse = await fetchFn(proxyUrl, {
60
62
  method: 'POST',
61
63
  headers: {
62
64
  'content-type': 'application/json',
63
- ...(this.clientId ? { 'x-mockifyer-client-id': this.clientId } : {}),
64
- ...(this.deviceId ? { 'x-mockifyer-device-id': this.deviceId } : {}),
65
+ ...(this.clientId ? { [mockifyer_core_2.MOCKIFYER_CLIENT_ID_HEADER]: this.clientId } : {}),
66
+ ...(this.deviceId ? { [mockifyer_core_2.MOCKIFYER_DEVICE_ID_HEADER]: this.deviceId } : {}),
65
67
  },
66
68
  body: JSON.stringify({
67
69
  url,
@@ -109,6 +111,12 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
109
111
  config,
110
112
  };
111
113
  }
114
+ if (this.clientId && String(this.clientId).trim() && !(0, mockifyer_core_2.getOutboundMockifyerClientIdHeader)(headers)) {
115
+ headers.set(mockifyer_core_2.MOCKIFYER_CLIENT_ID_HEADER, String(this.clientId).trim());
116
+ }
117
+ if (this.deviceId && String(this.deviceId).trim() && !(0, mockifyer_core_2.getOutboundMockifyerDeviceIdHeader)(headers)) {
118
+ headers.set(mockifyer_core_2.MOCKIFYER_DEVICE_ID_HEADER, String(this.deviceId).trim());
119
+ }
112
120
  const response = await fetchFn(url, requestConfig);
113
121
  const contentType = response.headers.get('content-type') || '';
114
122
  const rawText = await response.text();
package/dist/index.js CHANGED
@@ -98,6 +98,10 @@ class MockifyerClass {
98
98
  this.config.clientId = (0, mockifyer_core_1.resolveClientId)(this.config);
99
99
  }
100
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
+ }
101
105
  // Initialize test generator if test generation is enabled
102
106
  if (config.generateTests?.enabled) {
103
107
  this.testGenerator = new mockifyer_core_1.TestGenerator();
@@ -347,6 +351,12 @@ class MockifyerClass {
347
351
  config.__mockifyer_bypass = true;
348
352
  return config;
349
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
+ }
350
360
  // Normalize empty params: treat {} the same as undefined for consistent matching
351
361
  const rawParams = config.params || {};
352
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;
@@ -35,10 +62,17 @@ export interface ReactNativeMockifyerConfig {
35
62
  * When true, read `clientId` from Maestro/native launch arguments (optional peer `react-native-launch-arguments`).
36
63
  * Prefer this over passing scenario from E2E if the dashboard/Redis should control scenario on the fly for that lane.
37
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).
38
67
  */
39
68
  useLaunchArgumentsClientId?: boolean;
40
69
  /** Launch-argument key for the client lane id (default: `mockifyerClientId`). */
41
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;
42
76
  }
43
77
  /**
44
78
  * Setup Mockifyer for React Native/Expo with automatic conditional provider selection
@@ -50,13 +84,15 @@ export interface ReactNativeMockifyerConfig {
50
84
  * ```typescript
51
85
  * import { setupMockifyerForReactNative } from '@sgedda/mockifyer-fetch/react-native';
52
86
  *
53
- * await setupMockifyerForReactNative({
54
- * 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
55
90
  * mockDataPath: 'mock-data',
56
91
  * bundledDataPath: './assets/mock-data',
57
92
  * recordMode: process.env.MOCKIFYER_RECORD === 'true',
58
93
  * });
94
+ * // result.status: 'not_activated' | 'active' | 'failed_no_bundled_mocks'
59
95
  * ```
60
96
  */
61
- export declare function setupMockifyerForReactNative(options: ReactNativeMockifyerConfig): Promise<MockifyerInstance | null>;
97
+ export declare function setupMockifyerForReactNative(options: ReactNativeMockifyerConfig): Promise<SetupMockifyerForReactNativeResult>;
62
98
  export { tryGetClientIdFromLaunchArguments, MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY } from '@sgedda/mockifyer-core';
@@ -7,10 +7,18 @@
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY = exports.tryGetClientIdFromLaunchArguments = void 0;
10
+ exports.isMockifyerReactNativeActive = isMockifyerReactNativeActive;
10
11
  exports.setupMockifyerForReactNative = setupMockifyerForReactNative;
12
+ const join_proxy_dashboard_api_url_1 = require("./utils/join-proxy-dashboard-api-url");
11
13
  const index_1 = require("./index");
12
14
  const mockifyer_core_1 = require("@sgedda/mockifyer-core");
13
15
  const mockifyer_core_2 = require("@sgedda/mockifyer-core");
16
+ /**
17
+ * Type guard: `true` when {@link setupMockifyerForReactNative} patched `fetch` and returned an instance.
18
+ */
19
+ function isMockifyerReactNativeActive(result) {
20
+ return result.status === 'active';
21
+ }
14
22
  // Lazy load bundled data (only used in production builds)
15
23
  let bundledMockData = null;
16
24
  async function canUseStrictRedisProxy(proxyBaseUrl) {
@@ -19,7 +27,7 @@ async function canUseStrictRedisProxy(proxyBaseUrl) {
19
27
  try {
20
28
  const controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined;
21
29
  const timeout = setTimeout(() => controller?.abort(), 800);
22
- const url = new URL('/api/health', proxyBaseUrl).toString();
30
+ const url = (0, join_proxy_dashboard_api_url_1.joinProxyDashboardApiUrl)(proxyBaseUrl, 'api/health');
23
31
  const res = await fetch(url, { signal: controller?.signal });
24
32
  clearTimeout(timeout);
25
33
  if (!res.ok)
@@ -74,31 +82,48 @@ async function loadBundledMockData(bundledDataPath) {
74
82
  * ```typescript
75
83
  * import { setupMockifyerForReactNative } from '@sgedda/mockifyer-fetch/react-native';
76
84
  *
77
- * await setupMockifyerForReactNative({
78
- * isDev: __DEV__, // Pass React Native's __DEV__ variable
85
+ * // MOCKIFYER_MODE=on | launch_client | off — default when unset is on; use launch_client for Maestro-only activation.
86
+ * const result = await setupMockifyerForReactNative({
87
+ * isDev: __DEV__, // Selects Hybrid vs Memory provider once enabled
79
88
  * mockDataPath: 'mock-data',
80
89
  * bundledDataPath: './assets/mock-data',
81
90
  * recordMode: process.env.MOCKIFYER_RECORD === 'true',
82
91
  * });
92
+ * // result.status: 'not_activated' | 'active' | 'failed_no_bundled_mocks'
83
93
  * ```
84
94
  */
85
95
  async function setupMockifyerForReactNative(options) {
86
- const { isDev, mockDataPath = 'mock-data', bundledDataPath = './assets/mock-data', recordMode = false, config = {}, proxyBaseUrl, proxyScenario, proxyRecordOnMiss, useLaunchArgumentsClientId = false, launchArgumentClientIdKey = mockifyer_core_2.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY, } = 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;
87
97
  const proxyShouldRecordOnMiss = proxyRecordOnMiss ?? recordMode;
98
+ const launchClientIdKey = launchArgumentClientIdKey ?? mockifyer_core_2.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY;
99
+ const clientIdFromLaunchArgs = (0, mockifyer_core_2.tryGetClientIdFromLaunchArguments)(launchClientIdKey);
100
+ const shouldApplyLaunchClientId = useLaunchArgumentsClientId || Boolean(clientIdFromLaunchArgs);
101
+ const resolvedRuntimeMode = (0, mockifyer_core_2.resolveMockifyerRuntimeMode)({
102
+ configMode: runtimeModeOption ?? userConfig.runtimeMode,
103
+ });
88
104
  const mergedConfig = {
89
- ...config,
90
- ...(useLaunchArgumentsClientId
105
+ ...userConfig,
106
+ runtimeMode: resolvedRuntimeMode,
107
+ ...(shouldApplyLaunchClientId
91
108
  ? {
92
109
  useLaunchArgumentsClientId: true,
93
- launchArgumentClientIdKey: launchArgumentClientIdKey ?? mockifyer_core_2.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
110
+ launchArgumentClientIdKey: launchClientIdKey,
94
111
  }
95
112
  : {}),
96
113
  };
97
- // Check if Mockifyer is enabled
98
- const isEnabled = process.env.MOCKIFYER_ENABLED === 'true' || isDev;
114
+ const isEnabled = resolvedRuntimeMode === 'on' ||
115
+ (resolvedRuntimeMode === 'launch_client' && Boolean(clientIdFromLaunchArgs));
99
116
  if (!isEnabled) {
100
- mockifyer_core_2.logger.info('[Mockifyer] Disabled');
101
- return null;
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})`);
123
+ return { status: 'not_activated', instance: null };
124
+ }
125
+ if (clientIdFromLaunchArgs && !useLaunchArgumentsClientId) {
126
+ mockifyer_core_2.logger.info(`[Mockifyer] Enabled via launch argument "${launchClientIdKey}" (E2E lane "${clientIdFromLaunchArgs}")`);
102
127
  }
103
128
  if (isDev === true) {
104
129
  const strictProxyEnabled = await canUseStrictRedisProxy(proxyBaseUrl);
@@ -162,7 +187,7 @@ async function setupMockifyerForReactNative(options) {
162
187
  mockifyer_core_2.logger.warn('[Mockifyer] Initial project→device sync failed (Metro running with built mockifyer-fetch?):', error);
163
188
  }
164
189
  }
165
- return instance;
190
+ return { status: 'active', instance };
166
191
  }
167
192
  else {
168
193
  // PRODUCTION BUILD MODE
@@ -172,8 +197,8 @@ async function setupMockifyerForReactNative(options) {
172
197
  // Load bundled mock data
173
198
  const mockDataArray = await loadBundledMockData(bundledDataPath);
174
199
  if (mockDataArray.length === 0) {
175
- mockifyer_core_2.logger.warn('[Mockifyer] No bundled mock data found. Make sure to run the build script first.');
176
- return null;
200
+ 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.');
201
+ return { status: 'failed_no_bundled_mocks', instance: null };
177
202
  }
178
203
  // Pre-load all mocks into memory
179
204
  for (const mockData of mockDataArray) {
@@ -192,7 +217,7 @@ async function setupMockifyerForReactNative(options) {
192
217
  ...mergedConfig,
193
218
  });
194
219
  mockifyer_core_2.logger.info(`[Mockifyer] Production mode: Loaded ${mockDataArray.length} mocks from bundle`);
195
- return instance;
220
+ return { status: 'active', instance };
196
221
  }
197
222
  }
198
223
  var mockifyer_core_3 = require("@sgedda/mockifyer-core");
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Builds a full URL to the Mockifyer dashboard HTTP API under a given `proxyBaseUrl`.
3
+ *
4
+ * `proxyBaseUrl` may include a path prefix (e.g. `https://host/apim-prefix/mockifyer/`).
5
+ * Avoid `new URL('/api/...', proxyBaseUrl)` — a leading `/` on the second argument replaces the
6
+ * entire pathname of the base URL, so the gateway prefix is lost.
7
+ *
8
+ * @param proxyBaseUrl - Origin and optional path prefix (with or without trailing slash)
9
+ * @param apiSubPath - Path under that prefix without a leading slash (e.g. `api/health`, `api/proxy`)
10
+ */
11
+ export declare function joinProxyDashboardApiUrl(proxyBaseUrl: string, apiSubPath: string): string;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.joinProxyDashboardApiUrl = joinProxyDashboardApiUrl;
4
+ /**
5
+ * Builds a full URL to the Mockifyer dashboard HTTP API under a given `proxyBaseUrl`.
6
+ *
7
+ * `proxyBaseUrl` may include a path prefix (e.g. `https://host/apim-prefix/mockifyer/`).
8
+ * Avoid `new URL('/api/...', proxyBaseUrl)` — a leading `/` on the second argument replaces the
9
+ * entire pathname of the base URL, so the gateway prefix is lost.
10
+ *
11
+ * @param proxyBaseUrl - Origin and optional path prefix (with or without trailing slash)
12
+ * @param apiSubPath - Path under that prefix without a leading slash (e.g. `api/health`, `api/proxy`)
13
+ */
14
+ function joinProxyDashboardApiUrl(proxyBaseUrl, apiSubPath) {
15
+ const normalizedBase = proxyBaseUrl.trim().replace(/\/+$/, '');
16
+ const normalizedPath = apiSubPath.trim().replace(/^\/+/, '');
17
+ return `${normalizedBase}/${normalizedPath}`;
18
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sgedda/mockifyer-fetch",
3
- "version": "1.8.19",
3
+ "version": "1.8.22",
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.24"
49
+ "@sgedda/mockifyer-core": "^1.8.27"
50
50
  },
51
51
  "devDependencies": {
52
52
  "@types/node": "^20.11.24",
@@ -1,5 +1,12 @@
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';
9
+ import { joinProxyDashboardApiUrl } from '../utils/join-proxy-dashboard-api-url';
3
10
 
4
11
  export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
5
12
  private baseUrl?: string;
@@ -74,13 +81,13 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
74
81
 
75
82
  // Proxy mode (e.g. React Native → dashboard → Redis)
76
83
  if (this.proxyBaseUrl) {
77
- const proxyUrl = new URL('/api/proxy', this.proxyBaseUrl).toString();
84
+ const proxyUrl = joinProxyDashboardApiUrl(this.proxyBaseUrl, 'api/proxy');
78
85
  const proxyResponse = await fetchFn(proxyUrl, {
79
86
  method: 'POST',
80
87
  headers: {
81
88
  'content-type': 'application/json',
82
- ...(this.clientId ? { 'x-mockifyer-client-id': this.clientId } : {}),
83
- ...(this.deviceId ? { 'x-mockifyer-device-id': this.deviceId } : {}),
89
+ ...(this.clientId ? { [MOCKIFYER_CLIENT_ID_HEADER]: this.clientId } : {}),
90
+ ...(this.deviceId ? { [MOCKIFYER_DEVICE_ID_HEADER]: this.deviceId } : {}),
84
91
  },
85
92
  body: JSON.stringify({
86
93
  url,
@@ -133,6 +140,13 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
133
140
  };
134
141
  }
135
142
 
143
+ if (this.clientId && String(this.clientId).trim() && !getOutboundMockifyerClientIdHeader(headers)) {
144
+ headers.set(MOCKIFYER_CLIENT_ID_HEADER, String(this.clientId).trim());
145
+ }
146
+ if (this.deviceId && String(this.deviceId).trim() && !getOutboundMockifyerDeviceIdHeader(headers)) {
147
+ headers.set(MOCKIFYER_DEVICE_ID_HEADER, String(this.deviceId).trim());
148
+ }
149
+
136
150
  const response = await fetchFn(url, requestConfig);
137
151
  const contentType = response.headers.get('content-type') || '';
138
152
  const rawText = await response.text();
package/src/index.ts CHANGED
@@ -39,7 +39,10 @@ import {
39
39
  mockPassesThroughToRealApi,
40
40
  resolveClientId,
41
41
  tryGetClientIdFromLaunchArguments,
42
- MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY
42
+ MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
43
+ resolveActivationMode,
44
+ shouldApplyMockifyer,
45
+ type MockifyerActivationMode,
43
46
  } from '@sgedda/mockifyer-core';
44
47
  import { logger, setLogLevel } from '@sgedda/mockifyer-core';
45
48
 
@@ -57,6 +60,7 @@ class MockifyerClass {
57
60
  private sessionStartTime: number = 0;
58
61
  private readonly SESSION_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
59
62
  private testGenerator?: TestGenerator;
63
+ private readonly activationMode: MockifyerActivationMode;
60
64
 
61
65
  constructor(config: MockifyerConfig) {
62
66
  // Validate database provider - filesystem, expo-filesystem, hybrid, and memory are supported
@@ -127,7 +131,12 @@ class MockifyerClass {
127
131
  this.config.clientId = resolveClientId(this.config);
128
132
  }
129
133
  logger.info(`[Mockifyer-Fetch] clientId: ${this.config.clientId}`);
130
-
134
+
135
+ this.activationMode = resolveActivationMode(this.config);
136
+ if (this.activationMode !== 'always') {
137
+ logger.info(`[Mockifyer-Fetch] activationMode: ${this.activationMode}`);
138
+ }
139
+
131
140
  // Initialize test generator if test generation is enabled
132
141
  if (config.generateTests?.enabled) {
133
142
  this.testGenerator = new TestGenerator();
@@ -416,7 +425,16 @@ class MockifyerClass {
416
425
  (config as any).__mockifyer_bypass = true;
417
426
  return config;
418
427
  }
419
-
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
+
420
438
  // Normalize empty params: treat {} the same as undefined for consistent matching
421
439
  const rawParams = config.params || {};
422
440
  const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
@@ -524,7 +542,7 @@ class MockifyerClass {
524
542
  if ((response.config as any).__mockifyer_skip_save || (response.config as any).__mockifyer_bypass) {
525
543
  return response;
526
544
  }
527
-
545
+
528
546
  // CRITICAL: Skip Mockifyer sync endpoints to prevent infinite loops
529
547
  // Check multiple ways to get the URL in case response.config is undefined
530
548
  const url = response.config?.url || response.request?.responseURL || response.url || (response as any).config?.url || '';
@@ -5,11 +5,15 @@
5
5
  * conditional provider selection (FileSystem in dev, Memory in prod)
6
6
  */
7
7
 
8
+ import { joinProxyDashboardApiUrl } from './utils/join-proxy-dashboard-api-url';
8
9
  import { setupMockifyer } from './index';
9
10
  import { MemoryProvider, ExpoFileSystemProvider, MockData, HTTPClient } from '@sgedda/mockifyer-core';
10
11
  import {
11
12
  logger,
12
13
  MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
14
+ tryGetClientIdFromLaunchArguments,
15
+ resolveMockifyerRuntimeMode,
16
+ type MockifyerRuntimeMode,
13
17
  } from '@sgedda/mockifyer-core';
14
18
 
15
19
  // Re-export MockifyerInstance type to avoid circular dependency
@@ -19,6 +23,33 @@ export interface MockifyerInstance extends HTTPClient {
19
23
  clearAllMocks: () => Promise<void>;
20
24
  }
21
25
 
26
+ /**
27
+ * Outcome of {@link setupMockifyerForReactNative}.
28
+ *
29
+ * - **`not_activated`** — `fetch` was not patched this run (see **`MOCKIFYER_MODE`** / `runtimeMode`: `off`, or `launch_client` without a launch-arg lane).
30
+ * Not the same as “permanently off” unless mode is **`off`** (then launch args do not activate).
31
+ * - **`active`** — Mockifyer initialized and patched `global.fetch`.
32
+ * - **`failed_no_bundled_mocks`** — Activation criteria were met and `isDev` was false, but bundled mock data was missing or empty.
33
+ */
34
+ export type MockifyerReactNativeInitStatus =
35
+ | 'not_activated'
36
+ | 'active'
37
+ | 'failed_no_bundled_mocks';
38
+
39
+ export type SetupMockifyerForReactNativeResult =
40
+ | { readonly status: 'not_activated'; readonly instance: null }
41
+ | { readonly status: 'failed_no_bundled_mocks'; readonly instance: null }
42
+ | { readonly status: 'active'; readonly instance: MockifyerInstance };
43
+
44
+ /**
45
+ * Type guard: `true` when {@link setupMockifyerForReactNative} patched `fetch` and returned an instance.
46
+ */
47
+ export function isMockifyerReactNativeActive(
48
+ result: SetupMockifyerForReactNativeResult
49
+ ): result is { readonly status: 'active'; readonly instance: MockifyerInstance } {
50
+ return result.status === 'active';
51
+ }
52
+
22
53
  export interface ReactNativeMockifyerConfig {
23
54
  /** Whether we're in development mode (determines which provider to use) */
24
55
  isDev: boolean;
@@ -43,10 +74,17 @@ export interface ReactNativeMockifyerConfig {
43
74
  * When true, read `clientId` from Maestro/native launch arguments (optional peer `react-native-launch-arguments`).
44
75
  * Prefer this over passing scenario from E2E if the dashboard/Redis should control scenario on the fly for that lane.
45
76
  * Forwards to {@link MockifyerConfig.useLaunchArgumentsClientId} on the merged config passed to `setupMockifyer`.
77
+ *
78
+ * 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).
46
79
  */
47
80
  useLaunchArgumentsClientId?: boolean;
48
81
  /** Launch-argument key for the client lane id (default: `mockifyerClientId`). */
49
82
  launchArgumentClientIdKey?: string;
83
+ /**
84
+ * When Mockifyer may patch `fetch` at startup. Overrides **`MOCKIFYER_MODE`** env and `config.runtimeMode`.
85
+ * Prefer env **`MOCKIFYER_MODE`**: `off` | `on` | `launch_client` (aliases e.g. `e2e`, `maestro` → `launch_client`).
86
+ */
87
+ runtimeMode?: MockifyerRuntimeMode;
50
88
  }
51
89
 
52
90
  type DashboardHealth = {
@@ -63,7 +101,7 @@ async function canUseStrictRedisProxy(proxyBaseUrl?: string): Promise<boolean> {
63
101
  try {
64
102
  const controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined;
65
103
  const timeout = setTimeout(() => controller?.abort(), 800);
66
- const url = new URL('/api/health', proxyBaseUrl).toString();
104
+ const url = joinProxyDashboardApiUrl(proxyBaseUrl, 'api/health');
67
105
  const res = await fetch(url, { signal: controller?.signal });
68
106
  clearTimeout(timeout);
69
107
  if (!res.ok) return false;
@@ -119,49 +157,75 @@ async function loadBundledMockData(bundledDataPath: string): Promise<MockData[]>
119
157
  * @example
120
158
  * ```typescript
121
159
  * import { setupMockifyerForReactNative } from '@sgedda/mockifyer-fetch/react-native';
122
- *
123
- * await setupMockifyerForReactNative({
124
- * isDev: __DEV__, // Pass React Native's __DEV__ variable
160
+ *
161
+ * // MOCKIFYER_MODE=on | launch_client | off — default when unset is on; use launch_client for Maestro-only activation.
162
+ * const result = await setupMockifyerForReactNative({
163
+ * isDev: __DEV__, // Selects Hybrid vs Memory provider once enabled
125
164
  * mockDataPath: 'mock-data',
126
165
  * bundledDataPath: './assets/mock-data',
127
166
  * recordMode: process.env.MOCKIFYER_RECORD === 'true',
128
167
  * });
168
+ * // result.status: 'not_activated' | 'active' | 'failed_no_bundled_mocks'
129
169
  * ```
130
170
  */
131
171
  export async function setupMockifyerForReactNative(
132
172
  options: ReactNativeMockifyerConfig
133
- ): Promise<MockifyerInstance | null> {
173
+ ): Promise<SetupMockifyerForReactNativeResult> {
134
174
  const {
135
175
  isDev,
136
176
  mockDataPath = 'mock-data',
137
177
  bundledDataPath = './assets/mock-data',
138
178
  recordMode = false,
139
- config = {},
179
+ config: userConfig = {},
140
180
  proxyBaseUrl,
141
181
  proxyScenario,
142
182
  proxyRecordOnMiss,
143
183
  useLaunchArgumentsClientId = false,
144
184
  launchArgumentClientIdKey = MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
185
+ runtimeMode: runtimeModeOption,
145
186
  } = options;
146
187
 
147
188
  const proxyShouldRecordOnMiss = proxyRecordOnMiss ?? recordMode;
148
189
 
149
- const mergedConfig: typeof config = {
150
- ...config,
151
- ...(useLaunchArgumentsClientId
190
+ const launchClientIdKey =
191
+ launchArgumentClientIdKey ?? MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY;
192
+ const clientIdFromLaunchArgs = tryGetClientIdFromLaunchArguments(launchClientIdKey);
193
+ const shouldApplyLaunchClientId =
194
+ useLaunchArgumentsClientId || Boolean(clientIdFromLaunchArgs);
195
+
196
+ const resolvedRuntimeMode = resolveMockifyerRuntimeMode({
197
+ configMode: runtimeModeOption ?? userConfig.runtimeMode,
198
+ });
199
+
200
+ const mergedConfig: typeof userConfig = {
201
+ ...userConfig,
202
+ runtimeMode: resolvedRuntimeMode,
203
+ ...(shouldApplyLaunchClientId
152
204
  ? {
153
205
  useLaunchArgumentsClientId: true as const,
154
- launchArgumentClientIdKey:
155
- launchArgumentClientIdKey ?? MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
206
+ launchArgumentClientIdKey: launchClientIdKey,
156
207
  }
157
208
  : {}),
158
209
  };
159
210
 
160
- // Check if Mockifyer is enabled
161
- const isEnabled = process.env.MOCKIFYER_ENABLED === 'true' || isDev;
211
+ const isEnabled =
212
+ resolvedRuntimeMode === 'on' ||
213
+ (resolvedRuntimeMode === 'launch_client' && Boolean(clientIdFromLaunchArgs));
162
214
  if (!isEnabled) {
163
- logger.info('[Mockifyer] Disabled');
164
- return null;
215
+ const hint =
216
+ resolvedRuntimeMode === 'off'
217
+ ? 'MOCKIFYER_MODE=off (or runtimeMode off) — launch args are ignored.'
218
+ : resolvedRuntimeMode === 'launch_client'
219
+ ? 'MOCKIFYER_MODE=launch_client — pass mockifyerClientId via launch args, or set MOCKIFYER_MODE=on for always-on dev.'
220
+ : 'Adjust MOCKIFYER_MODE / runtimeMode.';
221
+ logger.info(`[Mockifyer] Not activated (${hint})`);
222
+ return { status: 'not_activated', instance: null } as const;
223
+ }
224
+
225
+ if (clientIdFromLaunchArgs && !useLaunchArgumentsClientId) {
226
+ logger.info(
227
+ `[Mockifyer] Enabled via launch argument "${launchClientIdKey}" (E2E lane "${clientIdFromLaunchArgs}")`
228
+ );
165
229
  }
166
230
 
167
231
  if (isDev === true) {
@@ -233,7 +297,7 @@ export async function setupMockifyerForReactNative(
233
297
  }
234
298
  }
235
299
 
236
- return instance;
300
+ return { status: 'active', instance } as const;
237
301
  } else {
238
302
  // PRODUCTION BUILD MODE
239
303
  // Use Memory provider with bundled TypeScript file
@@ -244,8 +308,10 @@ export async function setupMockifyerForReactNative(
244
308
  const mockDataArray = await loadBundledMockData(bundledDataPath);
245
309
 
246
310
  if (mockDataArray.length === 0) {
247
- logger.warn('[Mockifyer] No bundled mock data found. Make sure to run the build script first.');
248
- return null;
311
+ logger.warn(
312
+ '[Mockifyer] Activation requested but no bundled mock data found (status: failed_no_bundled_mocks). Run the bundle/generate step for your mocks.'
313
+ );
314
+ return { status: 'failed_no_bundled_mocks', instance: null } as const;
249
315
  }
250
316
 
251
317
  // Pre-load all mocks into memory
@@ -267,7 +333,7 @@ export async function setupMockifyerForReactNative(
267
333
  });
268
334
 
269
335
  logger.info(`[Mockifyer] Production mode: Loaded ${mockDataArray.length} mocks from bundle`);
270
- return instance;
336
+ return { status: 'active', instance } as const;
271
337
  }
272
338
  }
273
339
 
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Builds a full URL to the Mockifyer dashboard HTTP API under a given `proxyBaseUrl`.
3
+ *
4
+ * `proxyBaseUrl` may include a path prefix (e.g. `https://host/apim-prefix/mockifyer/`).
5
+ * Avoid `new URL('/api/...', proxyBaseUrl)` — a leading `/` on the second argument replaces the
6
+ * entire pathname of the base URL, so the gateway prefix is lost.
7
+ *
8
+ * @param proxyBaseUrl - Origin and optional path prefix (with or without trailing slash)
9
+ * @param apiSubPath - Path under that prefix without a leading slash (e.g. `api/health`, `api/proxy`)
10
+ */
11
+ export function joinProxyDashboardApiUrl(proxyBaseUrl: string, apiSubPath: string): string {
12
+ const normalizedBase = proxyBaseUrl.trim().replace(/\/+$/, '');
13
+ const normalizedPath = apiSubPath.trim().replace(/^\/+/, '');
14
+ return `${normalizedBase}/${normalizedPath}`;
15
+ }