@sgedda/mockifyer-fetch 1.8.32 → 1.8.33

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,27 +2,6 @@
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 join_proxy_dashboard_api_url_1 = require("../utils/join-proxy-dashboard-api-url");
6
- function buildProxyEnvelope(params) {
7
- const { url, method, lane, deviceId, requestId, parentRequestId, headers, body, scenario, recordOnMiss, recordResponses, strictLaneScenario, } = params;
8
- const envelope = {
9
- url,
10
- method,
11
- clientId: lane,
12
- deviceId,
13
- requestId,
14
- parentRequestId,
15
- headers,
16
- body,
17
- scenario,
18
- recordResponses,
19
- strictLaneScenario,
20
- };
21
- if (typeof recordOnMiss === 'boolean') {
22
- envelope.record = recordOnMiss;
23
- }
24
- return envelope;
25
- }
26
5
  class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
27
6
  constructor(config) {
28
7
  super();
@@ -93,7 +72,6 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
93
72
  body: config.data ? JSON.stringify(config.data) : undefined
94
73
  };
95
74
  // Use original fetch if available (when global fetch is patched), otherwise use global fetch
96
- // CRITICAL: Always use _originalFetch if available to prevent infinite loops
97
75
  const fetchFn = this._originalFetch || fetch;
98
76
  if (!this._originalFetch) {
99
77
  console.warn('[FetchHTTPClient] _originalFetch not set! This may cause infinite loops if global fetch is patched.');
@@ -103,80 +81,29 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
103
81
  const hopRequestId = config.__mockifyer_requestId;
104
82
  const hopParentRequestId = config.__mockifyer_parentRequestId;
105
83
  const explicitProxyContext = this.getExplicitProxyScenarioContext?.() ?? true;
106
- // Proxy mode (e.g. React Native → dashboard → Redis)
107
84
  if (this.proxyBaseUrl && !bypassMockifyer && explicitProxyContext) {
108
- const proxyUrl = (0, join_proxy_dashboard_api_url_1.joinProxyDashboardApiUrl)(this.proxyBaseUrl, 'api/proxy');
109
- const proxyResponse = await fetchFn(proxyUrl, {
110
- method: 'POST',
111
- headers: {
112
- 'content-type': 'application/json',
113
- ...(lane ? { [mockifyer_core_1.MOCKIFYER_CLIENT_ID_HEADER]: lane } : {}),
114
- ...(this.deviceId ? { [mockifyer_core_1.MOCKIFYER_DEVICE_ID_HEADER]: this.deviceId } : {}),
115
- ...(hopRequestId ? { [mockifyer_core_1.MOCKIFYER_REQUEST_ID_HEADER]: hopRequestId } : {}),
116
- ...(hopParentRequestId ? { [mockifyer_core_1.MOCKIFYER_PARENT_REQUEST_ID_HEADER]: hopParentRequestId } : {}),
117
- },
118
- body: JSON.stringify(buildProxyEnvelope({
119
- url,
120
- method: String(requestConfig.method || 'GET'),
121
- lane,
122
- deviceId: this.deviceId,
123
- requestId: hopRequestId,
124
- parentRequestId: hopParentRequestId,
125
- headers: (() => {
126
- const out = {};
127
- headers.forEach((value, key) => {
128
- out[key] = value;
129
- });
130
- return out;
131
- })(),
132
- body: config.data ?? null,
133
- scenario: this.proxyScenario,
134
- recordOnMiss: this.proxyRecordOnMiss,
135
- recordResponses: this.proxyRecordResponses,
136
- strictLaneScenario: this.getStrictLaneScenario?.() ?? true,
137
- })),
85
+ const headerRecord = {};
86
+ headers.forEach((value, key) => {
87
+ headerRecord[key] = value;
138
88
  });
139
- if (!proxyResponse.ok) {
140
- const txt = await proxyResponse.text();
141
- throw new Error(`[FetchHTTPClient] Proxy error: ${proxyResponse.status} ${txt}`);
142
- }
143
- const payload = await proxyResponse.json();
144
- try {
145
- const source = String(payload?.source || '');
146
- const hash = typeof payload?.hash === 'string' ? payload.hash : '';
147
- if (source) {
148
- const hashShort = hash ? `${hash.slice(0, 8)}…` : '';
149
- const laneLabel = lane ? lane : '—';
150
- const kind = source === 'redis' ? 'mock hit' : 'upstream';
151
- mockifyer_core_1.logger.debug(`[Mockifyer-Fetch] Proxy ${kind}: ${requestConfig.method} ${url} ${hashShort ? `(hash=${hashShort}) ` : ''}(lane=${laneLabel})`);
152
- }
153
- }
154
- catch {
155
- // ignore logging failures
156
- }
157
- const data = payload?.response?.data;
158
- const status = payload?.response?.status ?? 200;
159
- const responseHeaders = payload?.response?.headers ?? {};
160
- const scenarioResolution = payload?.scenarioResolution;
161
- const scenarioName = typeof scenarioResolution?.scenario === 'string' && scenarioResolution.scenario.trim()
162
- ? scenarioResolution.scenario.trim()
163
- : undefined;
164
- const mockifyerProxyRecording = payload?.recordedToStore === true && payload?.storedMock
165
- ? {
166
- recordedToStore: true,
167
- storedMock: payload.storedMock,
168
- hash: typeof payload.hash === 'string' ? payload.hash : undefined,
169
- scenarioName,
170
- }
171
- : undefined;
172
- return {
173
- data,
174
- status,
175
- statusText: String(status),
176
- headers: responseHeaders,
89
+ return (0, mockifyer_core_1.performDashboardProxyRequest)({
90
+ proxyBaseUrl: this.proxyBaseUrl,
91
+ url,
92
+ method: String(requestConfig.method || 'GET'),
93
+ headers: headerRecord,
94
+ body: config.data ?? null,
95
+ lane,
96
+ deviceId: this.deviceId,
97
+ requestId: hopRequestId,
98
+ parentRequestId: hopParentRequestId,
99
+ scenario: this.proxyScenario,
100
+ recordOnMiss: this.proxyRecordOnMiss,
101
+ recordResponses: this.proxyRecordResponses,
102
+ strictLaneScenario: this.getStrictLaneScenario?.() ?? true,
177
103
  config,
178
- mockifyerProxyRecording,
179
- };
104
+ fetchFn,
105
+ logTag: 'Mockifyer-Fetch',
106
+ });
180
107
  }
181
108
  if (!bypassMockifyer && lane && !(0, mockifyer_core_1.getOutboundMockifyerClientIdHeader)(headers)) {
182
109
  headers.set(mockifyer_core_1.MOCKIFYER_CLIENT_ID_HEADER, lane);
@@ -199,7 +126,6 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
199
126
  data = rawText;
200
127
  }
201
128
  }
202
- // Convert response Headers to Record<string, string>
203
129
  const responseHeaders = {};
204
130
  response.headers.forEach((value, key) => {
205
131
  responseHeaders[key] = value;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { MockifyerConfig, HTTPClient } from '@sgedda/mockifyer-core';
1
+ import { MockifyerConfig, HTTPClient, type InitMockifyerForDashboardProxyOptions, type InitMockifyerForLocalFilesystemOptions } from '@sgedda/mockifyer-core';
2
2
  export interface MockifyerInstance extends HTTPClient {
3
3
  reloadMockData: (syncFromProject?: boolean) => Promise<void>;
4
4
  clearStaleCacheEntries: () => number;
@@ -7,61 +7,14 @@ export interface MockifyerInstance extends HTTPClient {
7
7
  getClientId: () => string | undefined;
8
8
  }
9
9
  export declare function setupMockifyer(config: MockifyerConfig): MockifyerInstance;
10
- /** Options for {@link initMockifyerForDashboardProxy} — dashboard + `/api/proxy` (run `mockifyer-dashboard --provider redis`). */
11
- export interface InitMockifyerForDashboardProxyOptions {
12
- /** mockifyer-dashboard origin (e.g. `http://localhost:3002`). Not the Redis URL. */
13
- dashboardBaseUrl: string;
14
- /** Mock root for scenario file fallbacks etc. Defaults `MOCKIFYER_PATH` env or `./mock-data`. */
15
- mockDataPath?: string;
16
- /** Client lane id (`X-Mockifyer-Client-Id` / proxy envelope). Defaults `MOCKIFYER_CLIENT_ID` env. */
17
- clientId?: string;
18
- deviceId?: string;
19
- scenario?: string;
20
- /**
21
- * When **`true`**, each `/api/proxy` request sends **`"record": true`**. When **`false`**, sends **`"record": false`**.
22
- * When **omitted**, the **`record`** field is omitted so the **dashboard per-scenario** toggle applies; **`MOCKIFYER_PROXY_RECORD_ON_MISS`**
23
- * and **`MOCKIFYER_RECORD=true`** (last) still set an explicit client flag when you want env-driven recording without code.
24
- */
25
- recordOnMiss?: boolean;
26
- /**
27
- * When false, dashboard proxy stores request-only stubs on cache miss.
28
- * Defaults via {@link resolveRecordResponses} (`MOCKIFYER_RECORD_RESPONSES` env, else `false`).
29
- */
30
- recordResponses?: boolean;
31
- strictLaneScenario?: boolean;
32
- useGlobalFetch?: boolean;
33
- /** Use a local provider for mock hits before the proxy (default in-memory only) when **`/api/proxy`** is active. */
34
- databaseProvider?: MockifyerConfig['databaseProvider'];
35
- /** Additional `MockifyerConfig` fields — applied first, then preset fields win on `mockDataPath`, `proxy`, etc. */
36
- config?: Partial<MockifyerConfig>;
37
- /**
38
- * When **`true`**, skips **`GET …/api/health`** and always sets **`proxy`**.
39
- * Default **`false`**: if Redis is not healthy (or unreachable), omit **`proxy`** and use filesystem mocks + **`recordMode`** disk saves — aligns with **`setupMockifyerForReactNative`** dev fallback.
40
- */
41
- skipDashboardRedisHealthCheck?: boolean;
42
- /**
43
- * When the proxy records a response to Redis, also write the same mock under `mockDataPath` on this machine
44
- * (or via Metro when using strict RN + in-memory). Env: `MOCKIFYER_PROXY_MIRROR_TO_CLIENT`.
45
- */
46
- mirrorRecordedMocksToClient?: boolean;
47
- }
10
+ export type { InitMockifyerForDashboardProxyOptions, InitMockifyerForLocalFilesystemOptions };
48
11
  /**
49
- * Preset: **`GET /api/health`** must report Redis ready before **`proxy`** is set; otherwise filesystem mocks without proxy (like RN Hybrid fallback vs strict proxy).
50
- * Run **`mockifyer-dashboard --provider redis`** for the dashboard hop; use **`skipDashboardRedisHealthCheck`** to bypass the probe.
51
- *
12
+ * Preset: dashboard central store proxy when health check passes; otherwise filesystem mocks.
52
13
  * For full control, use {@link setupMockifyer} directly.
53
14
  */
54
15
  export declare function initMockifyerForDashboardProxy(options: InitMockifyerForDashboardProxyOptions): Promise<MockifyerInstance>;
55
- export interface InitMockifyerForLocalFilesystemOptions {
56
- mockDataPath?: string;
57
- useGlobalFetch?: boolean;
58
- recordMode?: boolean;
59
- /** Applied first; preset fills `mockDataPath` / `useGlobalFetch` when omitted. */
60
- config?: Partial<MockifyerConfig>;
61
- }
62
16
  /**
63
- * Preset: local **filesystem** mocks under {@link InitMockifyerForLocalFilesystemOptions.mockDataPath}
64
- * (default `./mock-data` or `MOCKIFYER_PATH`). No dashboard proxy.
17
+ * Preset: local filesystem mocks. No dashboard proxy.
65
18
  */
66
19
  export declare function initMockifyerForLocalFilesystem(options?: InitMockifyerForLocalFilesystemOptions): MockifyerInstance;
67
20
  /** Shared with {@link setupMockifyerForReactNative} strict-proxy branching. */
package/dist/index.js CHANGED
@@ -36,31 +36,6 @@ catch (e) {
36
36
  const mockifyer_core_1 = require("@sgedda/mockifyer-core");
37
37
  const mockifyer_core_2 = require("@sgedda/mockifyer-core");
38
38
  const fetch_client_1 = require("./clients/fetch-client");
39
- const dashboard_redis_health_1 = require("./utils/dashboard-redis-health");
40
- /**
41
- * When `proxy.baseUrl` is set and `proxy.recordOnMiss` is omitted, apply `MOCKIFYER_PROXY_RECORD_ON_MISS` if set.
42
- */
43
- function applyProxyRecordOnMissEnv(config) {
44
- const proxy = config.proxy;
45
- const baseUrl = proxy?.baseUrl?.trim();
46
- if (!proxy || !baseUrl || proxy.recordOnMiss !== undefined) {
47
- return config;
48
- }
49
- const parsed = (0, mockifyer_core_1.parseProxyRecordOnMissEnv)();
50
- if (parsed === undefined) {
51
- return config;
52
- }
53
- return {
54
- ...config,
55
- proxy: {
56
- baseUrl: proxy.baseUrl,
57
- scenario: proxy.scenario,
58
- recordOnMiss: parsed,
59
- strictLaneScenario: proxy.strictLaneScenario,
60
- mirrorRecordedMocksToClient: proxy.mirrorRecordedMocksToClient,
61
- },
62
- };
63
- }
64
39
  class MockifyerClass {
65
40
  /** Best-effort dashboard network log (skipped when traffic goes through `proxy.baseUrl`). */
66
41
  logNetworkEvent(partial, correlation) {
@@ -694,55 +669,22 @@ class MockifyerClass {
694
669
  }
695
670
  const hash = rec.hash?.trim();
696
671
  const scenarioName = rec.scenarioName?.trim();
697
- if (!hash || !scenarioName) {
698
- mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Proxy client mirror skipped: missing hash or scenario from proxy');
699
- return;
700
- }
701
672
  const mockData = rec.storedMock;
702
- const url = mockData?.request?.url || '';
703
- if ((0, mockifyer_core_1.shouldExcludeUrl)(url, this.config.excludedUrls)) {
704
- return;
705
- }
706
- const recExclusions = (0, mockifyer_core_1.resolveRecordingExclusions)(this.config);
707
- if ((0, mockifyer_core_1.shouldExcludeRecording)(url, recExclusions, this.config.baseUrl)) {
708
- return;
709
- }
710
- await this.databaseProviderInitPromise;
711
673
  const providerType = this.config.databaseProvider?.type;
712
- if (this.databaseProvider && providerType !== 'memory') {
713
- try {
714
- const out = this.databaseProvider.save(mockData, {
715
- relativePath: `redis/${hash}.json`,
716
- scenario: scenarioName,
717
- });
718
- if (out instanceof Promise) {
719
- await out;
720
- }
721
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (${providerType}): ${scenarioName}/redis/${hash}.json`);
722
- if (providerType === 'hybrid') {
723
- await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
724
- }
725
- }
726
- catch (e) {
727
- mockifyer_core_2.logger.error('[Mockifyer-Fetch] Proxy client mirror (provider) failed:', e);
728
- }
729
- return;
674
+ await (0, mockifyer_core_1.mirrorProxyRecordingToClient)({
675
+ config: this.config,
676
+ mockDataPath: this.config.mockDataPath,
677
+ recording: rec,
678
+ databaseProvider: this.databaseProvider,
679
+ databaseProviderInitPromise: this.databaseProviderInitPromise,
680
+ logPrefix: 'Mockifyer-Fetch',
681
+ });
682
+ if (providerType === 'hybrid' && hash && scenarioName && mockData) {
683
+ await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
730
684
  }
731
- if (fs && path) {
732
- try {
733
- (0, mockifyer_core_1.ensureScenarioFolder)(this.config.mockDataPath, scenarioName);
734
- const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(this.config.mockDataPath, scenarioName);
735
- const filePath = path.join(scenarioPath, 'redis', `${hash}.json`);
736
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
737
- fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
738
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (filesystem): ${scenarioName}/redis/${hash}.json`);
739
- }
740
- catch (e) {
741
- mockifyer_core_2.logger.error('[Mockifyer-Fetch] Proxy client mirror (Node fs) failed:', e);
742
- }
743
- return;
685
+ else if (!fs && hash && scenarioName && mockData) {
686
+ await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
744
687
  }
745
- await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
746
688
  }
747
689
  async tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash) {
748
690
  const metroPort = process.env.METRO_PORT ? parseInt(process.env.METRO_PORT, 10) : 8081;
@@ -1172,7 +1114,7 @@ function setupMockifyer(config) {
1172
1114
  if (typeof mockifyer_core_1.installNodeInboundRequestCorrelationCapture === 'function') {
1173
1115
  (0, mockifyer_core_1.installNodeInboundRequestCorrelationCapture)();
1174
1116
  }
1175
- const resolvedConfig = applyProxyRecordOnMissEnv(config);
1117
+ const resolvedConfig = (0, mockifyer_core_1.applyProxyRecordOnMissEnv)(config);
1176
1118
  // Initialize logger with config level (default to 'info' if not specified)
1177
1119
  (0, mockifyer_core_2.setLogLevel)(resolvedConfig.logging || 'info');
1178
1120
  // Set environment variables for Metro middleware to read test generation config
@@ -1317,134 +1259,23 @@ function setupMockifyer(config) {
1317
1259
  (0, mockifyer_core_1.registerMockifyerInstance)(extendedClient);
1318
1260
  return extendedClient;
1319
1261
  }
1320
- /** Drops `proxy` when merging partial config so filesystem fallback cannot accidentally keep proxy. */
1321
- function omitProxyFromPartialConfig(config) {
1322
- const { proxy: _drop, ...rest } = config;
1323
- void _drop;
1324
- return rest;
1325
- }
1326
1262
  /**
1327
- * Preset: **`GET /api/health`** must report Redis ready before **`proxy`** is set; otherwise filesystem mocks without proxy (like RN Hybrid fallback vs strict proxy).
1328
- * Run **`mockifyer-dashboard --provider redis`** for the dashboard hop; use **`skipDashboardRedisHealthCheck`** to bypass the probe.
1329
- *
1263
+ * Preset: dashboard central store proxy when health check passes; otherwise filesystem mocks.
1330
1264
  * For full control, use {@link setupMockifyer} directly.
1331
1265
  */
1332
1266
  async function initMockifyerForDashboardProxy(options) {
1333
- const extra = options.config ?? {};
1334
- const dashboardBaseUrl = String(options.dashboardBaseUrl).trim();
1335
- if (!dashboardBaseUrl) {
1336
- throw new Error('initMockifyerForDashboardProxy: dashboardBaseUrl is required');
1337
- }
1338
- const mockDataPath = options.mockDataPath ??
1339
- extra.mockDataPath ??
1340
- (typeof process !== 'undefined' && process.env?.MOCKIFYER_PATH
1341
- ? process.env.MOCKIFYER_PATH
1342
- : './mock-data');
1343
- const envRecord = typeof process !== 'undefined' && process.env?.MOCKIFYER_RECORD === 'true';
1344
- const recordOnMiss = options.recordOnMiss ??
1345
- extra.proxy?.recordOnMiss ??
1346
- (0, mockifyer_core_1.parseProxyRecordOnMissEnv)() ??
1347
- (envRecord ? true : undefined);
1348
- const recordResponses = (0, mockifyer_core_1.resolveRecordResponses)(options.recordResponses ?? extra.proxy?.recordResponses);
1349
- const useRedisProxy = options.skipDashboardRedisHealthCheck === true ||
1350
- (await (0, dashboard_redis_health_1.canUseDashboardRedisProxy)(dashboardBaseUrl));
1351
- if (!useRedisProxy) {
1352
- const strictProxyOnly = (0, mockifyer_core_1.resolveStrictScenarioResolution)({
1353
- strictScenarioResolution: options.config?.strictScenarioResolution ?? extra.strictScenarioResolution,
1354
- });
1355
- mockifyer_core_2.logger.warn(`[Mockifyer] initMockifyerForDashboardProxy: "${dashboardBaseUrl}" did not report healthy Redis ` +
1356
- (strictProxyOnly
1357
- ? '(strict proxy-only — local recording disabled). '
1358
- : '(unreachable or non-Redis provider). Falling back to filesystem mocks without proxy. ') +
1359
- 'Set skipDashboardRedisHealthCheck: true to force proxy anyway.');
1360
- const stripped = omitProxyFromPartialConfig(extra);
1361
- const fallbackDb = options.databaseProvider ?? extra.databaseProvider;
1362
- const mergedInitLogFs = {
1363
- ...stripped.initLog,
1364
- headline: stripped.initLog?.headline ??
1365
- (strictProxyOnly
1366
- ? '[Mockifyer preset] Node · strict proxy-only (dashboard Redis health check failed)'
1367
- : '[Mockifyer preset] Node · filesystem (dashboard Redis health check failed)'),
1368
- };
1369
- return setupMockifyer({
1370
- ...stripped,
1371
- mockDataPath,
1372
- ...(fallbackDb !== undefined ? { databaseProvider: fallbackDb } : {}),
1373
- ...(strictProxyOnly ? { intendedProxyBaseUrl: dashboardBaseUrl.trim() } : {}),
1374
- useGlobalFetch: options.useGlobalFetch ?? extra.useGlobalFetch ?? true,
1375
- clientId: options.clientId ?? extra.clientId,
1376
- deviceId: options.deviceId ?? extra.deviceId,
1377
- initLog: mergedInitLogFs,
1378
- });
1379
- }
1380
- const upstreamProxy = extra.proxy;
1381
- const mergedProxy = {
1382
- ...upstreamProxy,
1383
- baseUrl: upstreamProxy?.baseUrl ?? dashboardBaseUrl,
1384
- scenario: options.scenario ??
1385
- upstreamProxy?.scenario ??
1386
- (typeof process !== 'undefined' && process.env?.MOCKIFYER_SCENARIO?.trim()
1387
- ? process.env.MOCKIFYER_SCENARIO.trim()
1388
- : undefined),
1389
- ...(typeof recordOnMiss === 'boolean' ? { recordOnMiss } : {}),
1390
- recordResponses,
1391
- };
1392
- if (options.strictLaneScenario !== undefined ||
1393
- upstreamProxy?.strictLaneScenario !== undefined) {
1394
- mergedProxy.strictLaneScenario =
1395
- options.strictLaneScenario ?? upstreamProxy?.strictLaneScenario;
1396
- }
1397
- const envMirrorRaw = typeof process !== 'undefined'
1398
- ? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
1399
- : '';
1400
- const envMirror = envMirrorRaw === '1' || envMirrorRaw === 'true' || envMirrorRaw === 'yes' || envMirrorRaw === 'on';
1401
- const mirrorRecordedMocksToClient = options.mirrorRecordedMocksToClient ??
1402
- extra.proxy?.mirrorRecordedMocksToClient ??
1403
- (envMirror ? true : undefined);
1404
- if (mirrorRecordedMocksToClient !== undefined) {
1405
- mergedProxy.mirrorRecordedMocksToClient = mirrorRecordedMocksToClient;
1406
- }
1407
- const mergedInitLogProxy = {
1408
- ...extra.initLog,
1409
- headline: extra.initLog?.headline ?? '[Mockifyer preset] Node · dashboard Redis proxy',
1410
- };
1411
- const strictScenarioResolution = extra.strictScenarioResolution ??
1412
- options.config?.strictScenarioResolution ??
1413
- true;
1414
- return setupMockifyer({
1415
- ...extra,
1416
- mockDataPath,
1417
- strictScenarioResolution,
1418
- databaseProvider: options.databaseProvider ?? extra.databaseProvider ?? { type: 'memory' },
1419
- useGlobalFetch: options.useGlobalFetch ?? extra.useGlobalFetch ?? true,
1420
- clientId: options.clientId ?? extra.clientId,
1421
- deviceId: options.deviceId ?? extra.deviceId,
1422
- proxy: mergedProxy,
1423
- initLog: mergedInitLogProxy,
1424
- });
1267
+ return (0, mockifyer_core_1.initMockifyerForDashboardProxy)({ ...options, useGlobalFetch: options.useGlobalFetch ?? options.config?.useGlobalFetch ?? true }, setupMockifyer);
1425
1268
  }
1426
1269
  /**
1427
- * Preset: local **filesystem** mocks under {@link InitMockifyerForLocalFilesystemOptions.mockDataPath}
1428
- * (default `./mock-data` or `MOCKIFYER_PATH`). No dashboard proxy.
1270
+ * Preset: local filesystem mocks. No dashboard proxy.
1429
1271
  */
1430
1272
  function initMockifyerForLocalFilesystem(options = {}) {
1431
- const extra = options.config ?? {};
1432
- const mockDataPath = options.mockDataPath ??
1433
- extra.mockDataPath ??
1434
- (typeof process !== 'undefined' && process.env?.MOCKIFYER_PATH
1435
- ? process.env.MOCKIFYER_PATH
1436
- : './mock-data');
1437
- return setupMockifyer({
1438
- ...extra,
1439
- mockDataPath,
1440
- useGlobalFetch: options.useGlobalFetch ?? extra.useGlobalFetch ?? true,
1441
- recordMode: options.recordMode ?? extra.recordMode ?? false,
1442
- });
1273
+ return (0, mockifyer_core_1.initMockifyerForLocalFilesystem)({ ...options, useGlobalFetch: options.useGlobalFetch ?? options.config?.useGlobalFetch ?? true }, setupMockifyer);
1443
1274
  }
1444
1275
  /** Shared with {@link setupMockifyerForReactNative} strict-proxy branching. */
1445
- var dashboard_redis_health_2 = require("./utils/dashboard-redis-health");
1446
- Object.defineProperty(exports, "canUseDashboardRedisProxy", { enumerable: true, get: function () { return dashboard_redis_health_2.canUseDashboardRedisProxy; } });
1447
- Object.defineProperty(exports, "canUseDashboardCentralProxy", { enumerable: true, get: function () { return dashboard_redis_health_2.canUseDashboardCentralProxy; } });
1276
+ var dashboard_redis_health_1 = require("./utils/dashboard-redis-health");
1277
+ Object.defineProperty(exports, "canUseDashboardRedisProxy", { enumerable: true, get: function () { return dashboard_redis_health_1.canUseDashboardRedisProxy; } });
1278
+ Object.defineProperty(exports, "canUseDashboardCentralProxy", { enumerable: true, get: function () { return dashboard_redis_health_1.canUseDashboardCentralProxy; } });
1448
1279
  // Re-export types from core
1449
1280
  __exportStar(require("@sgedda/mockifyer-core"), exports);
1450
1281
  // React Native helpers: import `@sgedda/mockifyer-fetch/react-native` (not this entry — avoids
@@ -1,19 +1 @@
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>;
1
+ export { canUseDashboardCentralProxy, canUseDashboardRedisProxy, type DashboardHealthPayload, } from '@sgedda/mockifyer-core';
@@ -1,49 +1,6 @@
1
1
  "use strict";
2
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
- }
3
+ exports.canUseDashboardRedisProxy = exports.canUseDashboardCentralProxy = void 0;
4
+ var mockifyer_core_1 = require("@sgedda/mockifyer-core");
5
+ Object.defineProperty(exports, "canUseDashboardCentralProxy", { enumerable: true, get: function () { return mockifyer_core_1.canUseDashboardCentralProxy; } });
6
+ Object.defineProperty(exports, "canUseDashboardRedisProxy", { enumerable: true, get: function () { return mockifyer_core_1.canUseDashboardRedisProxy; } });
@@ -1,11 +1 @@
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;
1
+ export { joinProxyDashboardApiUrl } from '@sgedda/mockifyer-core';
@@ -1,18 +1,5 @@
1
1
  "use strict";
2
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
- }
3
+ exports.joinProxyDashboardApiUrl = void 0;
4
+ var mockifyer_core_1 = require("@sgedda/mockifyer-core");
5
+ Object.defineProperty(exports, "joinProxyDashboardApiUrl", { enumerable: true, get: function () { return mockifyer_core_1.joinProxyDashboardApiUrl; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sgedda/mockifyer-fetch",
3
- "version": "1.8.32",
3
+ "version": "1.8.33",
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,7 +49,7 @@
49
49
  },
50
50
  "license": "MIT",
51
51
  "dependencies": {
52
- "@sgedda/mockifyer-core": "^1.9.0"
52
+ "@sgedda/mockifyer-core": "^1.10.0"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@types/node": "^20.11.24",
@@ -8,57 +8,8 @@ import {
8
8
  getOutboundMockifyerDeviceIdHeader,
9
9
  MOCKIFYER_CLIENT_ID_HEADER,
10
10
  MOCKIFYER_DEVICE_ID_HEADER,
11
- MOCKIFYER_PARENT_REQUEST_ID_HEADER,
12
- MOCKIFYER_REQUEST_ID_HEADER,
11
+ performDashboardProxyRequest,
13
12
  } from '@sgedda/mockifyer-core';
14
- import { joinProxyDashboardApiUrl } from '../utils/join-proxy-dashboard-api-url';
15
-
16
- function buildProxyEnvelope(params: {
17
- url: string;
18
- method: string;
19
- lane: string | undefined;
20
- deviceId: string | undefined;
21
- requestId: string | undefined;
22
- parentRequestId: string | undefined;
23
- headers: Record<string, string>;
24
- body: unknown;
25
- scenario: string | undefined;
26
- recordOnMiss: boolean | undefined;
27
- recordResponses: boolean;
28
- strictLaneScenario: boolean;
29
- }): Record<string, unknown> {
30
- const {
31
- url,
32
- method,
33
- lane,
34
- deviceId,
35
- requestId,
36
- parentRequestId,
37
- headers,
38
- body,
39
- scenario,
40
- recordOnMiss,
41
- recordResponses,
42
- strictLaneScenario,
43
- } = params;
44
- const envelope: Record<string, unknown> = {
45
- url,
46
- method,
47
- clientId: lane,
48
- deviceId,
49
- requestId,
50
- parentRequestId,
51
- headers,
52
- body,
53
- scenario,
54
- recordResponses,
55
- strictLaneScenario,
56
- };
57
- if (typeof recordOnMiss === 'boolean') {
58
- envelope.record = recordOnMiss;
59
- }
60
- return envelope;
61
- }
62
13
 
63
14
  export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
64
15
  private baseUrl?: string;
@@ -166,7 +117,6 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
166
117
  };
167
118
 
168
119
  // Use original fetch if available (when global fetch is patched), otherwise use global fetch
169
- // CRITICAL: Always use _originalFetch if available to prevent infinite loops
170
120
  const fetchFn = (this as any)._originalFetch || fetch;
171
121
  if (!(this as any)._originalFetch) {
172
122
  console.warn('[FetchHTTPClient] _originalFetch not set! This may cause infinite loops if global fetch is patched.');
@@ -180,92 +130,29 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
180
130
 
181
131
  const explicitProxyContext = this.getExplicitProxyScenarioContext?.() ?? true;
182
132
 
183
- // Proxy mode (e.g. React Native → dashboard → Redis)
184
133
  if (this.proxyBaseUrl && !bypassMockifyer && explicitProxyContext) {
185
- const proxyUrl = joinProxyDashboardApiUrl(this.proxyBaseUrl, 'api/proxy');
186
- const proxyResponse = await fetchFn(proxyUrl, {
187
- method: 'POST',
188
- headers: {
189
- 'content-type': 'application/json',
190
- ...(lane ? { [MOCKIFYER_CLIENT_ID_HEADER]: lane } : {}),
191
- ...(this.deviceId ? { [MOCKIFYER_DEVICE_ID_HEADER]: this.deviceId } : {}),
192
- ...(hopRequestId ? { [MOCKIFYER_REQUEST_ID_HEADER]: hopRequestId } : {}),
193
- ...(hopParentRequestId ? { [MOCKIFYER_PARENT_REQUEST_ID_HEADER]: hopParentRequestId } : {}),
194
- },
195
- body: JSON.stringify(
196
- buildProxyEnvelope({
197
- url,
198
- method: String(requestConfig.method || 'GET'),
199
- lane,
200
- deviceId: this.deviceId,
201
- requestId: hopRequestId,
202
- parentRequestId: hopParentRequestId,
203
- headers: (() => {
204
- const out: Record<string, string> = {};
205
- headers.forEach((value, key) => {
206
- out[key] = value;
207
- });
208
- return out;
209
- })(),
210
- body: config.data ?? null,
211
- scenario: this.proxyScenario,
212
- recordOnMiss: this.proxyRecordOnMiss,
213
- recordResponses: this.proxyRecordResponses,
214
- strictLaneScenario: this.getStrictLaneScenario?.() ?? true,
215
- })
216
- ),
134
+ const headerRecord: Record<string, string> = {};
135
+ headers.forEach((value, key) => {
136
+ headerRecord[key] = value;
217
137
  });
218
- if (!proxyResponse.ok) {
219
- const txt = await proxyResponse.text();
220
- throw new Error(`[FetchHTTPClient] Proxy error: ${proxyResponse.status} ${txt}`);
221
- }
222
- const payload = await proxyResponse.json();
223
- try {
224
- const source = String(payload?.source || '');
225
- const hash = typeof payload?.hash === 'string' ? payload.hash : '';
226
- if (source) {
227
- const hashShort = hash ? `${hash.slice(0, 8)}…` : '';
228
- const laneLabel = lane ? lane : '—';
229
- const kind = source === 'redis' ? 'mock hit' : 'upstream';
230
- logger.debug(
231
- `[Mockifyer-Fetch] Proxy ${kind}: ${requestConfig.method} ${url} ${
232
- hashShort ? `(hash=${hashShort}) ` : ''
233
- }(lane=${laneLabel})`
234
- );
235
- }
236
- } catch {
237
- // ignore logging failures
238
- }
239
- const data = payload?.response?.data;
240
- const status = payload?.response?.status ?? 200;
241
- const responseHeaders: Record<string, string> = payload?.response?.headers ?? {};
242
-
243
- const scenarioResolution = payload?.scenarioResolution as
244
- | { scenario?: string | null }
245
- | undefined;
246
- const scenarioName =
247
- typeof scenarioResolution?.scenario === 'string' && scenarioResolution.scenario.trim()
248
- ? scenarioResolution.scenario.trim()
249
- : undefined;
250
-
251
- const mockifyerProxyRecording =
252
- payload?.recordedToStore === true && payload?.storedMock
253
- ? {
254
- recordedToStore: true as const,
255
- storedMock: payload.storedMock,
256
- hash: typeof payload.hash === 'string' ? payload.hash : undefined,
257
- scenarioName,
258
- }
259
- : undefined;
260
-
261
- return {
262
- data,
263
- status,
264
- statusText: String(status),
265
- headers: responseHeaders,
138
+ return performDashboardProxyRequest({
139
+ proxyBaseUrl: this.proxyBaseUrl,
140
+ url,
141
+ method: String(requestConfig.method || 'GET'),
142
+ headers: headerRecord,
143
+ body: config.data ?? null,
144
+ lane,
145
+ deviceId: this.deviceId,
146
+ requestId: hopRequestId,
147
+ parentRequestId: hopParentRequestId,
148
+ scenario: this.proxyScenario,
149
+ recordOnMiss: this.proxyRecordOnMiss,
150
+ recordResponses: this.proxyRecordResponses,
151
+ strictLaneScenario: this.getStrictLaneScenario?.() ?? true,
266
152
  config,
267
- mockifyerProxyRecording,
268
- };
153
+ fetchFn,
154
+ logTag: 'Mockifyer-Fetch',
155
+ });
269
156
  }
270
157
 
271
158
  if (!bypassMockifyer && lane && !getOutboundMockifyerClientIdHeader(headers)) {
@@ -292,7 +179,6 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
292
179
  }
293
180
  }
294
181
 
295
- // Convert response Headers to Record<string, string>
296
182
  const responseHeaders: Record<string, string> = {};
297
183
  response.headers.forEach((value: string, key: string) => {
298
184
  responseHeaders[key] = value;
@@ -317,4 +203,3 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
317
203
  };
318
204
  }
319
205
  }
320
-
package/src/index.ts CHANGED
@@ -56,7 +56,12 @@ import {
56
56
  resolveActivationMode,
57
57
  shouldApplyMockifyer,
58
58
  isExplicitProxyScenarioContext,
59
- parseProxyRecordOnMissEnv,
59
+ applyProxyRecordOnMissEnv,
60
+ mirrorProxyRecordingToClient,
61
+ initMockifyerForDashboardProxy as coreInitMockifyerForDashboardProxy,
62
+ initMockifyerForLocalFilesystem as coreInitMockifyerForLocalFilesystem,
63
+ type InitMockifyerForDashboardProxyOptions,
64
+ type InitMockifyerForLocalFilesystemOptions,
60
65
  newRecordingUsesAlwaysUseRealApi,
61
66
  shouldBlockLocalMockRecording,
62
67
  resolveStrictScenarioResolution,
@@ -71,32 +76,6 @@ import {
71
76
  import { logger, setLogLevel } from '@sgedda/mockifyer-core';
72
77
 
73
78
  import { FetchHTTPClient } from './clients/fetch-client';
74
- import { canUseDashboardRedisProxy } from './utils/dashboard-redis-health';
75
-
76
- /**
77
- * When `proxy.baseUrl` is set and `proxy.recordOnMiss` is omitted, apply `MOCKIFYER_PROXY_RECORD_ON_MISS` if set.
78
- */
79
- function applyProxyRecordOnMissEnv(config: MockifyerConfig): MockifyerConfig {
80
- const proxy = config.proxy;
81
- const baseUrl = proxy?.baseUrl?.trim();
82
- if (!proxy || !baseUrl || proxy.recordOnMiss !== undefined) {
83
- return config;
84
- }
85
- const parsed = parseProxyRecordOnMissEnv();
86
- if (parsed === undefined) {
87
- return config;
88
- }
89
- return {
90
- ...config,
91
- proxy: {
92
- baseUrl: proxy.baseUrl,
93
- scenario: proxy.scenario,
94
- recordOnMiss: parsed,
95
- strictLaneScenario: proxy.strictLaneScenario,
96
- mirrorRecordedMocksToClient: proxy.mirrorRecordedMocksToClient,
97
- },
98
- };
99
- }
100
79
 
101
80
  class MockifyerClass {
102
81
  private config: MockifyerConfig;
@@ -877,57 +856,23 @@ class MockifyerClass {
877
856
  }
878
857
  const hash = rec.hash?.trim();
879
858
  const scenarioName = rec.scenarioName?.trim();
880
- if (!hash || !scenarioName) {
881
- logger.warn('[Mockifyer-Fetch] Proxy client mirror skipped: missing hash or scenario from proxy');
882
- return;
883
- }
884
859
  const mockData = rec.storedMock as MockData;
885
- const url = mockData?.request?.url || '';
886
- if (shouldExcludeUrl(url, this.config.excludedUrls)) {
887
- return;
888
- }
889
- const recExclusions = resolveRecordingExclusions(this.config);
890
- if (shouldExcludeRecording(url, recExclusions, this.config.baseUrl)) {
891
- return;
892
- }
893
-
894
- await this.databaseProviderInitPromise;
895
-
896
860
  const providerType = this.config.databaseProvider?.type;
897
- if (this.databaseProvider && providerType !== 'memory') {
898
- try {
899
- const out = this.databaseProvider.save(mockData, {
900
- relativePath: `redis/${hash}.json`,
901
- scenario: scenarioName,
902
- });
903
- if (out instanceof Promise) {
904
- await out;
905
- }
906
- logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (${providerType}): ${scenarioName}/redis/${hash}.json`);
907
- if (providerType === 'hybrid') {
908
- await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
909
- }
910
- } catch (e) {
911
- logger.error('[Mockifyer-Fetch] Proxy client mirror (provider) failed:', e);
912
- }
913
- return;
914
- }
915
861
 
916
- if (fs && path) {
917
- try {
918
- ensureScenarioFolder(this.config.mockDataPath, scenarioName);
919
- const scenarioPath = getScenarioFolderPath(this.config.mockDataPath, scenarioName);
920
- const filePath = path.join(scenarioPath, 'redis', `${hash}.json`);
921
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
922
- fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
923
- logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (filesystem): ${scenarioName}/redis/${hash}.json`);
924
- } catch (e) {
925
- logger.error('[Mockifyer-Fetch] Proxy client mirror (Node fs) failed:', e);
926
- }
927
- return;
928
- }
862
+ await mirrorProxyRecordingToClient({
863
+ config: this.config,
864
+ mockDataPath: this.config.mockDataPath,
865
+ recording: rec,
866
+ databaseProvider: this.databaseProvider,
867
+ databaseProviderInitPromise: this.databaseProviderInitPromise,
868
+ logPrefix: 'Mockifyer-Fetch',
869
+ });
929
870
 
930
- await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
871
+ if (providerType === 'hybrid' && hash && scenarioName && mockData) {
872
+ await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
873
+ } else if (!fs && hash && scenarioName && mockData) {
874
+ await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
875
+ }
931
876
  }
932
877
 
933
878
  private async tryMirrorProxyRecordingViaMetro(
@@ -1609,212 +1554,31 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
1609
1554
  return extendedClient;
1610
1555
  }
1611
1556
 
1612
- /** Drops `proxy` when merging partial config so filesystem fallback cannot accidentally keep proxy. */
1613
- function omitProxyFromPartialConfig(config: Partial<MockifyerConfig>): Partial<MockifyerConfig> {
1614
- const { proxy: _drop, ...rest } = config;
1615
- void _drop;
1616
- return rest;
1617
- }
1618
-
1619
- /** Options for {@link initMockifyerForDashboardProxy} — dashboard + `/api/proxy` (run `mockifyer-dashboard --provider redis`). */
1620
- export interface InitMockifyerForDashboardProxyOptions {
1621
- /** mockifyer-dashboard origin (e.g. `http://localhost:3002`). Not the Redis URL. */
1622
- dashboardBaseUrl: string;
1623
- /** Mock root for scenario file fallbacks etc. Defaults `MOCKIFYER_PATH` env or `./mock-data`. */
1624
- mockDataPath?: string;
1625
- /** Client lane id (`X-Mockifyer-Client-Id` / proxy envelope). Defaults `MOCKIFYER_CLIENT_ID` env. */
1626
- clientId?: string;
1627
- deviceId?: string;
1628
- scenario?: string;
1629
- /**
1630
- * When **`true`**, each `/api/proxy` request sends **`"record": true`**. When **`false`**, sends **`"record": false`**.
1631
- * When **omitted**, the **`record`** field is omitted so the **dashboard per-scenario** toggle applies; **`MOCKIFYER_PROXY_RECORD_ON_MISS`**
1632
- * and **`MOCKIFYER_RECORD=true`** (last) still set an explicit client flag when you want env-driven recording without code.
1633
- */
1634
- recordOnMiss?: boolean;
1635
- /**
1636
- * When false, dashboard proxy stores request-only stubs on cache miss.
1637
- * Defaults via {@link resolveRecordResponses} (`MOCKIFYER_RECORD_RESPONSES` env, else `false`).
1638
- */
1639
- recordResponses?: boolean;
1640
- strictLaneScenario?: boolean;
1641
- useGlobalFetch?: boolean;
1642
- /** Use a local provider for mock hits before the proxy (default in-memory only) when **`/api/proxy`** is active. */
1643
- databaseProvider?: MockifyerConfig['databaseProvider'];
1644
- /** Additional `MockifyerConfig` fields — applied first, then preset fields win on `mockDataPath`, `proxy`, etc. */
1645
- config?: Partial<MockifyerConfig>;
1646
- /**
1647
- * When **`true`**, skips **`GET …/api/health`** and always sets **`proxy`**.
1648
- * Default **`false`**: if Redis is not healthy (or unreachable), omit **`proxy`** and use filesystem mocks + **`recordMode`** disk saves — aligns with **`setupMockifyerForReactNative`** dev fallback.
1649
- */
1650
- skipDashboardRedisHealthCheck?: boolean;
1651
- /**
1652
- * When the proxy records a response to Redis, also write the same mock under `mockDataPath` on this machine
1653
- * (or via Metro when using strict RN + in-memory). Env: `MOCKIFYER_PROXY_MIRROR_TO_CLIENT`.
1654
- */
1655
- mirrorRecordedMocksToClient?: boolean;
1656
- }
1557
+ export type { InitMockifyerForDashboardProxyOptions, InitMockifyerForLocalFilesystemOptions };
1657
1558
 
1658
1559
  /**
1659
- * Preset: **`GET /api/health`** must report Redis ready before **`proxy`** is set; otherwise filesystem mocks without proxy (like RN Hybrid fallback vs strict proxy).
1660
- * Run **`mockifyer-dashboard --provider redis`** for the dashboard hop; use **`skipDashboardRedisHealthCheck`** to bypass the probe.
1661
- *
1560
+ * Preset: dashboard central store proxy when health check passes; otherwise filesystem mocks.
1662
1561
  * For full control, use {@link setupMockifyer} directly.
1663
1562
  */
1664
1563
  export async function initMockifyerForDashboardProxy(
1665
1564
  options: InitMockifyerForDashboardProxyOptions
1666
1565
  ): Promise<MockifyerInstance> {
1667
- const extra = options.config ?? {};
1668
- const dashboardBaseUrl = String(options.dashboardBaseUrl).trim();
1669
- if (!dashboardBaseUrl) {
1670
- throw new Error('initMockifyerForDashboardProxy: dashboardBaseUrl is required');
1671
- }
1672
-
1673
- const mockDataPath =
1674
- options.mockDataPath ??
1675
- extra.mockDataPath ??
1676
- (typeof process !== 'undefined' && process.env?.MOCKIFYER_PATH
1677
- ? process.env.MOCKIFYER_PATH
1678
- : './mock-data');
1679
-
1680
- const envRecord =
1681
- typeof process !== 'undefined' && process.env?.MOCKIFYER_RECORD === 'true';
1682
-
1683
- const recordOnMiss =
1684
- options.recordOnMiss ??
1685
- extra.proxy?.recordOnMiss ??
1686
- parseProxyRecordOnMissEnv() ??
1687
- (envRecord ? true : undefined);
1688
-
1689
- const recordResponses = resolveRecordResponses(
1690
- options.recordResponses ?? extra.proxy?.recordResponses
1566
+ return coreInitMockifyerForDashboardProxy(
1567
+ { ...options, useGlobalFetch: options.useGlobalFetch ?? options.config?.useGlobalFetch ?? true },
1568
+ setupMockifyer
1691
1569
  );
1692
-
1693
- const useRedisProxy =
1694
- options.skipDashboardRedisHealthCheck === true ||
1695
- (await canUseDashboardRedisProxy(dashboardBaseUrl));
1696
-
1697
- if (!useRedisProxy) {
1698
- const strictProxyOnly = resolveStrictScenarioResolution({
1699
- strictScenarioResolution:
1700
- options.config?.strictScenarioResolution ?? extra.strictScenarioResolution,
1701
- });
1702
- logger.warn(
1703
- `[Mockifyer] initMockifyerForDashboardProxy: "${dashboardBaseUrl}" did not report healthy Redis ` +
1704
- (strictProxyOnly
1705
- ? '(strict proxy-only — local recording disabled). '
1706
- : '(unreachable or non-Redis provider). Falling back to filesystem mocks without proxy. ') +
1707
- 'Set skipDashboardRedisHealthCheck: true to force proxy anyway.'
1708
- );
1709
- const stripped = omitProxyFromPartialConfig(extra);
1710
- const fallbackDb = options.databaseProvider ?? extra.databaseProvider;
1711
- const mergedInitLogFs: MockifyerConfig['initLog'] = {
1712
- ...stripped.initLog,
1713
- headline:
1714
- stripped.initLog?.headline ??
1715
- (strictProxyOnly
1716
- ? '[Mockifyer preset] Node · strict proxy-only (dashboard Redis health check failed)'
1717
- : '[Mockifyer preset] Node · filesystem (dashboard Redis health check failed)'),
1718
- };
1719
- return setupMockifyer({
1720
- ...stripped,
1721
- mockDataPath,
1722
- ...(fallbackDb !== undefined ? { databaseProvider: fallbackDb } : {}),
1723
- ...(strictProxyOnly ? { intendedProxyBaseUrl: dashboardBaseUrl.trim() } : {}),
1724
- useGlobalFetch: options.useGlobalFetch ?? extra.useGlobalFetch ?? true,
1725
- clientId: options.clientId ?? extra.clientId,
1726
- deviceId: options.deviceId ?? extra.deviceId,
1727
- initLog: mergedInitLogFs,
1728
- });
1729
- }
1730
-
1731
- const upstreamProxy = extra.proxy as MockifyerConfig['proxy'] | undefined;
1732
- const mergedProxy = {
1733
- ...upstreamProxy,
1734
- baseUrl: upstreamProxy?.baseUrl ?? dashboardBaseUrl,
1735
- scenario:
1736
- options.scenario ??
1737
- upstreamProxy?.scenario ??
1738
- (typeof process !== 'undefined' && process.env?.MOCKIFYER_SCENARIO?.trim()
1739
- ? process.env.MOCKIFYER_SCENARIO.trim()
1740
- : undefined),
1741
- ...(typeof recordOnMiss === 'boolean' ? { recordOnMiss } : {}),
1742
- recordResponses,
1743
- } as NonNullable<MockifyerConfig['proxy']>;
1744
- if (
1745
- options.strictLaneScenario !== undefined ||
1746
- upstreamProxy?.strictLaneScenario !== undefined
1747
- ) {
1748
- mergedProxy.strictLaneScenario =
1749
- options.strictLaneScenario ?? upstreamProxy?.strictLaneScenario;
1750
- }
1751
-
1752
- const envMirrorRaw =
1753
- typeof process !== 'undefined'
1754
- ? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
1755
- : '';
1756
- const envMirror =
1757
- envMirrorRaw === '1' || envMirrorRaw === 'true' || envMirrorRaw === 'yes' || envMirrorRaw === 'on';
1758
- const mirrorRecordedMocksToClient =
1759
- options.mirrorRecordedMocksToClient ??
1760
- extra.proxy?.mirrorRecordedMocksToClient ??
1761
- (envMirror ? true : undefined);
1762
- if (mirrorRecordedMocksToClient !== undefined) {
1763
- mergedProxy.mirrorRecordedMocksToClient = mirrorRecordedMocksToClient;
1764
- }
1765
-
1766
- const mergedInitLogProxy: MockifyerConfig['initLog'] = {
1767
- ...extra.initLog,
1768
- headline: extra.initLog?.headline ?? '[Mockifyer preset] Node · dashboard Redis proxy',
1769
- };
1770
-
1771
- const strictScenarioResolution =
1772
- extra.strictScenarioResolution ??
1773
- options.config?.strictScenarioResolution ??
1774
- true;
1775
-
1776
- return setupMockifyer({
1777
- ...extra,
1778
- mockDataPath,
1779
- strictScenarioResolution,
1780
- databaseProvider: options.databaseProvider ?? extra.databaseProvider ?? { type: 'memory' },
1781
- useGlobalFetch: options.useGlobalFetch ?? extra.useGlobalFetch ?? true,
1782
- clientId: options.clientId ?? extra.clientId,
1783
- deviceId: options.deviceId ?? extra.deviceId,
1784
- proxy: mergedProxy,
1785
- initLog: mergedInitLogProxy,
1786
- });
1787
- }
1788
-
1789
- export interface InitMockifyerForLocalFilesystemOptions {
1790
- mockDataPath?: string;
1791
- useGlobalFetch?: boolean;
1792
- recordMode?: boolean;
1793
- /** Applied first; preset fills `mockDataPath` / `useGlobalFetch` when omitted. */
1794
- config?: Partial<MockifyerConfig>;
1795
1570
  }
1796
1571
 
1797
1572
  /**
1798
- * Preset: local **filesystem** mocks under {@link InitMockifyerForLocalFilesystemOptions.mockDataPath}
1799
- * (default `./mock-data` or `MOCKIFYER_PATH`). No dashboard proxy.
1573
+ * Preset: local filesystem mocks. No dashboard proxy.
1800
1574
  */
1801
1575
  export function initMockifyerForLocalFilesystem(
1802
1576
  options: InitMockifyerForLocalFilesystemOptions = {}
1803
1577
  ): MockifyerInstance {
1804
- const extra = options.config ?? {};
1805
- const mockDataPath =
1806
- options.mockDataPath ??
1807
- extra.mockDataPath ??
1808
- (typeof process !== 'undefined' && process.env?.MOCKIFYER_PATH
1809
- ? process.env.MOCKIFYER_PATH
1810
- : './mock-data');
1811
-
1812
- return setupMockifyer({
1813
- ...extra,
1814
- mockDataPath,
1815
- useGlobalFetch: options.useGlobalFetch ?? extra.useGlobalFetch ?? true,
1816
- recordMode: options.recordMode ?? extra.recordMode ?? false,
1817
- });
1578
+ return coreInitMockifyerForLocalFilesystem(
1579
+ { ...options, useGlobalFetch: options.useGlobalFetch ?? options.config?.useGlobalFetch ?? true },
1580
+ setupMockifyer
1581
+ );
1818
1582
  }
1819
1583
 
1820
1584
  /** Shared with {@link setupMockifyerForReactNative} strict-proxy branching. */
@@ -1,58 +1,5 @@
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
- }
1
+ export {
2
+ canUseDashboardCentralProxy,
3
+ canUseDashboardRedisProxy,
4
+ type DashboardHealthPayload,
5
+ } from '@sgedda/mockifyer-core';
@@ -1,15 +1 @@
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
- }
1
+ export { joinProxyDashboardApiUrl } from '@sgedda/mockifyer-core';