@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.
- package/dist/clients/fetch-client.d.ts +12 -3
- package/dist/clients/fetch-client.js +73 -17
- package/dist/index.d.ts +59 -1
- package/dist/index.js +484 -66
- package/dist/metro-config.js +24 -5
- package/dist/metro-sync-middleware.js +51 -1
- package/dist/react-native.d.ts +35 -0
- package/dist/react-native.js +119 -44
- package/dist/utils/dashboard-redis-health.d.ts +19 -0
- package/dist/utils/dashboard-redis-health.js +49 -0
- package/package.json +14 -2
- package/src/clients/fetch-client.ts +142 -27
- package/src/index.ts +691 -86
- package/src/metro-config.ts +28 -5
- package/src/metro-sync-middleware.ts +67 -1
- package/src/react-native.ts +181 -60
- package/src/utils/dashboard-redis-health.ts +58 -0
package/src/index.ts
CHANGED
|
@@ -36,19 +36,67 @@ import {
|
|
|
36
36
|
prepareMockResponseBody,
|
|
37
37
|
getCurrentDate,
|
|
38
38
|
shouldExcludeUrl,
|
|
39
|
+
resolveRecordingExclusions,
|
|
40
|
+
shouldExcludeRecording,
|
|
39
41
|
mockPassesThroughToRealApi,
|
|
42
|
+
mockShouldServeStoredBody,
|
|
43
|
+
mockShouldBeIncludedInRequestMatch,
|
|
44
|
+
buildClientResponseFromLiveCapture,
|
|
45
|
+
buildMockDataAfterLiveCapture,
|
|
46
|
+
resolveShouldPersistLiveCapture,
|
|
47
|
+
resolveMockRecordingSaveDecision,
|
|
48
|
+
applyRecordingPassthroughFlag,
|
|
40
49
|
resolveClientId,
|
|
50
|
+
resolveExplicitClientIdOnly,
|
|
51
|
+
resolveProxyStrictLaneScenario,
|
|
41
52
|
registerMockifyerInstance,
|
|
53
|
+
logMockifyerInitSummary,
|
|
42
54
|
tryGetClientIdFromLaunchArguments,
|
|
43
55
|
MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
|
|
44
56
|
resolveActivationMode,
|
|
45
57
|
shouldApplyMockifyer,
|
|
46
58
|
isExplicitProxyScenarioContext,
|
|
59
|
+
parseProxyRecordOnMissEnv,
|
|
60
|
+
newRecordingUsesAlwaysUseRealApi,
|
|
61
|
+
shouldBlockLocalMockRecording,
|
|
62
|
+
resolveStrictScenarioResolution,
|
|
47
63
|
type MockifyerActivationMode,
|
|
64
|
+
emitMockifyerNetworkEvent,
|
|
65
|
+
networkEventHashFromRequestKey,
|
|
66
|
+
resolveRecordResponses,
|
|
67
|
+
applyOutboundRequestCorrelation,
|
|
68
|
+
type RequestCorrelationContext,
|
|
69
|
+
installNodeInboundRequestCorrelationCapture,
|
|
48
70
|
} from '@sgedda/mockifyer-core';
|
|
49
71
|
import { logger, setLogLevel } from '@sgedda/mockifyer-core';
|
|
50
72
|
|
|
51
73
|
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
|
+
}
|
|
52
100
|
|
|
53
101
|
class MockifyerClass {
|
|
54
102
|
private config: MockifyerConfig;
|
|
@@ -64,6 +112,42 @@ class MockifyerClass {
|
|
|
64
112
|
private testGenerator?: TestGenerator;
|
|
65
113
|
private readonly activationMode: MockifyerActivationMode;
|
|
66
114
|
|
|
115
|
+
/** Best-effort dashboard network log (skipped when traffic goes through `proxy.baseUrl`). */
|
|
116
|
+
private logNetworkEvent(
|
|
117
|
+
partial: Parameters<typeof emitMockifyerNetworkEvent>[0]['event'] & { transport?: 'fetch' },
|
|
118
|
+
correlation?: RequestCorrelationContext
|
|
119
|
+
): void {
|
|
120
|
+
if (this.config.proxy?.baseUrl) return;
|
|
121
|
+
const scenario =
|
|
122
|
+
this.config.proxy?.scenario?.trim() ||
|
|
123
|
+
getCurrentScenario(this.config.mockDataPath);
|
|
124
|
+
emitMockifyerNetworkEvent({
|
|
125
|
+
config: this.config,
|
|
126
|
+
scenario,
|
|
127
|
+
clientId: this.config.clientId,
|
|
128
|
+
event: {
|
|
129
|
+
...partial,
|
|
130
|
+
transport: partial.transport ?? 'fetch',
|
|
131
|
+
requestId: correlation?.requestId ?? partial.requestId,
|
|
132
|
+
parentRequestId: correlation?.parentRequestId ?? partial.parentRequestId,
|
|
133
|
+
},
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private stashRequestCorrelation(config: unknown, correlation: RequestCorrelationContext): void {
|
|
138
|
+
(config as { __mockifyer_requestId?: string; __mockifyer_parentRequestId?: string }).__mockifyer_requestId =
|
|
139
|
+
correlation.requestId;
|
|
140
|
+
(config as { __mockifyer_parentRequestId?: string }).__mockifyer_parentRequestId =
|
|
141
|
+
correlation.parentRequestId;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
private readRequestCorrelation(config: unknown): RequestCorrelationContext | undefined {
|
|
145
|
+
const requestId = (config as { __mockifyer_requestId?: string }).__mockifyer_requestId;
|
|
146
|
+
if (!requestId) return undefined;
|
|
147
|
+
const parentRequestId = (config as { __mockifyer_parentRequestId?: string }).__mockifyer_parentRequestId;
|
|
148
|
+
return parentRequestId ? { requestId, parentRequestId } : { requestId };
|
|
149
|
+
}
|
|
150
|
+
|
|
67
151
|
constructor(config: MockifyerConfig) {
|
|
68
152
|
// Validate database provider - filesystem, expo-filesystem, hybrid, and memory are supported
|
|
69
153
|
if (config.databaseProvider && config.databaseProvider.type) {
|
|
@@ -129,14 +213,25 @@ class MockifyerClass {
|
|
|
129
213
|
// Launch arg wins over MOCKIFYER_CLIENT_ID / config.clientId when present (E2E).
|
|
130
214
|
if (launchClientId) {
|
|
131
215
|
this.config.clientId = launchClientId;
|
|
216
|
+
} else if (
|
|
217
|
+
resolveStrictScenarioResolution(this.config) &&
|
|
218
|
+
Boolean(this.config.proxy?.baseUrl?.trim())
|
|
219
|
+
) {
|
|
220
|
+
// Strict proxy: no auto lane until explicit clientId / setClientId (devtools show real URLs).
|
|
221
|
+
this.config.clientId = resolveExplicitClientIdOnly(this.config);
|
|
132
222
|
} else {
|
|
133
223
|
this.config.clientId = resolveClientId(this.config);
|
|
134
224
|
}
|
|
135
|
-
logger.info(`[Mockifyer-Fetch] clientId: ${this.config.clientId}`);
|
|
136
|
-
|
|
137
225
|
this.activationMode = resolveActivationMode(this.config);
|
|
138
|
-
|
|
139
|
-
|
|
226
|
+
|
|
227
|
+
if (this.config.proxy?.baseUrl && this.config.proxy.mirrorRecordedMocksToClient === undefined) {
|
|
228
|
+
const raw =
|
|
229
|
+
typeof process !== 'undefined'
|
|
230
|
+
? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
|
|
231
|
+
: '';
|
|
232
|
+
if (raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on') {
|
|
233
|
+
this.config.proxy = { ...this.config.proxy, mirrorRecordedMocksToClient: true };
|
|
234
|
+
}
|
|
140
235
|
}
|
|
141
236
|
|
|
142
237
|
// Initialize test generator if test generation is enabled
|
|
@@ -170,12 +265,14 @@ class MockifyerClass {
|
|
|
170
265
|
}
|
|
171
266
|
|
|
172
267
|
// Create fetch HTTP client
|
|
173
|
-
this.httpClient = new FetchHTTPClient({
|
|
174
|
-
baseUrl: config.baseUrl,
|
|
268
|
+
this.httpClient = new FetchHTTPClient({
|
|
269
|
+
baseUrl: config.baseUrl,
|
|
175
270
|
defaultHeaders: config.defaultHeaders,
|
|
176
271
|
proxy: config.proxy,
|
|
177
272
|
clientId: this.config.clientId,
|
|
178
273
|
getClientId: () => this.config.clientId,
|
|
274
|
+
getStrictLaneScenario: () => resolveProxyStrictLaneScenario(this.config),
|
|
275
|
+
getExplicitProxyScenarioContext: () => isExplicitProxyScenarioContext(this.config),
|
|
179
276
|
deviceId: (this.config as any).deviceId,
|
|
180
277
|
});
|
|
181
278
|
|
|
@@ -187,6 +284,11 @@ class MockifyerClass {
|
|
|
187
284
|
|
|
188
285
|
// Set up response interceptor to save responses when recordMode is enabled
|
|
189
286
|
this.setupResponseInterceptor();
|
|
287
|
+
|
|
288
|
+
logMockifyerInitSummary(this.config, {
|
|
289
|
+
runtimeMode: this.config.runtimeMode,
|
|
290
|
+
headline: this.config.initLog?.headline,
|
|
291
|
+
});
|
|
190
292
|
}
|
|
191
293
|
|
|
192
294
|
private ensureMockDataDirectory(): void {
|
|
@@ -203,7 +305,16 @@ class MockifyerClass {
|
|
|
203
305
|
return generateRequestKeyUtil(request);
|
|
204
306
|
}
|
|
205
307
|
|
|
206
|
-
|
|
308
|
+
/** When set, mock resolution happens on the dashboard `/api/proxy` (Redis/disk), not local `mock-data`. */
|
|
309
|
+
private usesDashboardProxy(): boolean {
|
|
310
|
+
const baseUrl = this.config.proxy?.baseUrl;
|
|
311
|
+
return typeof baseUrl === 'string' && baseUrl.trim().length > 0;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
private async findBestMatchingMock(
|
|
315
|
+
request: StoredRequest,
|
|
316
|
+
options?: { includePassthroughMocks?: boolean }
|
|
317
|
+
): Promise<CachedMockData | undefined> {
|
|
207
318
|
// CRITICAL: Never try to match sync endpoint requests - they should never be mocked
|
|
208
319
|
const requestUrl = request?.url || '';
|
|
209
320
|
if (requestUrl.includes('/mockifyer-save') ||
|
|
@@ -223,13 +334,16 @@ class MockifyerClass {
|
|
|
223
334
|
|
|
224
335
|
// Use database provider if available, otherwise fallback to filesystem
|
|
225
336
|
if (this.databaseProvider) {
|
|
226
|
-
return await this.findBestMatchingMockFromProvider(request);
|
|
337
|
+
return await this.findBestMatchingMockFromProvider(request, options);
|
|
227
338
|
}
|
|
228
339
|
// Fallback to Node.js filesystem
|
|
229
|
-
return this.findBestMatchingMockFromFiles(request);
|
|
340
|
+
return this.findBestMatchingMockFromFiles(request, options);
|
|
230
341
|
}
|
|
231
342
|
|
|
232
|
-
private async findBestMatchingMockFromProvider(
|
|
343
|
+
private async findBestMatchingMockFromProvider(
|
|
344
|
+
request: StoredRequest,
|
|
345
|
+
options?: { includePassthroughMocks?: boolean }
|
|
346
|
+
): Promise<CachedMockData | undefined> {
|
|
233
347
|
if (!this.databaseProvider) {
|
|
234
348
|
return undefined;
|
|
235
349
|
}
|
|
@@ -252,7 +366,7 @@ class MockifyerClass {
|
|
|
252
366
|
}
|
|
253
367
|
|
|
254
368
|
// Try exact match first
|
|
255
|
-
const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey);
|
|
369
|
+
const exactMatch = await this.databaseProvider.findExactMatch(request, requestKey, options);
|
|
256
370
|
if (exactMatch) {
|
|
257
371
|
return exactMatch;
|
|
258
372
|
}
|
|
@@ -269,7 +383,11 @@ class MockifyerClass {
|
|
|
269
383
|
return undefined;
|
|
270
384
|
}
|
|
271
385
|
|
|
272
|
-
private findBestMatchingMockFromFiles(
|
|
386
|
+
private findBestMatchingMockFromFiles(
|
|
387
|
+
request: StoredRequest,
|
|
388
|
+
options?: { includePassthroughMocks?: boolean }
|
|
389
|
+
): CachedMockData | undefined {
|
|
390
|
+
const includePassthroughMocks = options?.includePassthroughMocks === true;
|
|
273
391
|
// Only use fs if available (Node.js environment)
|
|
274
392
|
// This method should never be called when using a database provider
|
|
275
393
|
if (!fs || !path) {
|
|
@@ -310,7 +428,7 @@ class MockifyerClass {
|
|
|
310
428
|
const mockKey = this.generateRequestKey(mockData.request);
|
|
311
429
|
|
|
312
430
|
if (mockKey === requestKey) {
|
|
313
|
-
if (
|
|
431
|
+
if (mockShouldBeIncludedInRequestMatch(mockData, { includePassthroughMocks })) {
|
|
314
432
|
exactMatch = { mockData, filename: file, filePath };
|
|
315
433
|
break;
|
|
316
434
|
}
|
|
@@ -435,6 +553,7 @@ class MockifyerClass {
|
|
|
435
553
|
useProxyLane: { proxyBaseUrl: this.config.proxy?.baseUrl, resolvedClientId: this.config.clientId },
|
|
436
554
|
})
|
|
437
555
|
) {
|
|
556
|
+
applyOutboundRequestCorrelation(config);
|
|
438
557
|
(config as any).__mockifyer_bypass = true;
|
|
439
558
|
return config;
|
|
440
559
|
}
|
|
@@ -447,6 +566,9 @@ class MockifyerClass {
|
|
|
447
566
|
return config;
|
|
448
567
|
}
|
|
449
568
|
|
|
569
|
+
const correlation = applyOutboundRequestCorrelation(config);
|
|
570
|
+
this.stashRequestCorrelation(config, correlation);
|
|
571
|
+
|
|
450
572
|
// Normalize empty params: treat {} the same as undefined for consistent matching
|
|
451
573
|
const rawParams = config.params || {};
|
|
452
574
|
const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
|
|
@@ -468,6 +590,12 @@ class MockifyerClass {
|
|
|
468
590
|
(config as any).__mockifyer_requestKey = requestKey;
|
|
469
591
|
// Store request start time for duration calculation
|
|
470
592
|
(config as any).__mockifyer_startTime = Date.now();
|
|
593
|
+
|
|
594
|
+
// Dashboard proxy owns mock hits (Redis + server-side disk fallback). Do not short-circuit
|
|
595
|
+
// from local mock-data while proxy.baseUrl is configured — that bypasses /api/proxy entirely.
|
|
596
|
+
if (this.usesDashboardProxy()) {
|
|
597
|
+
return config;
|
|
598
|
+
}
|
|
471
599
|
|
|
472
600
|
const cachedMock = await this.findBestMatchingMock(request);
|
|
473
601
|
|
|
@@ -475,31 +603,49 @@ class MockifyerClass {
|
|
|
475
603
|
|
|
476
604
|
if (cachedMock) {
|
|
477
605
|
const { mockData, filename, filePath } = cachedMock;
|
|
606
|
+
if (mockShouldServeStoredBody(mockData)) {
|
|
607
|
+
logger.info(
|
|
608
|
+
`[Mockifyer-Fetch] Mock hit: ${request.method} ${request.url} → ${filename}` +
|
|
609
|
+
(filePath ? ` (${filePath})` : '')
|
|
610
|
+
);
|
|
611
|
+
this.logNetworkEvent(
|
|
612
|
+
{
|
|
613
|
+
method: (request.method || 'GET').toUpperCase(),
|
|
614
|
+
url: request.url,
|
|
615
|
+
source: 'mock-hit',
|
|
616
|
+
status: mockData.response.status,
|
|
617
|
+
requestHash: networkEventHashFromRequestKey(requestKey),
|
|
618
|
+
},
|
|
619
|
+
correlation
|
|
620
|
+
);
|
|
621
|
+
const responseHeaders = {
|
|
622
|
+
...mockData.response.headers,
|
|
623
|
+
'x-mockifyer': 'true',
|
|
624
|
+
'x-mockifyer-timestamp': mockData.timestamp,
|
|
625
|
+
'x-mockifyer-filename': filename,
|
|
626
|
+
'x-mockifyer-filepath': filePath
|
|
627
|
+
};
|
|
628
|
+
|
|
629
|
+
const mockResponse = {
|
|
630
|
+
data: prepareMockResponseBody(mockData, getCurrentDate),
|
|
631
|
+
status: mockData.response.status,
|
|
632
|
+
statusText: 'OK',
|
|
633
|
+
headers: responseHeaders,
|
|
634
|
+
config: config as any
|
|
635
|
+
};
|
|
636
|
+
|
|
637
|
+
return {
|
|
638
|
+
...config,
|
|
639
|
+
__mockResponse: Promise.resolve(mockResponse),
|
|
640
|
+
__mockifyer_requestKey: requestKey
|
|
641
|
+
} as any;
|
|
642
|
+
}
|
|
643
|
+
|
|
478
644
|
logger.info(
|
|
479
|
-
`[Mockifyer-Fetch]
|
|
645
|
+
`[Mockifyer-Fetch] Live refresh: ${request.method} ${request.url} → ${filename}` +
|
|
480
646
|
(filePath ? ` (${filePath})` : '')
|
|
481
647
|
);
|
|
482
|
-
|
|
483
|
-
...mockData.response.headers,
|
|
484
|
-
'x-mockifyer': 'true',
|
|
485
|
-
'x-mockifyer-timestamp': mockData.timestamp,
|
|
486
|
-
'x-mockifyer-filename': filename,
|
|
487
|
-
'x-mockifyer-filepath': filePath
|
|
488
|
-
};
|
|
489
|
-
|
|
490
|
-
const mockResponse = {
|
|
491
|
-
data: prepareMockResponseBody(mockData, getCurrentDate),
|
|
492
|
-
status: mockData.response.status,
|
|
493
|
-
statusText: 'OK',
|
|
494
|
-
headers: responseHeaders,
|
|
495
|
-
config: config as any
|
|
496
|
-
};
|
|
497
|
-
|
|
498
|
-
return {
|
|
499
|
-
...config,
|
|
500
|
-
__mockResponse: Promise.resolve(mockResponse),
|
|
501
|
-
__mockifyer_requestKey: requestKey
|
|
502
|
-
} as any;
|
|
648
|
+
(config as any).__mockifyer_matchedMock = cachedMock;
|
|
503
649
|
}
|
|
504
650
|
|
|
505
651
|
// Check request limit BEFORE making real API call (only if no mock found and in record mode)
|
|
@@ -630,12 +776,71 @@ class MockifyerClass {
|
|
|
630
776
|
if (isMocked || isLimitReached) {
|
|
631
777
|
return response;
|
|
632
778
|
}
|
|
633
|
-
|
|
779
|
+
|
|
780
|
+
if (this.config.proxy?.baseUrl && this.config.proxy?.mirrorRecordedMocksToClient) {
|
|
781
|
+
await this.maybeMirrorProxyRecordingToClient(response);
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
const matchedMock = (response.config as any).__mockifyer_matchedMock as CachedMockData | undefined;
|
|
785
|
+
if (matchedMock) {
|
|
786
|
+
const capturedResponse: StoredResponse = {
|
|
787
|
+
status: response.status,
|
|
788
|
+
data: response.data,
|
|
789
|
+
headers: (response.headers as Record<string, string>) || {},
|
|
790
|
+
};
|
|
791
|
+
const startTime = (response.config as any).__mockifyer_startTime;
|
|
792
|
+
const durationMs = startTime ? Date.now() - startTime : undefined;
|
|
793
|
+
|
|
794
|
+
if (resolveShouldPersistLiveCapture(matchedMock.mockData, this.config)) {
|
|
795
|
+
await this.persistMatchedMockAfterLiveCapture(matchedMock, capturedResponse, durationMs);
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
const clientResponse = buildClientResponseFromLiveCapture(
|
|
799
|
+
matchedMock.mockData,
|
|
800
|
+
capturedResponse,
|
|
801
|
+
getCurrentDate
|
|
802
|
+
);
|
|
803
|
+
response.data = clientResponse.data;
|
|
804
|
+
response.status = clientResponse.status;
|
|
805
|
+
delete (response.config as any).__mockifyer_matchedMock;
|
|
806
|
+
|
|
807
|
+
const reqUrl = response.config?.url || url;
|
|
808
|
+
const reqMethod = (response.config?.method || 'GET').toUpperCase();
|
|
809
|
+
this.logNetworkEvent(
|
|
810
|
+
{
|
|
811
|
+
method: reqMethod,
|
|
812
|
+
url: reqUrl,
|
|
813
|
+
source: 'upstream',
|
|
814
|
+
status: response.status,
|
|
815
|
+
durationMs,
|
|
816
|
+
},
|
|
817
|
+
this.readRequestCorrelation(response.config)
|
|
818
|
+
);
|
|
819
|
+
return response;
|
|
820
|
+
}
|
|
821
|
+
|
|
634
822
|
// Only save locally if recordMode is enabled AND we're not proxying upstream calls.
|
|
635
823
|
// When proxy is configured, recording should happen on the proxy (e.g. dashboard → Redis).
|
|
636
824
|
if (this.config.recordMode && !this.config.proxy?.baseUrl) {
|
|
637
825
|
await this.saveResponse(response);
|
|
638
826
|
}
|
|
827
|
+
|
|
828
|
+
const reqUrl = response.config?.url || url;
|
|
829
|
+
const reqMethod = (response.config?.method || 'GET').toUpperCase();
|
|
830
|
+
this.logNetworkEvent(
|
|
831
|
+
{
|
|
832
|
+
method: reqMethod,
|
|
833
|
+
url: reqUrl,
|
|
834
|
+
source: 'upstream',
|
|
835
|
+
status: response.status,
|
|
836
|
+
durationMs:
|
|
837
|
+
typeof response.config?.metadata?.durationMs === 'number'
|
|
838
|
+
? response.config.metadata.durationMs
|
|
839
|
+
: undefined,
|
|
840
|
+
},
|
|
841
|
+
this.readRequestCorrelation(response.config)
|
|
842
|
+
);
|
|
843
|
+
|
|
639
844
|
return response;
|
|
640
845
|
},
|
|
641
846
|
async (error: any) => {
|
|
@@ -643,11 +848,131 @@ class MockifyerClass {
|
|
|
643
848
|
if (requestKey) {
|
|
644
849
|
this.processingRequests.delete(requestKey);
|
|
645
850
|
}
|
|
851
|
+
const reqUrl = error.config?.url || '';
|
|
852
|
+
if (reqUrl) {
|
|
853
|
+
this.logNetworkEvent(
|
|
854
|
+
{
|
|
855
|
+
method: (error.config?.method || 'GET').toUpperCase(),
|
|
856
|
+
url: reqUrl,
|
|
857
|
+
source: 'error',
|
|
858
|
+
status: error.response?.status,
|
|
859
|
+
errorMessage: error?.message ?? String(error),
|
|
860
|
+
},
|
|
861
|
+
this.readRequestCorrelation(error.config)
|
|
862
|
+
);
|
|
863
|
+
}
|
|
646
864
|
throw error;
|
|
647
865
|
}
|
|
648
866
|
);
|
|
649
867
|
}
|
|
650
868
|
|
|
869
|
+
/**
|
|
870
|
+
* When dashboard proxy records to Redis, optionally persist the same payload next to the client
|
|
871
|
+
* (Node fs, database provider with `SaveMockOptions.scenario`, or Metro /mockifyer-save for strict RN).
|
|
872
|
+
*/
|
|
873
|
+
private async maybeMirrorProxyRecordingToClient(response: HTTPResponse): Promise<void> {
|
|
874
|
+
const rec = response.mockifyerProxyRecording;
|
|
875
|
+
if (!rec?.recordedToStore || !rec.storedMock) {
|
|
876
|
+
return;
|
|
877
|
+
}
|
|
878
|
+
const hash = rec.hash?.trim();
|
|
879
|
+
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
|
+
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
|
+
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
|
+
|
|
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
|
+
}
|
|
929
|
+
|
|
930
|
+
await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
private async tryMirrorProxyRecordingViaMetro(
|
|
934
|
+
mockData: MockData,
|
|
935
|
+
scenarioName: string,
|
|
936
|
+
hash: string
|
|
937
|
+
): Promise<void> {
|
|
938
|
+
const metroPort = process.env.METRO_PORT ? parseInt(process.env.METRO_PORT, 10) : 8081;
|
|
939
|
+
const fetchFn = (global as any).__mockifyer_original_fetch || fetch;
|
|
940
|
+
if (!fetchFn) {
|
|
941
|
+
logger.warn('[Mockifyer-Fetch] Proxy client mirror: no fetch for Metro save');
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
944
|
+
try {
|
|
945
|
+
const body = JSON.stringify({
|
|
946
|
+
__mockifyerProxyMirror: true,
|
|
947
|
+
mockData,
|
|
948
|
+
scenarioName,
|
|
949
|
+
relativePath: `redis/${hash}.json`,
|
|
950
|
+
});
|
|
951
|
+
const res = await fetchFn(`http://localhost:${metroPort}/mockifyer-save`, {
|
|
952
|
+
method: 'POST',
|
|
953
|
+
headers: { 'Content-Type': 'application/json' },
|
|
954
|
+
body,
|
|
955
|
+
});
|
|
956
|
+
const text = await res.text().catch(() => '');
|
|
957
|
+
if (!res.ok) {
|
|
958
|
+
logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): HTTP ${res.status} ${text}`);
|
|
959
|
+
return;
|
|
960
|
+
}
|
|
961
|
+
try {
|
|
962
|
+
const parsed = JSON.parse(text) as { success?: boolean; error?: string };
|
|
963
|
+
if (parsed.success === false) {
|
|
964
|
+
logger.warn(`[Mockifyer-Fetch] Proxy client mirror (Metro): ${parsed.error || 'save failed'}`);
|
|
965
|
+
return;
|
|
966
|
+
}
|
|
967
|
+
} catch {
|
|
968
|
+
// non-JSON response
|
|
969
|
+
}
|
|
970
|
+
logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (Metro): ${scenarioName}/redis/${hash}.json`);
|
|
971
|
+
} catch (e) {
|
|
972
|
+
logger.warn('[Mockifyer-Fetch] Proxy client mirror (Metro) failed:', e);
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
|
|
651
976
|
private async saveResponse(response: HTTPResponse): Promise<void> {
|
|
652
977
|
// CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
|
|
653
978
|
if ((response.config as any)?.__mockifyer_skip_save || (response.config as any)?.__mockifyer_bypass) {
|
|
@@ -659,11 +984,25 @@ class MockifyerClass {
|
|
|
659
984
|
if (this.config.proxy?.baseUrl) {
|
|
660
985
|
return;
|
|
661
986
|
}
|
|
987
|
+
|
|
988
|
+
if (shouldBlockLocalMockRecording(this.config)) {
|
|
989
|
+
logger.info(
|
|
990
|
+
'[Mockifyer-Fetch] Strict proxy-only mode: skipping local mock save (dashboard proxy unavailable).'
|
|
991
|
+
);
|
|
992
|
+
return;
|
|
993
|
+
}
|
|
662
994
|
|
|
663
995
|
const url = response.config?.url || (response as any).request?.responseURL || (response as any).url || '';
|
|
996
|
+
const recordingExclusions = resolveRecordingExclusions(this.config);
|
|
664
997
|
if (url && shouldExcludeUrl(url, this.config.excludedUrls)) {
|
|
665
998
|
return;
|
|
666
999
|
}
|
|
1000
|
+
if (
|
|
1001
|
+
url &&
|
|
1002
|
+
shouldExcludeRecording(url, recordingExclusions, this.config.baseUrl)
|
|
1003
|
+
) {
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
667
1006
|
|
|
668
1007
|
// CRITICAL: Check response data for sync endpoint references and Metro rejection messages
|
|
669
1008
|
// This is a defense-in-depth measure
|
|
@@ -700,97 +1039,126 @@ class MockifyerClass {
|
|
|
700
1039
|
const rawParams = response.config.params || {};
|
|
701
1040
|
const normalizedParams = rawParams && Object.keys(rawParams).length > 0 ? rawParams : undefined;
|
|
702
1041
|
|
|
703
|
-
const
|
|
1042
|
+
const saveLookupRequest: StoredRequest = {
|
|
704
1043
|
method: response.config.method?.toUpperCase() || 'GET',
|
|
705
1044
|
url: response.config.url || '',
|
|
706
1045
|
headers: {},
|
|
707
1046
|
data: response.config.data,
|
|
708
|
-
queryParams: normalizedParams
|
|
709
|
-
}
|
|
710
|
-
|
|
1047
|
+
queryParams: normalizedParams,
|
|
1048
|
+
};
|
|
1049
|
+
|
|
1050
|
+
const requestKey = this.generateRequestKey(saveLookupRequest);
|
|
1051
|
+
|
|
711
1052
|
if (this.savingResponses.has(requestKey)) {
|
|
712
1053
|
return;
|
|
713
1054
|
}
|
|
714
|
-
|
|
1055
|
+
|
|
1056
|
+
const existingMock = await this.findBestMatchingMock(saveLookupRequest, {
|
|
1057
|
+
includePassthroughMocks: true,
|
|
1058
|
+
});
|
|
1059
|
+
|
|
1060
|
+
const saveDecision = resolveMockRecordingSaveDecision(
|
|
1061
|
+
this.config,
|
|
1062
|
+
existingMock?.mockData
|
|
1063
|
+
);
|
|
1064
|
+
|
|
1065
|
+
if (saveDecision.action === 'skip') {
|
|
1066
|
+
if (existingMock && mockPassesThroughToRealApi(existingMock.mockData)) {
|
|
1067
|
+
logger.info(
|
|
1068
|
+
`[Mockifyer-Fetch] Passthrough mock exists for ${requestKey}, skipping save (enable refreshPassthroughRecordings to update).`
|
|
1069
|
+
);
|
|
1070
|
+
}
|
|
1071
|
+
return;
|
|
1072
|
+
}
|
|
1073
|
+
|
|
715
1074
|
this.savingResponses.add(requestKey);
|
|
716
|
-
|
|
1075
|
+
|
|
717
1076
|
try {
|
|
718
|
-
|
|
719
|
-
const
|
|
720
|
-
const
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
// Generate or reuse sessionId
|
|
1077
|
+
const rawParamsForSave = response.config.params || {};
|
|
1078
|
+
const anonymizedQueryParams = this.anonymizeQueryParams(rawParamsForSave);
|
|
1079
|
+
const normalizedParamsForSave =
|
|
1080
|
+
anonymizedQueryParams && Object.keys(anonymizedQueryParams).length > 0
|
|
1081
|
+
? anonymizedQueryParams
|
|
1082
|
+
: undefined;
|
|
1083
|
+
|
|
726
1084
|
const now = Date.now();
|
|
727
|
-
if (!this.currentSessionId ||
|
|
728
|
-
// Generate new session ID
|
|
1085
|
+
if (!this.currentSessionId || now - this.sessionStartTime > this.SESSION_TIMEOUT_MS) {
|
|
729
1086
|
this.currentSessionId = `session-${now}-${Math.random().toString(36).substring(2, 11)}`;
|
|
730
1087
|
this.sessionStartTime = now;
|
|
731
1088
|
}
|
|
732
1089
|
|
|
733
|
-
// Calculate request duration if start time is available
|
|
734
1090
|
const startTime = (response.config as any).__mockifyer_startTime;
|
|
735
1091
|
const duration = startTime ? Date.now() - startTime : undefined;
|
|
736
1092
|
|
|
1093
|
+
const correlation = this.readRequestCorrelation(response.config);
|
|
1094
|
+
|
|
737
1095
|
const mockData: MockData = {
|
|
738
1096
|
request: {
|
|
739
1097
|
method: response.config?.method?.toUpperCase() || 'GET',
|
|
740
1098
|
url: response.config?.url || '',
|
|
741
1099
|
headers: this.anonymizeHeaders(response.config?.headers || {}),
|
|
742
1100
|
data: response.config?.data,
|
|
743
|
-
queryParams:
|
|
1101
|
+
queryParams: normalizedParamsForSave,
|
|
744
1102
|
},
|
|
745
1103
|
response: {
|
|
746
1104
|
status: response.status,
|
|
747
1105
|
data: response.data,
|
|
748
|
-
headers: response.headers || {}
|
|
1106
|
+
headers: response.headers || {},
|
|
749
1107
|
},
|
|
750
1108
|
timestamp: new Date().toISOString(),
|
|
751
1109
|
duration,
|
|
752
|
-
sessionId:
|
|
1110
|
+
sessionId:
|
|
1111
|
+
saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
|
|
1112
|
+
? existingMock.mockData.sessionId
|
|
1113
|
+
: this.currentSessionId,
|
|
1114
|
+
requestId: correlation?.requestId,
|
|
1115
|
+
parentRequestId: correlation?.parentRequestId,
|
|
1116
|
+
...(newRecordingUsesAlwaysUseRealApi() ? { alwaysUseRealApi: true as const } : {}),
|
|
753
1117
|
};
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
1118
|
+
|
|
1119
|
+
applyRecordingPassthroughFlag(mockData, saveDecision.alwaysUseRealApi);
|
|
1120
|
+
|
|
757
1121
|
if (this.databaseProvider) {
|
|
758
1122
|
try {
|
|
759
1123
|
await this.databaseProvider.save(mockData);
|
|
760
|
-
|
|
761
|
-
// Generate test if enabled (try to write test files even with database provider)
|
|
762
|
-
// Generate test if enabled
|
|
1124
|
+
|
|
763
1125
|
if (this.config.generateTests?.enabled) {
|
|
764
1126
|
await this.generateTestForMock(mockData);
|
|
765
1127
|
}
|
|
766
1128
|
} catch (error) {
|
|
767
|
-
console.error(
|
|
1129
|
+
console.error(
|
|
1130
|
+
`[Mockifyer-Fetch] ❌ Error saving mock using ${this.config.databaseProvider?.type} provider:`,
|
|
1131
|
+
error
|
|
1132
|
+
);
|
|
768
1133
|
throw error;
|
|
769
1134
|
}
|
|
770
1135
|
} else if (fs && path) {
|
|
771
|
-
// Fallback to Node.js filesystem (only if fs/path are available)
|
|
772
|
-
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
773
|
-
const urlParts = (response.config.url || '').replace(/https?:\/\//, '').split('/');
|
|
774
|
-
const domain = urlParts[0].replace(/\./g, '_');
|
|
775
|
-
const urlPathPart = urlParts.slice(1).join('_') || 'root';
|
|
776
|
-
const filename = `${timestamp}_${response.config.method?.toUpperCase() || 'GET'}_${domain}_${urlPathPart}.json`;
|
|
777
1136
|
const currentScenario = getCurrentScenario(this.config.mockDataPath, this.config.clientId);
|
|
778
1137
|
const scenarioPath = getScenarioFolderPath(this.config.mockDataPath, currentScenario);
|
|
779
1138
|
ensureScenarioFolder(this.config.mockDataPath, currentScenario);
|
|
780
|
-
|
|
781
|
-
// Check request limit before saving (only if limit is set via env var)
|
|
1139
|
+
|
|
782
1140
|
const limitCheck = checkRequestLimit(this.config.mockDataPath);
|
|
783
1141
|
if (limitCheck.limitReached && limitCheck.error) {
|
|
784
1142
|
console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
|
|
785
|
-
// Don't throw - just log and return to prevent app crash
|
|
786
1143
|
return;
|
|
787
1144
|
}
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
1145
|
+
|
|
1146
|
+
if (saveDecision.action === 'overwrite' && existingMock?.filePath) {
|
|
1147
|
+
fs.writeFileSync(existingMock.filePath, JSON.stringify(mockData, null, 2));
|
|
1148
|
+
logger.info(
|
|
1149
|
+
`[Mockifyer] Refreshed passthrough mock: ${currentScenario}/${existingMock.filename}`
|
|
1150
|
+
);
|
|
1151
|
+
} else {
|
|
1152
|
+
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
1153
|
+
const urlParts = (response.config.url || '').replace(/https?:\/\//, '').split('/');
|
|
1154
|
+
const domain = urlParts[0].replace(/\./g, '_');
|
|
1155
|
+
const urlPathPart = urlParts.slice(1).join('_') || 'root';
|
|
1156
|
+
const filename = `${timestamp}_${response.config.method?.toUpperCase() || 'GET'}_${domain}_${urlPathPart}.json`;
|
|
1157
|
+
const filePath = path.join(scenarioPath, filename);
|
|
1158
|
+
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
1159
|
+
logger.info(`[Mockifyer] Saved new mock to file: ${currentScenario}/${filename}`);
|
|
1160
|
+
}
|
|
1161
|
+
|
|
794
1162
|
if (this.config.generateTests?.enabled && this.testGenerator) {
|
|
795
1163
|
await this.generateTestForMock(mockData);
|
|
796
1164
|
}
|
|
@@ -802,6 +1170,24 @@ class MockifyerClass {
|
|
|
802
1170
|
}
|
|
803
1171
|
}
|
|
804
1172
|
|
|
1173
|
+
private async persistMatchedMockAfterLiveCapture(
|
|
1174
|
+
cachedMock: CachedMockData,
|
|
1175
|
+
capturedResponse: StoredResponse,
|
|
1176
|
+
durationMs?: number
|
|
1177
|
+
): Promise<void> {
|
|
1178
|
+
const updated = buildMockDataAfterLiveCapture(cachedMock.mockData, capturedResponse, durationMs);
|
|
1179
|
+
|
|
1180
|
+
if (this.databaseProvider) {
|
|
1181
|
+
await this.databaseProvider.save(updated);
|
|
1182
|
+
return;
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
if (fs && cachedMock.filePath) {
|
|
1186
|
+
fs.writeFileSync(cachedMock.filePath, JSON.stringify(updated, null, 2));
|
|
1187
|
+
logger.info(`[Mockifyer-Fetch] Refreshed mock from live API: ${cachedMock.filename}`);
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
|
|
805
1191
|
/**
|
|
806
1192
|
* Simple path resolution fallback for React Native (when path module is stubbed)
|
|
807
1193
|
*/
|
|
@@ -1055,8 +1441,13 @@ export interface MockifyerInstance extends HTTPClient {
|
|
|
1055
1441
|
}
|
|
1056
1442
|
|
|
1057
1443
|
export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
1444
|
+
// Node-only inbound capture; safe on RN (no-op when not on Node).
|
|
1445
|
+
if (typeof installNodeInboundRequestCorrelationCapture === 'function') {
|
|
1446
|
+
installNodeInboundRequestCorrelationCapture();
|
|
1447
|
+
}
|
|
1448
|
+
const resolvedConfig = applyProxyRecordOnMissEnv(config);
|
|
1058
1449
|
// Initialize logger with config level (default to 'info' if not specified)
|
|
1059
|
-
setLogLevel(
|
|
1450
|
+
setLogLevel(resolvedConfig.logging || 'info');
|
|
1060
1451
|
|
|
1061
1452
|
// Set environment variables for Metro middleware to read test generation config
|
|
1062
1453
|
// This allows Metro middleware (which runs in Node.js) to generate tests
|
|
@@ -1083,11 +1474,11 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1083
1474
|
}
|
|
1084
1475
|
}
|
|
1085
1476
|
|
|
1086
|
-
initializeDateManipulation(
|
|
1087
|
-
initializeScenario(
|
|
1088
|
-
|
|
1477
|
+
initializeDateManipulation(resolvedConfig);
|
|
1478
|
+
initializeScenario(resolvedConfig);
|
|
1479
|
+
|
|
1089
1480
|
|
|
1090
|
-
const mockifyer = new MockifyerClass(
|
|
1481
|
+
const mockifyer = new MockifyerClass(resolvedConfig);
|
|
1091
1482
|
const httpClient = mockifyer.getHTTPClient();
|
|
1092
1483
|
|
|
1093
1484
|
// Always store original fetch (even if not patching global)
|
|
@@ -1105,7 +1496,7 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1105
1496
|
}
|
|
1106
1497
|
|
|
1107
1498
|
// Patch global fetch if useGlobalFetch is true
|
|
1108
|
-
if (
|
|
1499
|
+
if (resolvedConfig.useGlobalFetch) {
|
|
1109
1500
|
const mockifyerInstance = mockifyer;
|
|
1110
1501
|
const originalFetchForPatched = (global as any).__mockifyer_original_fetch || originalFetch;
|
|
1111
1502
|
|
|
@@ -1218,9 +1609,223 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1218
1609
|
return extendedClient;
|
|
1219
1610
|
}
|
|
1220
1611
|
|
|
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
|
+
}
|
|
1657
|
+
|
|
1658
|
+
/**
|
|
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
|
+
*
|
|
1662
|
+
* For full control, use {@link setupMockifyer} directly.
|
|
1663
|
+
*/
|
|
1664
|
+
export async function initMockifyerForDashboardProxy(
|
|
1665
|
+
options: InitMockifyerForDashboardProxyOptions
|
|
1666
|
+
): 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
|
|
1691
|
+
);
|
|
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
|
+
}
|
|
1796
|
+
|
|
1797
|
+
/**
|
|
1798
|
+
* Preset: local **filesystem** mocks under {@link InitMockifyerForLocalFilesystemOptions.mockDataPath}
|
|
1799
|
+
* (default `./mock-data` or `MOCKIFYER_PATH`). No dashboard proxy.
|
|
1800
|
+
*/
|
|
1801
|
+
export function initMockifyerForLocalFilesystem(
|
|
1802
|
+
options: InitMockifyerForLocalFilesystemOptions = {}
|
|
1803
|
+
): 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
|
+
});
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
/** Shared with {@link setupMockifyerForReactNative} strict-proxy branching. */
|
|
1821
|
+
export {
|
|
1822
|
+
canUseDashboardRedisProxy,
|
|
1823
|
+
canUseDashboardCentralProxy,
|
|
1824
|
+
} from './utils/dashboard-redis-health';
|
|
1825
|
+
|
|
1221
1826
|
// Re-export types from core
|
|
1222
1827
|
export * from '@sgedda/mockifyer-core';
|
|
1223
1828
|
|
|
1224
|
-
//
|
|
1225
|
-
|
|
1829
|
+
// React Native helpers: import `@sgedda/mockifyer-fetch/react-native` (not this entry — avoids
|
|
1830
|
+
// pulling optional `react-native-launch-arguments` into Node/Next webpack bundles).
|
|
1226
1831
|
|