@sgedda/mockifyer-fetch 1.8.104 → 1.8.107
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 +155 -0
- package/dist/clients/fetch-client.d.ts +1 -1
- package/dist/clients/fetch-client.js +4 -2
- package/dist/core-proxy.browser.d.ts +19 -0
- package/dist/core-proxy.browser.js +57 -0
- package/dist/index.browser.d.ts +52 -0
- package/dist/index.browser.js +107 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +32 -1540
- package/dist/metro-sync-middleware.js +2 -56
- package/dist/mockifyer-class.d.ts +123 -0
- package/dist/mockifyer-class.js +1306 -0
- package/dist/node-capabilities.browser.d.ts +6 -0
- package/dist/node-capabilities.browser.js +110 -0
- package/dist/node-capabilities.d.ts +51 -0
- package/dist/node-capabilities.js +6 -0
- package/dist/node-capabilities.node.d.ts +6 -0
- package/dist/node-capabilities.node.js +31 -0
- package/dist/react-native.js +2 -1
- package/package.json +14 -3
- package/src/clients/fetch-client.ts +6 -3
- package/src/core-proxy.browser.ts +62 -0
- package/src/index.browser.ts +166 -0
- package/src/index.ts +36 -1887
- package/src/metro-sync-middleware.ts +5 -56
- package/src/mockifyer-class.ts +1700 -0
- package/src/node-capabilities.browser.ts +123 -0
- package/src/node-capabilities.node.ts +40 -0
- package/src/node-capabilities.ts +60 -0
- package/src/react-native.ts +2 -1
package/README.md
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
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
|
+
## Browser & Expo Web Usage
|
|
27
|
+
|
|
28
|
+
Mockifyer works in browsers and Expo web builds with the memory provider and preloaded fixtures.
|
|
29
|
+
|
|
30
|
+
### Requirements
|
|
31
|
+
|
|
32
|
+
- Only the `memory` provider is supported (no filesystem/Redis/SQLite in browsers)
|
|
33
|
+
- Fixtures must be preloaded via `databaseProvider.options.fixtures`
|
|
34
|
+
- Uses Web Crypto API for hashing (or pure-JS fallback)
|
|
35
|
+
|
|
36
|
+
### Browser Example
|
|
37
|
+
|
|
38
|
+
```typescript
|
|
39
|
+
import { setupMockifyer } from '@sgedda/mockifyer-fetch';
|
|
40
|
+
import rates from './fixtures/api.frankfurter.dev/v1/latest.json';
|
|
41
|
+
|
|
42
|
+
const mockifyer = setupMockifyer({
|
|
43
|
+
mockDataPath: './fixtures',
|
|
44
|
+
databaseProvider: {
|
|
45
|
+
type: 'memory',
|
|
46
|
+
options: {
|
|
47
|
+
fixtures: [rates] // Preload your mock data
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
recordMode: false,
|
|
51
|
+
failOnMissingMock: true, // Recommended for testing
|
|
52
|
+
useGlobalFetch: true // Patch global fetch
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// Fetch will use the preloaded mock
|
|
56
|
+
const response = await fetch('https://api.frankfurter.dev/v1/latest');
|
|
57
|
+
const data = await response.json();
|
|
58
|
+
console.log(data); // Returns your mock data
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Expo Web Example
|
|
62
|
+
|
|
63
|
+
```javascript
|
|
64
|
+
// App.js
|
|
65
|
+
import { setupMockifyer } from '@sgedda/mockifyer-fetch';
|
|
66
|
+
import frankfurterRates from './fixtures/frankfurter-rates.json';
|
|
67
|
+
|
|
68
|
+
export default function App() {
|
|
69
|
+
useEffect(() => {
|
|
70
|
+
// Initialize mockifyer on mount
|
|
71
|
+
setupMockifyer({
|
|
72
|
+
mockDataPath: './fixtures',
|
|
73
|
+
databaseProvider: {
|
|
74
|
+
type: 'memory',
|
|
75
|
+
options: {
|
|
76
|
+
fixtures: [frankfurterRates]
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
recordMode: false,
|
|
80
|
+
failOnMissingMock: true,
|
|
81
|
+
useGlobalFetch: true
|
|
82
|
+
});
|
|
83
|
+
}, []);
|
|
84
|
+
|
|
85
|
+
const fetchData = async () => {
|
|
86
|
+
const response = await fetch('https://api.frankfurter.dev/v1/latest');
|
|
87
|
+
const data = await response.json();
|
|
88
|
+
console.log(data); // Returns your mock data
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
// ... rest of your component
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Fixture Format
|
|
96
|
+
|
|
97
|
+
Fixtures are JSON files with this structure:
|
|
98
|
+
|
|
99
|
+
```json
|
|
100
|
+
{
|
|
101
|
+
"request": {
|
|
102
|
+
"method": "GET",
|
|
103
|
+
"url": "https://api.example.com/endpoint",
|
|
104
|
+
"headers": {},
|
|
105
|
+
"queryParams": {}
|
|
106
|
+
},
|
|
107
|
+
"response": {
|
|
108
|
+
"status": 200,
|
|
109
|
+
"headers": {
|
|
110
|
+
"content-type": "application/json"
|
|
111
|
+
},
|
|
112
|
+
"data": {
|
|
113
|
+
"result": "your mock data here"
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
"timestamp": "2024-01-15T10:00:00.000Z"
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Bundler Configuration
|
|
121
|
+
|
|
122
|
+
Mockifyer uses package.json `browser` field mappings to automatically resolve browser-safe modules. Modern bundlers (Metro, Vite, webpack, esbuild) honor these mappings automatically.
|
|
123
|
+
|
|
124
|
+
**Metro (Expo)**:
|
|
125
|
+
- Works out of the box with `npx expo export --platform web`
|
|
126
|
+
- Uses the browser entry point automatically
|
|
127
|
+
|
|
128
|
+
**Vite**:
|
|
129
|
+
- Add `conditions: ['browser']` to your config if needed
|
|
130
|
+
|
|
131
|
+
**webpack**:
|
|
132
|
+
- The `browser` field is respected by default
|
|
133
|
+
|
|
134
|
+
### Browser Compatibility
|
|
135
|
+
|
|
136
|
+
- ✅ Chrome, Firefox, Safari, Edge (modern versions)
|
|
137
|
+
- ✅ Expo web (Metro bundler)
|
|
138
|
+
- ✅ Vite, webpack, esbuild (with `platform: 'browser'`)
|
|
139
|
+
- ❌ Node.js built-ins are not available (fs, path, crypto → Web Crypto)
|
|
140
|
+
- ❌ Redis, SQLite providers not supported (use `memory` only)
|
|
141
|
+
|
|
142
|
+
### Limitations in Browser
|
|
143
|
+
|
|
144
|
+
- No filesystem access (no recording, no file-based mocks)
|
|
145
|
+
- No Redis/SQLite support
|
|
146
|
+
- All fixtures must be preloaded at initialization
|
|
147
|
+
- Request correlation is simplified (header-only)
|
|
148
|
+
- No Atlas HTML generation
|
|
149
|
+
- No screenshot capture
|
|
150
|
+
|
|
151
|
+
### See Also
|
|
152
|
+
|
|
153
|
+
- [@sgedda/mockifyer-core](../mockifyer-core/README.md) - Core types and providers
|
|
154
|
+
- [Full documentation](https://mockifyer.dev)
|
|
155
|
+
- [GitHub repository](https://github.com/sgedda/mockifyer)
|
|
@@ -20,7 +20,7 @@ export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<an
|
|
|
20
20
|
baseUrl: string;
|
|
21
21
|
scenario?: string;
|
|
22
22
|
recordOnMiss?: boolean;
|
|
23
|
-
recordResponses?: boolean
|
|
23
|
+
recordResponses?: boolean | Array<string | RegExp>;
|
|
24
24
|
strictLaneScenario?: boolean;
|
|
25
25
|
mirrorRecordedMocksToClient?: boolean;
|
|
26
26
|
};
|
|
@@ -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,6 +51,7 @@ 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;
|
|
@@ -129,7 +129,9 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
|
|
|
129
129
|
headers.forEach((value, key) => {
|
|
130
130
|
headerRecord[key] = value;
|
|
131
131
|
});
|
|
132
|
-
|
|
132
|
+
// Dashboard proxy now works in both Node and browser (browser uses fetch, Node uses http)
|
|
133
|
+
const { performDashboardProxyRequest } = require('../core-proxy');
|
|
134
|
+
return performDashboardProxyRequest({
|
|
133
135
|
proxyBaseUrl: this.proxyBaseUrl,
|
|
134
136
|
url,
|
|
135
137
|
method: String(requestConfig.method || 'GET'),
|
|
@@ -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,52 @@
|
|
|
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
|
+
export { bodyInitForFetchResponse } from './utils/fetch-response-body';
|
|
10
|
+
export { resolvePatchedFetchRequest } from './utils/resolve-patched-fetch-request';
|
|
11
|
+
export { canUseDashboardRedisProxy, canUseDashboardCentralProxy, } from './utils/dashboard-redis-health';
|
|
12
|
+
export interface MockifyerInstance extends HTTPClient {
|
|
13
|
+
reloadMockData: (syncFromProject?: boolean) => Promise<void>;
|
|
14
|
+
clearStaleCacheEntries: () => number;
|
|
15
|
+
clearAllMocks: () => Promise<void>;
|
|
16
|
+
setClientId: (lane: string) => void;
|
|
17
|
+
getClientId: () => string | undefined;
|
|
18
|
+
setRecordMode: (enabled: boolean) => void;
|
|
19
|
+
isRecordMode: () => boolean;
|
|
20
|
+
setRecordResponses: (enabled: boolean) => void;
|
|
21
|
+
isRecordResponses: () => boolean;
|
|
22
|
+
enableMockifyer: () => void;
|
|
23
|
+
disableMockifyer: () => void;
|
|
24
|
+
isMockifyerEnabled: () => boolean;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Setup Mockifyer for browser/web with in-memory provider.
|
|
28
|
+
*
|
|
29
|
+
* **Browser-specific constraints:**
|
|
30
|
+
* - Only `memory` provider is supported (filesystem/redis/sqlite need Node.js)
|
|
31
|
+
* - Preload fixtures via `databaseProvider.options.fixtures: MockData[]`
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```ts
|
|
35
|
+
* import { setupMockifyer } from '@sgedda/mockifyer-fetch';
|
|
36
|
+
* import rates from './mock-data/api.frankfurter.dev/v1/latest.json';
|
|
37
|
+
*
|
|
38
|
+
* const mockifyer = setupMockifyer({
|
|
39
|
+
* mockDataPath: './mock-data',
|
|
40
|
+
* databaseProvider: {
|
|
41
|
+
* type: 'memory',
|
|
42
|
+
* options: {
|
|
43
|
+
* fixtures: [rates]
|
|
44
|
+
* }
|
|
45
|
+
* },
|
|
46
|
+
* recordMode: false,
|
|
47
|
+
* failOnMissingMock: true,
|
|
48
|
+
* useGlobalFetch: true
|
|
49
|
+
* });
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
export declare function setupMockifyer(config: MockifyerConfig): MockifyerInstance;
|
|
@@ -0,0 +1,107 @@
|
|
|
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
|
+
var 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
|
|
86
|
+
return new Response(typeof response.data === 'string' ? response.data : JSON.stringify(response.data), {
|
|
87
|
+
status: response.status,
|
|
88
|
+
headers: new Headers(response.headers || {})
|
|
89
|
+
});
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
// Return httpClient extended with mockifyer methods
|
|
93
|
+
const extendedClient = httpClient;
|
|
94
|
+
extendedClient.reloadMockData = (syncFromProject) => mockifyer.reloadMockData(syncFromProject);
|
|
95
|
+
extendedClient.clearStaleCacheEntries = () => mockifyer.clearStaleCacheEntries();
|
|
96
|
+
extendedClient.clearAllMocks = () => mockifyer.clearAllMocks();
|
|
97
|
+
extendedClient.setClientId = (lane) => mockifyer.setClientId(lane);
|
|
98
|
+
extendedClient.getClientId = () => mockifyer.getClientId();
|
|
99
|
+
extendedClient.setRecordMode = (enabled) => mockifyer.setRecordMode(enabled);
|
|
100
|
+
extendedClient.isRecordMode = () => mockifyer.isRecordMode();
|
|
101
|
+
extendedClient.setRecordResponses = (enabled) => mockifyer.setRecordResponses(enabled);
|
|
102
|
+
extendedClient.isRecordResponses = () => mockifyer.isRecordResponses();
|
|
103
|
+
extendedClient.enableMockifyer = () => mockifyer.enableMockifyer();
|
|
104
|
+
extendedClient.disableMockifyer = () => mockifyer.disableMockifyer();
|
|
105
|
+
extendedClient.isMockifyerEnabled = () => mockifyer.isMockifyerEnabled();
|
|
106
|
+
return extendedClient;
|
|
107
|
+
}
|
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';
|