@sgedda/mockifyer-fetch 1.8.106 → 1.8.108

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.
package/README.md ADDED
@@ -0,0 +1,181 @@
1
+ # @sgedda/mockifyer-fetch
2
+
3
+ HTTP mock record/replay for `fetch` API with in-memory provider support for browser and Expo web.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @sgedda/mockifyer-fetch @sgedda/mockifyer-core
9
+ ```
10
+
11
+ ## Node.js Usage
12
+
13
+ ```typescript
14
+ import { setupMockifyer } from '@sgedda/mockifyer-fetch';
15
+
16
+ const mockifyer = setupMockifyer({
17
+ mockDataPath: './mock-data',
18
+ recordMode: false,
19
+ useGlobalFetch: true
20
+ });
21
+
22
+ // Your fetch calls are now mocked
23
+ const response = await fetch('https://api.example.com/data');
24
+ ```
25
+
26
+ ## Streaming responses (SSE / chunked)
27
+
28
+ When a live response is `text/event-stream` or chunked without `Content-Length`, Mockifyer can record a chunk timeline on `response.stream` while keeping `response.data` as the concatenated body (backward compatible).
29
+
30
+ ```typescript
31
+ setupMockifyer({
32
+ mockDataPath: './mock-data',
33
+ recordMode: true,
34
+ recordResponses: true,
35
+ useGlobalFetch: true,
36
+ // 'accelerated' (default) | 'original' | 'immediate'
37
+ streamReplay: 'accelerated',
38
+ streamRecordMaxBytes: 1_000_000,
39
+ streamRecordMaxDurationMs: 30_000,
40
+ });
41
+ ```
42
+
43
+ - **Record:** the fetch body is teed — your caller still gets the live `ReadableStream` without extra buffering; recording respects the byte/duration caps and sets `truncated` when a cap is hit.
44
+ - **Replay:** mocks with `stream` rebuild a real `ReadableStream` paced by `streamReplay`. Mocks without `stream` behave exactly as before.
45
+ - **Proxy (phase 1):** dashboard `/api/proxy` still returns a JSON envelope; the client rebuilds the stream from stored chunks on mock-hit.
46
+ - **React Native:** if `ReadableStream` is unavailable, Mockifyer falls back to flat bodies (no crash).
47
+
48
+ Axios `responseType: 'stream'` and `EventSource` patching are not included in this release.
49
+
50
+ ## Browser & Expo Web Usage
51
+
52
+ Mockifyer works in browsers and Expo web builds with the memory provider and preloaded fixtures.
53
+
54
+ ### Requirements
55
+
56
+ - Only the `memory` provider is supported (no filesystem/Redis/SQLite in browsers)
57
+ - Fixtures must be preloaded via `databaseProvider.options.fixtures`
58
+ - Uses Web Crypto API for hashing (or pure-JS fallback)
59
+
60
+ ### Browser Example
61
+
62
+ ```typescript
63
+ import { setupMockifyer } from '@sgedda/mockifyer-fetch';
64
+ import rates from './fixtures/api.frankfurter.dev/v1/latest.json';
65
+
66
+ const mockifyer = setupMockifyer({
67
+ mockDataPath: './fixtures',
68
+ databaseProvider: {
69
+ type: 'memory',
70
+ options: {
71
+ fixtures: [rates] // Preload your mock data
72
+ }
73
+ },
74
+ recordMode: false,
75
+ failOnMissingMock: true, // Recommended for testing
76
+ useGlobalFetch: true // Patch global fetch
77
+ });
78
+
79
+ // Fetch will use the preloaded mock
80
+ const response = await fetch('https://api.frankfurter.dev/v1/latest');
81
+ const data = await response.json();
82
+ console.log(data); // Returns your mock data
83
+ ```
84
+
85
+ ### Expo Web Example
86
+
87
+ ```javascript
88
+ // App.js
89
+ import { setupMockifyer } from '@sgedda/mockifyer-fetch';
90
+ import frankfurterRates from './fixtures/frankfurter-rates.json';
91
+
92
+ export default function App() {
93
+ useEffect(() => {
94
+ // Initialize mockifyer on mount
95
+ setupMockifyer({
96
+ mockDataPath: './fixtures',
97
+ databaseProvider: {
98
+ type: 'memory',
99
+ options: {
100
+ fixtures: [frankfurterRates]
101
+ }
102
+ },
103
+ recordMode: false,
104
+ failOnMissingMock: true,
105
+ useGlobalFetch: true
106
+ });
107
+ }, []);
108
+
109
+ const fetchData = async () => {
110
+ const response = await fetch('https://api.frankfurter.dev/v1/latest');
111
+ const data = await response.json();
112
+ console.log(data); // Returns your mock data
113
+ };
114
+
115
+ // ... rest of your component
116
+ }
117
+ ```
118
+
119
+ ### Fixture Format
120
+
121
+ Fixtures are JSON files with this structure:
122
+
123
+ ```json
124
+ {
125
+ "request": {
126
+ "method": "GET",
127
+ "url": "https://api.example.com/endpoint",
128
+ "headers": {},
129
+ "queryParams": {}
130
+ },
131
+ "response": {
132
+ "status": 200,
133
+ "headers": {
134
+ "content-type": "application/json"
135
+ },
136
+ "data": {
137
+ "result": "your mock data here"
138
+ }
139
+ },
140
+ "timestamp": "2024-01-15T10:00:00.000Z"
141
+ }
142
+ ```
143
+
144
+ ### Bundler Configuration
145
+
146
+ Mockifyer uses package.json `browser` field mappings to automatically resolve browser-safe modules. Modern bundlers (Metro, Vite, webpack, esbuild) honor these mappings automatically.
147
+
148
+ **Metro (Expo)**:
149
+ - Works out of the box with `npx expo export --platform web`
150
+ - Uses the browser entry point automatically
151
+
152
+ **Vite**:
153
+ - Add `conditions: ['browser']` to your config if needed
154
+
155
+ **webpack**:
156
+ - The `browser` field is respected by default
157
+
158
+ ### Browser Compatibility
159
+
160
+ - ✅ Chrome, Firefox, Safari, Edge (modern versions)
161
+ - ✅ Expo web (Metro bundler)
162
+ - ✅ Vite, webpack, esbuild (with `platform: 'browser'`)
163
+ - ❌ Node.js built-ins are not available (fs, path, crypto → Web Crypto)
164
+ - ❌ Redis, SQLite providers not supported (use `memory` only)
165
+
166
+ ### Limitations in Browser
167
+
168
+ - **No local filesystem recording**. Record through the dashboard proxy or in Node.
169
+ - No Redis/SQLite support
170
+ - All fixtures must be preloaded at initialization
171
+ - Request correlation is simplified (header-only)
172
+ - No Atlas HTML generation
173
+ - No screenshot capture
174
+
175
+ **Dashboard proxy in the browser:** Set `proxy.baseUrl` (for example `http://localhost:3002`) in `setupMockifyer`. The browser build sends requests to the dashboard's `/api/proxy` using `fetch`, so you can record and replay through the dashboard without Node. `initMockifyerForDashboardProxy` and `initMockifyerForDashboardProxyClients` are not available in browser builds, so use `setupMockifyer` from the browser entry.
176
+
177
+ ### See Also
178
+
179
+ - [@sgedda/mockifyer-core](../mockifyer-core/README.md) - Core types and providers
180
+ - [Full documentation](https://mockifyer.dev)
181
+ - [GitHub repository](https://github.com/sgedda/mockifyer)
@@ -1,4 +1,4 @@
1
- import { BaseHTTPClient, HTTPRequestConfig, HTTPResponse } from '@sgedda/mockifyer-core';
1
+ import { BaseHTTPClient, HTTPRequestConfig, HTTPResponse, type StreamRecordCaps } from '@sgedda/mockifyer-core';
2
2
  export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
3
3
  private baseUrl?;
4
4
  private defaultHeaders;
@@ -11,6 +11,8 @@ export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<an
11
11
  private getStrictLaneScenario?;
12
12
  private getUpstreamTlsInsecure?;
13
13
  private getExplicitProxyScenarioContext?;
14
+ private getShouldRecordStreams?;
15
+ private getStreamRecordCaps?;
14
16
  private clientIdSnapshot?;
15
17
  private deviceId?;
16
18
  constructor(config?: {
@@ -20,7 +22,7 @@ export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<an
20
22
  baseUrl: string;
21
23
  scenario?: string;
22
24
  recordOnMiss?: boolean;
23
- recordResponses?: boolean;
25
+ recordResponses?: boolean | Array<string | RegExp>;
24
26
  strictLaneScenario?: boolean;
25
27
  mirrorRecordedMocksToClient?: boolean;
26
28
  };
@@ -30,6 +32,9 @@ export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<an
30
32
  getUpstreamTlsInsecure?: () => boolean;
31
33
  /** When false, skip `/api/proxy` and call the real URL (devtools-friendly passthrough). */
32
34
  getExplicitProxyScenarioContext?: () => boolean;
35
+ /** When true, tee streaming bodies and capture chunk timelines while recording. */
36
+ getShouldRecordStreams?: () => boolean;
37
+ getStreamRecordCaps?: () => StreamRecordCaps;
33
38
  deviceId?: string;
34
39
  });
35
40
  private resolvedClientLane;
@@ -2,7 +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 core_proxy_1 = require("../core-proxy");
6
5
  function headerContentType(headers) {
7
6
  const contentType = headers.get('content-type');
8
7
  return contentType ? contentType.toLowerCase() : undefined;
@@ -52,11 +51,14 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
52
51
  this.proxyBaseUrl = config?.proxy?.baseUrl;
53
52
  this.proxyScenario = config?.proxy?.scenario;
54
53
  this.proxyRecordOnMiss = config?.proxy?.recordOnMiss;
54
+ // Pass recordResponses through (boolean or array) - envelope handles URL matching
55
55
  this.proxyRecordResponses = config?.proxy?.recordResponses ?? false;
56
56
  this.getClientId = config?.getClientId;
57
57
  this.getStrictLaneScenario = config?.getStrictLaneScenario;
58
58
  this.getUpstreamTlsInsecure = config?.getUpstreamTlsInsecure;
59
59
  this.getExplicitProxyScenarioContext = config?.getExplicitProxyScenarioContext;
60
+ this.getShouldRecordStreams = config?.getShouldRecordStreams;
61
+ this.getStreamRecordCaps = config?.getStreamRecordCaps;
60
62
  this.clientIdSnapshot = config?.clientId;
61
63
  this.deviceId = config?.deviceId;
62
64
  }
@@ -129,7 +131,9 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
129
131
  headers.forEach((value, key) => {
130
132
  headerRecord[key] = value;
131
133
  });
132
- return (0, core_proxy_1.performDashboardProxyRequest)({
134
+ // Dashboard proxy now works in both Node and browser (browser uses fetch, Node uses http)
135
+ const { performDashboardProxyRequest } = require('../core-proxy');
136
+ return performDashboardProxyRequest({
133
137
  proxyBaseUrl: this.proxyBaseUrl,
134
138
  url,
135
139
  method: String(requestConfig.method || 'GET'),
@@ -159,7 +163,48 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
159
163
  headers.set(mockifyer_core_1.MOCKIFYER_DEVICE_ID_HEADER, String(this.deviceId).trim());
160
164
  }
161
165
  const response = await fetchFn(url, requestConfig);
166
+ const responseHeaders = {};
167
+ response.headers.forEach((value, key) => {
168
+ responseHeaders[key] = value;
169
+ });
170
+ const mockifyerTrace = (0, mockifyer_core_1.resolveMockifyerTraceFromHeaders)(responseHeaders);
162
171
  const contentType = response.headers.get('content-type') || '';
172
+ const streamKind = (0, mockifyer_core_1.detectStreamKind)(response.headers);
173
+ const canStream = (0, mockifyer_core_1.supportsReadableStreamBody)() && streamKind != null && response.body != null;
174
+ const shouldRecordStreams = this.getShouldRecordStreams?.() === true;
175
+ // Streaming path: pass the live body through without buffering so the caller
176
+ // is not delayed. When recording, tee and capture chunks in the background.
177
+ if (canStream) {
178
+ const caps = this.getStreamRecordCaps?.() ?? {};
179
+ if (shouldRecordStreams) {
180
+ const teed = (0, mockifyer_core_1.teeResponseBodyForRecording)(response.body);
181
+ if (teed) {
182
+ const recording = (0, mockifyer_core_1.captureReadableStreamChunks)(teed.record, streamKind, caps);
183
+ return {
184
+ data: teed.live,
185
+ status: response.status,
186
+ statusText: response.statusText,
187
+ headers: responseHeaders,
188
+ config,
189
+ mockifyerStreamRecording: recording,
190
+ ...(mockifyerTrace ? { mockifyerTrace } : {}),
191
+ };
192
+ }
193
+ // Tee unavailable — fall through to buffered text() so recording still works.
194
+ }
195
+ else {
196
+ // Not recording: avoid buffering the live stream for the caller.
197
+ return {
198
+ data: response.body,
199
+ status: response.status,
200
+ statusText: response.statusText,
201
+ headers: responseHeaders,
202
+ config,
203
+ ...(mockifyerTrace ? { mockifyerTrace } : {}),
204
+ };
205
+ }
206
+ }
207
+ // Flat path (legacy / React Native without ReadableStream / non-stream responses)
163
208
  const rawText = await response.text();
164
209
  let data = rawText;
165
210
  if (contentType.includes('application/json')) {
@@ -170,11 +215,6 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
170
215
  data = rawText;
171
216
  }
172
217
  }
173
- const responseHeaders = {};
174
- response.headers.forEach((value, key) => {
175
- responseHeaders[key] = value;
176
- });
177
- const mockifyerTrace = (0, mockifyer_core_1.resolveMockifyerTraceFromHeaders)(responseHeaders);
178
218
  return {
179
219
  data,
180
220
  status: response.status,
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Browser implementation for core-proxy - exports browser-compatible dashboard proxy via fetch
3
+ */
4
+ export declare function applyProxyRecordOnMissEnv(config: any): any;
5
+ export declare function mirrorProxyRecordingToClient(): void;
6
+ export { performDashboardProxyRequest } from '@sgedda/mockifyer-core/utils/perform-dashboard-proxy-request';
7
+ export declare function initMockifyerForDashboardProxy(): Promise<never>;
8
+ export declare function initMockifyerForLocalFilesystem(): never;
9
+ export declare function initMockifyerForDashboardProxyClients(): Promise<never>;
10
+ export declare function initMockifyerForLocalFilesystemClients(): never;
11
+ export declare function resolveClientInitFlags(): any;
12
+ export declare function needsSiblingClientSetup(): boolean;
13
+ export declare function syncDualMockifyerControls(): void;
14
+ export declare function pickPrimaryDualMockifyerInstance(_transport: string, _flags: any, result: any): any;
15
+ export declare function loadAxiosSetupMockifyer(): null;
16
+ export declare function loadFetchSetupMockifyer(): null;
17
+ export type InitMockifyerForDashboardProxyOptions = any;
18
+ export type InitMockifyerForLocalFilesystemOptions = any;
19
+ export type DualMockifyerControlSurface = any;
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ /**
3
+ * Browser implementation for core-proxy - exports browser-compatible dashboard proxy via fetch
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.performDashboardProxyRequest = void 0;
7
+ exports.applyProxyRecordOnMissEnv = applyProxyRecordOnMissEnv;
8
+ exports.mirrorProxyRecordingToClient = mirrorProxyRecordingToClient;
9
+ exports.initMockifyerForDashboardProxy = initMockifyerForDashboardProxy;
10
+ exports.initMockifyerForLocalFilesystem = initMockifyerForLocalFilesystem;
11
+ exports.initMockifyerForDashboardProxyClients = initMockifyerForDashboardProxyClients;
12
+ exports.initMockifyerForLocalFilesystemClients = initMockifyerForLocalFilesystemClients;
13
+ exports.resolveClientInitFlags = resolveClientInitFlags;
14
+ exports.needsSiblingClientSetup = needsSiblingClientSetup;
15
+ exports.syncDualMockifyerControls = syncDualMockifyerControls;
16
+ exports.pickPrimaryDualMockifyerInstance = pickPrimaryDualMockifyerInstance;
17
+ exports.loadAxiosSetupMockifyer = loadAxiosSetupMockifyer;
18
+ exports.loadFetchSetupMockifyer = loadFetchSetupMockifyer;
19
+ function applyProxyRecordOnMissEnv(config) {
20
+ return config;
21
+ }
22
+ function mirrorProxyRecordingToClient() {
23
+ // Browser: no-op
24
+ }
25
+ // Export browser implementation of dashboard proxy (uses fetch instead of Node http)
26
+ var perform_dashboard_proxy_request_1 = require("@sgedda/mockifyer-core/utils/perform-dashboard-proxy-request");
27
+ Object.defineProperty(exports, "performDashboardProxyRequest", { enumerable: true, get: function () { return perform_dashboard_proxy_request_1.performDashboardProxyRequest; } });
28
+ function initMockifyerForDashboardProxy() {
29
+ return Promise.reject(new Error('[Mockifyer Browser] Use setupMockifyer from browser entry instead of initMockifyerForDashboardProxy'));
30
+ }
31
+ function initMockifyerForLocalFilesystem() {
32
+ throw new Error('[Mockifyer Browser] Use setupMockifyer from browser entry');
33
+ }
34
+ function initMockifyerForDashboardProxyClients() {
35
+ return Promise.reject(new Error('[Mockifyer Browser] Use setupMockifyer from browser entry instead of initMockifyerForDashboardProxyClients'));
36
+ }
37
+ function initMockifyerForLocalFilesystemClients() {
38
+ throw new Error('[Mockifyer Browser] Use setupMockifyer from browser entry');
39
+ }
40
+ function resolveClientInitFlags() {
41
+ return {};
42
+ }
43
+ function needsSiblingClientSetup() {
44
+ return false;
45
+ }
46
+ function syncDualMockifyerControls() {
47
+ // Browser: no-op
48
+ }
49
+ function pickPrimaryDualMockifyerInstance(_transport, _flags, result) {
50
+ return result.fetch || result.axios;
51
+ }
52
+ function loadAxiosSetupMockifyer() {
53
+ return null;
54
+ }
55
+ function loadFetchSetupMockifyer() {
56
+ return null;
57
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Browser entry for mockifyer-fetch.
3
+ * Avoids statically loading Node built-ins by not re-exporting the full main index barrel.
4
+ */
5
+ import type { MockifyerConfig, MockData, StoredRequest, StoredResponse, HTTPClient, HTTPResponse, DatabaseProvider, DatabaseProviderConfig } from '@sgedda/mockifyer-core';
6
+ export type { MockifyerConfig, MockData, StoredRequest, StoredResponse, HTTPClient, HTTPResponse, DatabaseProvider, DatabaseProviderConfig, };
7
+ export { MemoryProvider, createProvider, } from '@sgedda/mockifyer-core';
8
+ export { FetchHTTPClient } from './clients/fetch-client';
9
+ import { bodyInitForFetchResponse } from './utils/fetch-response-body';
10
+ export { bodyInitForFetchResponse };
11
+ export { resolvePatchedFetchRequest } from './utils/resolve-patched-fetch-request';
12
+ export { canUseDashboardRedisProxy, canUseDashboardCentralProxy, } from './utils/dashboard-redis-health';
13
+ export interface MockifyerInstance extends HTTPClient {
14
+ reloadMockData: (syncFromProject?: boolean) => Promise<void>;
15
+ clearStaleCacheEntries: () => number;
16
+ clearAllMocks: () => Promise<void>;
17
+ setClientId: (lane: string) => void;
18
+ getClientId: () => string | undefined;
19
+ setRecordMode: (enabled: boolean) => void;
20
+ isRecordMode: () => boolean;
21
+ setRecordResponses: (enabled: boolean) => void;
22
+ isRecordResponses: () => boolean;
23
+ enableMockifyer: () => void;
24
+ disableMockifyer: () => void;
25
+ isMockifyerEnabled: () => boolean;
26
+ }
27
+ /**
28
+ * Setup Mockifyer for browser/web with in-memory provider.
29
+ *
30
+ * **Browser-specific constraints:**
31
+ * - Only `memory` provider is supported (filesystem/redis/sqlite need Node.js)
32
+ * - Preload fixtures via `databaseProvider.options.fixtures: MockData[]`
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * import { setupMockifyer } from '@sgedda/mockifyer-fetch';
37
+ * import rates from './mock-data/api.frankfurter.dev/v1/latest.json';
38
+ *
39
+ * const mockifyer = setupMockifyer({
40
+ * mockDataPath: './mock-data',
41
+ * databaseProvider: {
42
+ * type: 'memory',
43
+ * options: {
44
+ * fixtures: [rates]
45
+ * }
46
+ * },
47
+ * recordMode: false,
48
+ * failOnMissingMock: true,
49
+ * useGlobalFetch: true
50
+ * });
51
+ * ```
52
+ */
53
+ export declare function setupMockifyer(config: MockifyerConfig): MockifyerInstance;
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ /**
3
+ * Browser entry for mockifyer-fetch.
4
+ * Avoids statically loading Node built-ins by not re-exporting the full main index barrel.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.canUseDashboardCentralProxy = exports.canUseDashboardRedisProxy = exports.resolvePatchedFetchRequest = exports.bodyInitForFetchResponse = exports.FetchHTTPClient = exports.createProvider = exports.MemoryProvider = void 0;
8
+ exports.setupMockifyer = setupMockifyer;
9
+ var mockifyer_core_1 = require("@sgedda/mockifyer-core");
10
+ Object.defineProperty(exports, "MemoryProvider", { enumerable: true, get: function () { return mockifyer_core_1.MemoryProvider; } });
11
+ Object.defineProperty(exports, "createProvider", { enumerable: true, get: function () { return mockifyer_core_1.createProvider; } });
12
+ // Re-export browser-safe fetch utilities
13
+ var fetch_client_1 = require("./clients/fetch-client");
14
+ Object.defineProperty(exports, "FetchHTTPClient", { enumerable: true, get: function () { return fetch_client_1.FetchHTTPClient; } });
15
+ const fetch_response_body_1 = require("./utils/fetch-response-body");
16
+ Object.defineProperty(exports, "bodyInitForFetchResponse", { enumerable: true, get: function () { return fetch_response_body_1.bodyInitForFetchResponse; } });
17
+ var resolve_patched_fetch_request_1 = require("./utils/resolve-patched-fetch-request");
18
+ Object.defineProperty(exports, "resolvePatchedFetchRequest", { enumerable: true, get: function () { return resolve_patched_fetch_request_1.resolvePatchedFetchRequest; } });
19
+ var dashboard_redis_health_1 = require("./utils/dashboard-redis-health");
20
+ Object.defineProperty(exports, "canUseDashboardRedisProxy", { enumerable: true, get: function () { return dashboard_redis_health_1.canUseDashboardRedisProxy; } });
21
+ Object.defineProperty(exports, "canUseDashboardCentralProxy", { enumerable: true, get: function () { return dashboard_redis_health_1.canUseDashboardCentralProxy; } });
22
+ // Import MockifyerClass and browser capabilities
23
+ const mockifyer_class_1 = require("./mockifyer-class");
24
+ const node_capabilities_browser_1 = require("./node-capabilities.browser");
25
+ /**
26
+ * Setup Mockifyer for browser/web with in-memory provider.
27
+ *
28
+ * **Browser-specific constraints:**
29
+ * - Only `memory` provider is supported (filesystem/redis/sqlite need Node.js)
30
+ * - Preload fixtures via `databaseProvider.options.fixtures: MockData[]`
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * import { setupMockifyer } from '@sgedda/mockifyer-fetch';
35
+ * import rates from './mock-data/api.frankfurter.dev/v1/latest.json';
36
+ *
37
+ * const mockifyer = setupMockifyer({
38
+ * mockDataPath: './mock-data',
39
+ * databaseProvider: {
40
+ * type: 'memory',
41
+ * options: {
42
+ * fixtures: [rates]
43
+ * }
44
+ * },
45
+ * recordMode: false,
46
+ * failOnMissingMock: true,
47
+ * useGlobalFetch: true
48
+ * });
49
+ * ```
50
+ */
51
+ function setupMockifyer(config) {
52
+ // Validate browser-safe config
53
+ if (config.databaseProvider && config.databaseProvider.type && config.databaseProvider.type !== 'memory') {
54
+ throw new Error(`[Mockifyer Browser] Provider '${config.databaseProvider.type}' requires Node.js (fs/path/crypto). ` +
55
+ `Use databaseProvider: { type: 'memory', options: { fixtures: [...] } } in browser builds.`);
56
+ }
57
+ if (!config.databaseProvider) {
58
+ console.warn('[Mockifyer Browser] No databaseProvider configured. Falling back to memory provider. ' +
59
+ 'Preload fixtures via databaseProvider: { type: "memory", options: { fixtures: [...] } }');
60
+ config.databaseProvider = { type: 'memory', options: {} };
61
+ }
62
+ // Create with browser capabilities (no Node fs/path/crypto)
63
+ const mockifyer = new mockifyer_class_1.MockifyerClass(config, node_capabilities_browser_1.nodeCapabilities);
64
+ // Get HTTP client
65
+ const httpClient = mockifyer.getHTTPClient();
66
+ // Patch global fetch if useGlobalFetch is true
67
+ if (config.useGlobalFetch) {
68
+ const originalFetch = globalThis.fetch;
69
+ const mockifyerInstance = mockifyer;
70
+ // Store original fetch on the http client so it can be used for unmocked requests
71
+ httpClient._originalFetch = originalFetch;
72
+ globalThis.fetch = async function (input, init) {
73
+ if (!mockifyerInstance.isMockifyerEnabled()) {
74
+ return await originalFetch(input, init);
75
+ }
76
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
77
+ const method = (init?.method || 'GET').toUpperCase();
78
+ // Perform the request through mockifyer
79
+ const response = await httpClient.request({
80
+ method,
81
+ url,
82
+ headers: init?.headers || {},
83
+ data: init?.body,
84
+ });
85
+ // Convert mockifyer response to fetch Response (rebuild stream when present)
86
+ return new Response((0, fetch_response_body_1.bodyInitForFetchResponse)(response.status, response.data, {
87
+ stream: response.mockifyerStoredStream,
88
+ streamReplay: config.streamReplay,
89
+ }), {
90
+ status: response.status,
91
+ statusText: response.statusText || '',
92
+ headers: new Headers(response.headers || {})
93
+ });
94
+ };
95
+ }
96
+ // Return httpClient extended with mockifyer methods
97
+ const extendedClient = httpClient;
98
+ extendedClient.reloadMockData = (syncFromProject) => mockifyer.reloadMockData(syncFromProject);
99
+ extendedClient.clearStaleCacheEntries = () => mockifyer.clearStaleCacheEntries();
100
+ extendedClient.clearAllMocks = () => mockifyer.clearAllMocks();
101
+ extendedClient.setClientId = (lane) => mockifyer.setClientId(lane);
102
+ extendedClient.getClientId = () => mockifyer.getClientId();
103
+ extendedClient.setRecordMode = (enabled) => mockifyer.setRecordMode(enabled);
104
+ extendedClient.isRecordMode = () => mockifyer.isRecordMode();
105
+ extendedClient.setRecordResponses = (enabled) => mockifyer.setRecordResponses(enabled);
106
+ extendedClient.isRecordResponses = () => mockifyer.isRecordResponses();
107
+ extendedClient.enableMockifyer = () => mockifyer.enableMockifyer();
108
+ extendedClient.disableMockifyer = () => mockifyer.disableMockifyer();
109
+ extendedClient.isMockifyerEnabled = () => mockifyer.isMockifyerEnabled();
110
+ return extendedClient;
111
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { MockifyerConfig, HTTPClient } from '@sgedda/mockifyer-core';
2
2
  import { type InitMockifyerForDashboardProxyOptions, type InitMockifyerForLocalFilesystemOptions } from './core-proxy';
3
+ import { MockifyerClass } from './mockifyer-class';
3
4
  export interface MockifyerInstance extends HTTPClient {
4
5
  reloadMockData: (syncFromProject?: boolean) => Promise<void>;
5
6
  clearStaleCacheEntries: () => number;
@@ -30,4 +31,5 @@ export declare function initMockifyerForDashboardProxy(options: InitMockifyerFor
30
31
  export declare function initMockifyerForLocalFilesystem(options?: InitMockifyerForLocalFilesystemOptions): MockifyerInstance;
31
32
  /** Shared with {@link setupMockifyerForReactNative} strict-proxy branching. */
32
33
  export { canUseDashboardRedisProxy, canUseDashboardCentralProxy, } from './utils/dashboard-redis-health';
34
+ export { MockifyerClass };
33
35
  export * from '@sgedda/mockifyer-core';