@sgedda/mockifyer-fetch 1.8.25 → 1.8.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,15 @@
1
- import { BaseHTTPClient } from '@sgedda/mockifyer-core';
2
- import { HTTPRequestConfig, HTTPResponse } from '@sgedda/mockifyer-core';
1
+ import { BaseHTTPClient, HTTPRequestConfig, HTTPResponse } from '@sgedda/mockifyer-core';
3
2
  export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
4
3
  private baseUrl?;
5
4
  private defaultHeaders;
6
5
  private proxyBaseUrl?;
7
6
  private proxyScenario?;
8
- private proxyRecordOnMiss;
7
+ /** When set, included as `record` on `/api/proxy`. When unset, dashboard per-scenario default applies. */
8
+ private proxyRecordOnMiss?;
9
+ private proxyRecordResponses;
9
10
  private getClientId?;
11
+ private getStrictLaneScenario?;
12
+ private getExplicitProxyScenarioContext?;
10
13
  private clientIdSnapshot?;
11
14
  private deviceId?;
12
15
  constructor(config?: {
@@ -16,9 +19,15 @@ export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<an
16
19
  baseUrl: string;
17
20
  scenario?: string;
18
21
  recordOnMiss?: boolean;
22
+ recordResponses?: boolean;
23
+ strictLaneScenario?: boolean;
24
+ mirrorRecordedMocksToClient?: boolean;
19
25
  };
20
26
  clientId?: string;
21
27
  getClientId?: () => string | undefined;
28
+ getStrictLaneScenario?: () => boolean;
29
+ /** When false, skip `/api/proxy` and call the real URL (devtools-friendly passthrough). */
30
+ getExplicitProxyScenarioContext?: () => boolean;
22
31
  deviceId?: string;
23
32
  });
24
33
  private resolvedClientLane;
@@ -2,8 +2,27 @@
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
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
+ }
7
26
  class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
8
27
  constructor(config) {
9
28
  super();
@@ -11,12 +30,23 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
11
30
  this.defaultHeaders = config?.defaultHeaders || {};
12
31
  this.proxyBaseUrl = config?.proxy?.baseUrl;
13
32
  this.proxyScenario = config?.proxy?.scenario;
14
- this.proxyRecordOnMiss = config?.proxy?.recordOnMiss ?? false;
33
+ this.proxyRecordOnMiss = config?.proxy?.recordOnMiss;
34
+ this.proxyRecordResponses = config?.proxy?.recordResponses ?? false;
15
35
  this.getClientId = config?.getClientId;
36
+ this.getStrictLaneScenario = config?.getStrictLaneScenario;
37
+ this.getExplicitProxyScenarioContext = config?.getExplicitProxyScenarioContext;
16
38
  this.clientIdSnapshot = config?.clientId;
17
39
  this.deviceId = config?.deviceId;
18
40
  }
19
- resolvedClientLane() {
41
+ resolvedClientLane(hopHeaders) {
42
+ const fromHop = (0, mockifyer_core_1.getOutboundMockifyerClientIdHeader)(hopHeaders);
43
+ if (fromHop) {
44
+ return fromHop;
45
+ }
46
+ const fromInbound = (0, mockifyer_core_1.getActiveInboundClientId)();
47
+ if (fromInbound) {
48
+ return fromInbound;
49
+ }
20
50
  if (this.getClientId) {
21
51
  const v = this.getClientId();
22
52
  if (v != null && String(v).trim() !== '') {
@@ -68,22 +98,30 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
68
98
  if (!this._originalFetch) {
69
99
  console.warn('[FetchHTTPClient] _originalFetch not set! This may cause infinite loops if global fetch is patched.');
70
100
  }
71
- const lane = this.resolvedClientLane();
101
+ const lane = this.resolvedClientLane(config.headers);
102
+ const bypassMockifyer = config.__mockifyer_bypass === true || config.__mockifyer_skip_save === true;
103
+ const hopRequestId = config.__mockifyer_requestId;
104
+ const hopParentRequestId = config.__mockifyer_parentRequestId;
105
+ const explicitProxyContext = this.getExplicitProxyScenarioContext?.() ?? true;
72
106
  // Proxy mode (e.g. React Native → dashboard → Redis)
73
- if (this.proxyBaseUrl) {
107
+ if (this.proxyBaseUrl && !bypassMockifyer && explicitProxyContext) {
74
108
  const proxyUrl = (0, join_proxy_dashboard_api_url_1.joinProxyDashboardApiUrl)(this.proxyBaseUrl, 'api/proxy');
75
109
  const proxyResponse = await fetchFn(proxyUrl, {
76
110
  method: 'POST',
77
111
  headers: {
78
112
  'content-type': 'application/json',
79
- ...(lane ? { [mockifyer_core_2.MOCKIFYER_CLIENT_ID_HEADER]: lane } : {}),
80
- ...(this.deviceId ? { [mockifyer_core_2.MOCKIFYER_DEVICE_ID_HEADER]: this.deviceId } : {}),
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 } : {}),
81
117
  },
82
- body: JSON.stringify({
118
+ body: JSON.stringify(buildProxyEnvelope({
83
119
  url,
84
- method: requestConfig.method,
85
- clientId: lane,
120
+ method: String(requestConfig.method || 'GET'),
121
+ lane,
86
122
  deviceId: this.deviceId,
123
+ requestId: hopRequestId,
124
+ parentRequestId: hopParentRequestId,
87
125
  headers: (() => {
88
126
  const out = {};
89
127
  headers.forEach((value, key) => {
@@ -93,8 +131,10 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
93
131
  })(),
94
132
  body: config.data ?? null,
95
133
  scenario: this.proxyScenario,
96
- record: this.proxyRecordOnMiss,
97
- }),
134
+ recordOnMiss: this.proxyRecordOnMiss,
135
+ recordResponses: this.proxyRecordResponses,
136
+ strictLaneScenario: this.getStrictLaneScenario?.() ?? true,
137
+ })),
98
138
  });
99
139
  if (!proxyResponse.ok) {
100
140
  const txt = await proxyResponse.text();
@@ -108,7 +148,7 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
108
148
  const hashShort = hash ? `${hash.slice(0, 8)}…` : '';
109
149
  const laneLabel = lane ? lane : '—';
110
150
  const kind = source === 'redis' ? 'mock hit' : 'upstream';
111
- console.log(`[Mockifyer-Fetch] Proxy ${kind}: ${requestConfig.method} ${url} ${hashShort ? `(hash=${hashShort}) ` : ''}(lane=${laneLabel})`);
151
+ mockifyer_core_1.logger.debug(`[Mockifyer-Fetch] Proxy ${kind}: ${requestConfig.method} ${url} ${hashShort ? `(hash=${hashShort}) ` : ''}(lane=${laneLabel})`);
112
152
  }
113
153
  }
114
154
  catch {
@@ -117,19 +157,35 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
117
157
  const data = payload?.response?.data;
118
158
  const status = payload?.response?.status ?? 200;
119
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;
120
172
  return {
121
173
  data,
122
174
  status,
123
175
  statusText: String(status),
124
176
  headers: responseHeaders,
125
177
  config,
178
+ mockifyerProxyRecording,
126
179
  };
127
180
  }
128
- if (lane && !(0, mockifyer_core_2.getOutboundMockifyerClientIdHeader)(headers)) {
129
- headers.set(mockifyer_core_2.MOCKIFYER_CLIENT_ID_HEADER, lane);
181
+ if (!bypassMockifyer && lane && !(0, mockifyer_core_1.getOutboundMockifyerClientIdHeader)(headers)) {
182
+ headers.set(mockifyer_core_1.MOCKIFYER_CLIENT_ID_HEADER, lane);
130
183
  }
131
- if (this.deviceId && String(this.deviceId).trim() && !(0, mockifyer_core_2.getOutboundMockifyerDeviceIdHeader)(headers)) {
132
- headers.set(mockifyer_core_2.MOCKIFYER_DEVICE_ID_HEADER, String(this.deviceId).trim());
184
+ if (!bypassMockifyer &&
185
+ this.deviceId &&
186
+ String(this.deviceId).trim() &&
187
+ !(0, mockifyer_core_1.getOutboundMockifyerDeviceIdHeader)(headers)) {
188
+ headers.set(mockifyer_core_1.MOCKIFYER_DEVICE_ID_HEADER, String(this.deviceId).trim());
133
189
  }
134
190
  const response = await fetchFn(url, requestConfig);
135
191
  const contentType = response.headers.get('content-type') || '';
package/dist/index.d.ts CHANGED
@@ -7,5 +7,63 @@ 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
+ }
48
+ /**
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
+ *
52
+ * For full control, use {@link setupMockifyer} directly.
53
+ */
54
+ 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
+ /**
63
+ * Preset: local **filesystem** mocks under {@link InitMockifyerForLocalFilesystemOptions.mockDataPath}
64
+ * (default `./mock-data` or `MOCKIFYER_PATH`). No dashboard proxy.
65
+ */
66
+ export declare function initMockifyerForLocalFilesystem(options?: InitMockifyerForLocalFilesystemOptions): MockifyerInstance;
67
+ /** Shared with {@link setupMockifyerForReactNative} strict-proxy branching. */
68
+ export { canUseDashboardRedisProxy, canUseDashboardCentralProxy, } from './utils/dashboard-redis-health';
10
69
  export * from '@sgedda/mockifyer-core';
11
- export * from './react-native';