@sgedda/mockifyer-fetch 1.8.100 → 1.8.106
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 +4 -0
- package/dist/clients/fetch-client.js +50 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +207 -65
- package/dist/metro-sync-middleware.d.ts +10 -0
- package/dist/metro-sync-middleware.js +159 -73
- package/dist/react-native.d.ts +4 -0
- package/dist/utils/resolve-patched-fetch-request.d.ts +24 -0
- package/dist/utils/resolve-patched-fetch-request.js +91 -0
- package/package.json +3 -3
- package/src/clients/fetch-client.ts +66 -1
- package/src/index.ts +251 -68
- package/src/metro-sync-middleware.ts +201 -76
- package/src/react-native.ts +4 -0
- package/src/utils/resolve-patched-fetch-request.ts +105 -0
package/src/index.ts
CHANGED
|
@@ -80,10 +80,16 @@ import {
|
|
|
80
80
|
resolveNetworkLogIncludeTraceOptionsAsync,
|
|
81
81
|
getInlineTraceEnvelopeBusinessBody,
|
|
82
82
|
resolveRecordResponses,
|
|
83
|
+
resolveLocalRecordResponses,
|
|
84
|
+
buildLocalRecordingMockData,
|
|
83
85
|
applyOutboundRequestCorrelation,
|
|
84
86
|
adoptStoredOutboundRequestId,
|
|
85
87
|
resolvePersistedHopIds,
|
|
86
88
|
applyPersistedHopIds,
|
|
89
|
+
ensureLocalInboundParentStubSaved,
|
|
90
|
+
inboundParentStubFilename,
|
|
91
|
+
readOutboundParentHopFromConfig,
|
|
92
|
+
getActiveInboundRequest,
|
|
87
93
|
attachMockifyerRequestIdToError,
|
|
88
94
|
resolveMockifyerRequestIdForError,
|
|
89
95
|
configureFlightRecorder,
|
|
@@ -101,6 +107,10 @@ import {
|
|
|
101
107
|
type MockifyerRuntimeEnabledStorage,
|
|
102
108
|
outboundHeadersToRecord,
|
|
103
109
|
appendParamsToUrl,
|
|
110
|
+
getMockFilePath,
|
|
111
|
+
formatDateStr,
|
|
112
|
+
getCurrentDate,
|
|
113
|
+
isMockRecordingSidecarDir,
|
|
104
114
|
} from '@sgedda/mockifyer-core';
|
|
105
115
|
import { logger, setLogLevel } from '@sgedda/mockifyer-core';
|
|
106
116
|
import {
|
|
@@ -121,6 +131,7 @@ import { resolveProxyUpstreamTlsInsecure } from '@sgedda/mockifyer-core/utils/pr
|
|
|
121
131
|
|
|
122
132
|
import { FetchHTTPClient } from './clients/fetch-client';
|
|
123
133
|
import { bodyInitForFetchResponse } from './utils/fetch-response-body';
|
|
134
|
+
import { resolvePatchedFetchRequest } from './utils/resolve-patched-fetch-request';
|
|
124
135
|
|
|
125
136
|
class MockifyerClass {
|
|
126
137
|
private config: MockifyerConfig;
|
|
@@ -145,6 +156,11 @@ class MockifyerClass {
|
|
|
145
156
|
private runtimeEnabled: boolean;
|
|
146
157
|
/** Optional storage for persisting enable/disable across restarts. */
|
|
147
158
|
private readonly runtimeEnabledStorage?: MockifyerRuntimeEnabledStorage;
|
|
159
|
+
/**
|
|
160
|
+
* Runtime override for whether local/proxy recordings include response bodies.
|
|
161
|
+
* `undefined` = follow env / defaults ({@link resolveLocalRecordResponses} / {@link resolveRecordResponses}).
|
|
162
|
+
*/
|
|
163
|
+
private recordResponsesOverride: boolean | undefined = undefined;
|
|
148
164
|
|
|
149
165
|
/** Session id for timeline hops — per-screen id from {@link setFlightRecorderRuntimeContext} when set. */
|
|
150
166
|
private getRuntimeSessionId(): string {
|
|
@@ -472,7 +488,10 @@ class MockifyerClass {
|
|
|
472
488
|
this.config.clientId = resolveClientId(this.config);
|
|
473
489
|
}
|
|
474
490
|
this.activationMode = resolveActivationMode(this.config);
|
|
475
|
-
this.domainPathRules = new DomainPathRulesSession({
|
|
491
|
+
this.domainPathRules = new DomainPathRulesSession({
|
|
492
|
+
config: this.config,
|
|
493
|
+
getRecordMode: () => this.config.recordMode === true,
|
|
494
|
+
});
|
|
476
495
|
|
|
477
496
|
this.runtimeEnabledStorage = resolveRuntimeEnabledStorage(config.persistRuntimeEnabled);
|
|
478
497
|
if (config.persistRuntimeEnabled === true && !this.runtimeEnabledStorage) {
|
|
@@ -670,6 +689,23 @@ class MockifyerClass {
|
|
|
670
689
|
return undefined;
|
|
671
690
|
}
|
|
672
691
|
|
|
692
|
+
private getAllJsonFiles(dir: string): string[] {
|
|
693
|
+
if (!fs || !path || !fs.existsSync(dir)) return [];
|
|
694
|
+
const results: string[] = [];
|
|
695
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
696
|
+
const fullPath = path.join(dir, entry.name);
|
|
697
|
+
if (entry.isDirectory()) {
|
|
698
|
+
if (isMockRecordingSidecarDir(entry.name)) {
|
|
699
|
+
continue;
|
|
700
|
+
}
|
|
701
|
+
results.push(...this.getAllJsonFiles(fullPath));
|
|
702
|
+
} else if (entry.name.endsWith('.json')) {
|
|
703
|
+
results.push(fullPath);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
return results;
|
|
707
|
+
}
|
|
708
|
+
|
|
673
709
|
private findBestMatchingMockFromFiles(
|
|
674
710
|
request: StoredRequest,
|
|
675
711
|
options?: { includePassthroughMocks?: boolean }
|
|
@@ -696,16 +732,14 @@ class MockifyerClass {
|
|
|
696
732
|
return undefined;
|
|
697
733
|
}
|
|
698
734
|
|
|
699
|
-
const files =
|
|
700
|
-
.filter(file => file.endsWith('.json'));
|
|
735
|
+
const files = this.getAllJsonFiles(scenarioPath);
|
|
701
736
|
|
|
702
737
|
const requestKey = this.generateRequestKey(request);
|
|
703
738
|
let exactMatch: CachedMockData | undefined;
|
|
704
739
|
let similarMatch: CachedMockData | undefined;
|
|
705
740
|
|
|
706
|
-
for (const
|
|
741
|
+
for (const filePath of files) {
|
|
707
742
|
try {
|
|
708
|
-
const filePath = path!.join(scenarioPath, file);
|
|
709
743
|
const fileContent = fs.readFileSync(filePath, 'utf-8');
|
|
710
744
|
const mockData: MockData = JSON.parse(fileContent);
|
|
711
745
|
|
|
@@ -714,16 +748,17 @@ class MockifyerClass {
|
|
|
714
748
|
}
|
|
715
749
|
|
|
716
750
|
const mockKey = this.generateRequestKey(mockData.request);
|
|
751
|
+
const filename = path.relative(scenarioPath, filePath);
|
|
717
752
|
|
|
718
753
|
if (mockKey === requestKey) {
|
|
719
754
|
if (
|
|
720
755
|
mockShouldBeIncludedInRequestMatch(mockData, {
|
|
721
756
|
includePassthroughMocks,
|
|
722
|
-
filename
|
|
757
|
+
filename,
|
|
723
758
|
scenarioPath,
|
|
724
759
|
})
|
|
725
760
|
) {
|
|
726
|
-
exactMatch = { mockData, filename
|
|
761
|
+
exactMatch = { mockData, filename, filePath };
|
|
727
762
|
break;
|
|
728
763
|
}
|
|
729
764
|
continue;
|
|
@@ -805,11 +840,11 @@ class MockifyerClass {
|
|
|
805
840
|
if (
|
|
806
841
|
mockShouldBeIncludedInRequestMatch(mockData, {
|
|
807
842
|
includePassthroughMocks,
|
|
808
|
-
filename
|
|
843
|
+
filename,
|
|
809
844
|
scenarioPath,
|
|
810
845
|
})
|
|
811
846
|
) {
|
|
812
|
-
similarMatch = { mockData, filename
|
|
847
|
+
similarMatch = { mockData, filename, filePath };
|
|
813
848
|
}
|
|
814
849
|
}
|
|
815
850
|
} catch (e) {
|
|
@@ -818,7 +853,7 @@ class MockifyerClass {
|
|
|
818
853
|
}
|
|
819
854
|
}
|
|
820
855
|
} catch (error) {
|
|
821
|
-
logger.warn(`[Mockifyer] Failed to load mock file ${
|
|
856
|
+
logger.warn(`[Mockifyer] Failed to load mock file ${filePath}:`, error);
|
|
822
857
|
}
|
|
823
858
|
}
|
|
824
859
|
|
|
@@ -935,13 +970,19 @@ class MockifyerClass {
|
|
|
935
970
|
if (hitScenarioPath) {
|
|
936
971
|
ensureOverrideGroupRuntimeForScenarioPath(hitScenarioPath, { clientId: this.config.clientId });
|
|
937
972
|
}
|
|
973
|
+
|
|
974
|
+
if (mockData.responseDelayMs && mockData.responseDelayMs > 0) {
|
|
975
|
+
await new Promise(resolve => setTimeout(resolve, mockData.responseDelayMs));
|
|
976
|
+
}
|
|
977
|
+
|
|
938
978
|
const mockResponseBody = this.prepareStoredResponseBody(mockData, filename, hitScenarioPath);
|
|
979
|
+
const effectiveStatus = mockData.statusOverride ?? mockData.response.status;
|
|
939
980
|
this.logNetworkEvent(
|
|
940
981
|
{
|
|
941
982
|
method: (request.method || 'GET').toUpperCase(),
|
|
942
983
|
url: this.resolveLoggedRequestUrl(config, request.url),
|
|
943
984
|
source: 'mock-hit',
|
|
944
|
-
status:
|
|
985
|
+
status: effectiveStatus,
|
|
945
986
|
requestHash: networkEventHashFromRequestKey(requestKey),
|
|
946
987
|
requestBody: request.data,
|
|
947
988
|
responseBody: mockResponseBody,
|
|
@@ -961,7 +1002,7 @@ class MockifyerClass {
|
|
|
961
1002
|
|
|
962
1003
|
const mockResponse = {
|
|
963
1004
|
data: mockResponseBody,
|
|
964
|
-
status:
|
|
1005
|
+
status: effectiveStatus,
|
|
965
1006
|
statusText: 'OK',
|
|
966
1007
|
headers: responseHeaders,
|
|
967
1008
|
config: config as any
|
|
@@ -1076,16 +1117,17 @@ class MockifyerClass {
|
|
|
1076
1117
|
}
|
|
1077
1118
|
}
|
|
1078
1119
|
|
|
1079
|
-
//
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1120
|
+
// Only Metro's own save rejection should skip recording. A business
|
|
1121
|
+
// payload such as `{ success: false, error: "username taken" }` must
|
|
1122
|
+
// still be logged, unwrapped, and saved.
|
|
1123
|
+
const METRO_SAVE_REJECTION = 'Cannot save Mockifyer sync endpoint';
|
|
1124
|
+
const hasRejectionMessage = Boolean(
|
|
1125
|
+
responseDataStr && responseDataStr.includes(METRO_SAVE_REJECTION)
|
|
1083
1126
|
);
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
(responseDataObj.success === false && responseDataObj.error)
|
|
1127
|
+
const hasRejectionInObject = Boolean(
|
|
1128
|
+
responseDataObj &&
|
|
1129
|
+
typeof responseDataObj.error === 'string' &&
|
|
1130
|
+
responseDataObj.error.includes(METRO_SAVE_REJECTION)
|
|
1089
1131
|
);
|
|
1090
1132
|
|
|
1091
1133
|
if (hasRejectionMessage || hasRejectionInObject) {
|
|
@@ -1467,30 +1509,42 @@ class MockifyerClass {
|
|
|
1467
1509
|
correlation
|
|
1468
1510
|
);
|
|
1469
1511
|
|
|
1470
|
-
const
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1512
|
+
const storedRequest: StoredRequest = {
|
|
1513
|
+
method: response.config?.method?.toUpperCase() || 'GET',
|
|
1514
|
+
url: response.config?.url || '',
|
|
1515
|
+
headers: this.anonymizeHeaders(response.config?.headers || {}),
|
|
1516
|
+
data: response.config?.data,
|
|
1517
|
+
queryParams: normalizedParamsForSave,
|
|
1518
|
+
};
|
|
1519
|
+
// Prefer explicit override / config; else request-only default (same as proxy).
|
|
1520
|
+
const recordBodies = resolveLocalRecordResponses(
|
|
1521
|
+
this.recordResponsesOverride ??
|
|
1522
|
+
this.config.proxy?.recordResponses ??
|
|
1523
|
+
this.config.recordResponses
|
|
1524
|
+
);
|
|
1525
|
+
const mockData = buildLocalRecordingMockData({
|
|
1526
|
+
request: storedRequest,
|
|
1478
1527
|
response: {
|
|
1479
1528
|
status: response.status,
|
|
1480
1529
|
data: stripMockifyerTraceFromBody(response.data),
|
|
1481
1530
|
headers: response.headers || {},
|
|
1482
1531
|
},
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1532
|
+
recordResponses: recordBodies,
|
|
1533
|
+
meta: {
|
|
1534
|
+
timestamp: new Date().toISOString(),
|
|
1535
|
+
duration,
|
|
1536
|
+
sessionId:
|
|
1537
|
+
saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
|
|
1538
|
+
? existingMock.mockData.sessionId
|
|
1539
|
+
: this.currentSessionId,
|
|
1540
|
+
requestId: hopIds.requestId,
|
|
1541
|
+
parentRequestId: hopIds.parentRequestId,
|
|
1542
|
+
parentRequestIds: hopIds.parentRequestIds,
|
|
1543
|
+
...(newRecordingUsesAlwaysUseRealApi() || !recordBodies
|
|
1544
|
+
? { alwaysUseRealApi: true as const }
|
|
1545
|
+
: {}),
|
|
1546
|
+
},
|
|
1547
|
+
});
|
|
1494
1548
|
|
|
1495
1549
|
applyRecordingPassthroughFlag(mockData, saveDecision.alwaysUseRealApi);
|
|
1496
1550
|
|
|
@@ -1525,14 +1579,15 @@ class MockifyerClass {
|
|
|
1525
1579
|
`[Mockifyer] Refreshed passthrough mock: ${currentScenario}/${existingMock.filename}`
|
|
1526
1580
|
);
|
|
1527
1581
|
} else {
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
const
|
|
1531
|
-
const
|
|
1532
|
-
|
|
1533
|
-
const filePath = path.join(scenarioPath, filename);
|
|
1582
|
+
// Same nested host/path layout as FilesystemProvider / Expo (Folders view).
|
|
1583
|
+
// getMockFilePath clamps over-long path segments to stay within NAME_MAX.
|
|
1584
|
+
const { dir, filename } = getMockFilePath(mockData, formatDateStr(getCurrentDate()));
|
|
1585
|
+
const filePath = path.join(scenarioPath, dir, filename);
|
|
1586
|
+
fs.mkdirSync(path.join(scenarioPath, dir), { recursive: true });
|
|
1534
1587
|
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
1535
|
-
logger.info(
|
|
1588
|
+
logger.info(
|
|
1589
|
+
`[Mockifyer] Saved new mock to file: ${currentScenario}/${dir ? `${dir}/` : ''}${filename}`
|
|
1590
|
+
);
|
|
1536
1591
|
}
|
|
1537
1592
|
|
|
1538
1593
|
if (this.config.generateTests?.enabled && this.testGenerator) {
|
|
@@ -1541,11 +1596,65 @@ class MockifyerClass {
|
|
|
1541
1596
|
} else {
|
|
1542
1597
|
console.warn('[Mockifyer] Cannot save mock: no database provider and fs/path not available');
|
|
1543
1598
|
}
|
|
1599
|
+
|
|
1600
|
+
await this.ensureInboundParentStubForChild(hopIds.parentRequestId, response.config);
|
|
1544
1601
|
} finally {
|
|
1545
1602
|
this.savingResponses.delete(requestKey);
|
|
1546
1603
|
}
|
|
1547
1604
|
}
|
|
1548
1605
|
|
|
1606
|
+
/**
|
|
1607
|
+
* When a child hop is recorded locally, persist a synthetic inbound-parent stub so
|
|
1608
|
+
* Hops does not show "Missing entry hop" for the ALS gateway id.
|
|
1609
|
+
*/
|
|
1610
|
+
private async ensureInboundParentStubForChild(
|
|
1611
|
+
parentRequestId: string | null | undefined,
|
|
1612
|
+
config: unknown
|
|
1613
|
+
): Promise<void> {
|
|
1614
|
+
const activeInbound = getActiveInboundRequest();
|
|
1615
|
+
const hop =
|
|
1616
|
+
readOutboundParentHopFromConfig(config) ??
|
|
1617
|
+
(activeInbound ? { method: activeInbound.method, url: activeInbound.url } : undefined);
|
|
1618
|
+
|
|
1619
|
+
try {
|
|
1620
|
+
await ensureLocalInboundParentStubSaved({
|
|
1621
|
+
parentRequestId,
|
|
1622
|
+
hop,
|
|
1623
|
+
parentExists: (id) => {
|
|
1624
|
+
if (!fs || !path || this.databaseProvider) {
|
|
1625
|
+
return false;
|
|
1626
|
+
}
|
|
1627
|
+
const currentScenario = getCurrentScenario(this.config.mockDataPath, this.config.clientId);
|
|
1628
|
+
const scenarioPath = getScenarioFolderPath(this.config.mockDataPath, currentScenario);
|
|
1629
|
+
return fs.existsSync(path.join(scenarioPath, inboundParentStubFilename(id)));
|
|
1630
|
+
},
|
|
1631
|
+
save: async (row) => {
|
|
1632
|
+
if (this.databaseProvider) {
|
|
1633
|
+
await this.databaseProvider.save(row.mock);
|
|
1634
|
+
return;
|
|
1635
|
+
}
|
|
1636
|
+
if (!fs || !path) {
|
|
1637
|
+
return;
|
|
1638
|
+
}
|
|
1639
|
+
const currentScenario = getCurrentScenario(this.config.mockDataPath, this.config.clientId);
|
|
1640
|
+
const scenarioPath = getScenarioFolderPath(this.config.mockDataPath, currentScenario);
|
|
1641
|
+
ensureScenarioFolder(this.config.mockDataPath, currentScenario);
|
|
1642
|
+
const filePath = path.join(scenarioPath, row.filename);
|
|
1643
|
+
if (fs.existsSync(filePath)) {
|
|
1644
|
+
return;
|
|
1645
|
+
}
|
|
1646
|
+
fs.writeFileSync(filePath, JSON.stringify(row.mock, null, 2));
|
|
1647
|
+
logger.info(
|
|
1648
|
+
`[Mockifyer-Fetch] Saved inbound parent stub: ${currentScenario}/${row.filename}`
|
|
1649
|
+
);
|
|
1650
|
+
},
|
|
1651
|
+
});
|
|
1652
|
+
} catch (error) {
|
|
1653
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1654
|
+
logger.warn(`[Mockifyer-Fetch] Failed to save inbound parent stub: ${message}`);
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1549
1658
|
private async persistMatchedMockAfterLiveCapture(
|
|
1550
1659
|
cachedMock: CachedMockData,
|
|
1551
1660
|
capturedResponse: StoredResponse,
|
|
@@ -1774,6 +1883,74 @@ class MockifyerClass {
|
|
|
1774
1883
|
return this.config.clientId;
|
|
1775
1884
|
}
|
|
1776
1885
|
|
|
1886
|
+
/**
|
|
1887
|
+
* Turn record mode on/off at runtime (dev menus, tests).
|
|
1888
|
+
* Also updates `proxy.recordOnMiss` when a dashboard proxy is configured so
|
|
1889
|
+
* Redis/proxy recording follows the same switch as local hybrid saves.
|
|
1890
|
+
*
|
|
1891
|
+
* When enabling: flips existing allowlist `recordResponses` to true and new
|
|
1892
|
+
* discoveries enable recording. When disabled, allowlist discovery stops
|
|
1893
|
+
* persisting new keys (so browsing does not poison the rules file).
|
|
1894
|
+
*/
|
|
1895
|
+
setRecordMode(enabled: boolean): void {
|
|
1896
|
+
const next = Boolean(enabled);
|
|
1897
|
+
this.config.recordMode = next;
|
|
1898
|
+
if (next) {
|
|
1899
|
+
// Recording needs live upstream calls; fail-on-miss conflicts with that.
|
|
1900
|
+
this.config.failOnMissingMock = false;
|
|
1901
|
+
this.domainPathRules.enableRecordResponsesForAllRules();
|
|
1902
|
+
}
|
|
1903
|
+
if (this.config.proxy?.baseUrl) {
|
|
1904
|
+
this.config.proxy = {
|
|
1905
|
+
...this.config.proxy,
|
|
1906
|
+
recordOnMiss: next,
|
|
1907
|
+
};
|
|
1908
|
+
const client = this.httpClient as FetchHTTPClient & {
|
|
1909
|
+
setProxyRecordOnMiss?: (value: boolean | undefined) => void;
|
|
1910
|
+
};
|
|
1911
|
+
client.setProxyRecordOnMiss?.(next);
|
|
1912
|
+
}
|
|
1913
|
+
logger.info(`[Mockifyer-Fetch] recordMode set to: ${next}`);
|
|
1914
|
+
}
|
|
1915
|
+
|
|
1916
|
+
/** Whether newly unmatched requests can be recorded (local or proxy record-on-miss). */
|
|
1917
|
+
isRecordMode(): boolean {
|
|
1918
|
+
return this.config.recordMode === true;
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
/**
|
|
1922
|
+
* Whether new recordings store full response bodies (true) or request-only stubs (false, default).
|
|
1923
|
+
* Matches dashboard proxy `recordResponses` / env `MOCKIFYER_RECORD_RESPONSES`.
|
|
1924
|
+
*/
|
|
1925
|
+
setRecordResponses(enabled: boolean): void {
|
|
1926
|
+
const next = Boolean(enabled);
|
|
1927
|
+
this.recordResponsesOverride = next;
|
|
1928
|
+
this.config.recordResponses = next;
|
|
1929
|
+
if (this.config.proxy) {
|
|
1930
|
+
this.config.proxy = {
|
|
1931
|
+
...this.config.proxy,
|
|
1932
|
+
recordResponses: next,
|
|
1933
|
+
};
|
|
1934
|
+
}
|
|
1935
|
+
const client = this.httpClient as FetchHTTPClient & {
|
|
1936
|
+
setProxyRecordResponses?: (value: boolean) => void;
|
|
1937
|
+
};
|
|
1938
|
+
client.setProxyRecordResponses?.(next);
|
|
1939
|
+
logger.info(`[Mockifyer-Fetch] recordResponses (store bodies) set to: ${next}`);
|
|
1940
|
+
}
|
|
1941
|
+
|
|
1942
|
+
/** True when new recordings include response bodies (not request-only stubs). */
|
|
1943
|
+
isRecordResponses(): boolean {
|
|
1944
|
+
if (this.config.proxy?.baseUrl) {
|
|
1945
|
+
return resolveRecordResponses(
|
|
1946
|
+
this.recordResponsesOverride ?? this.config.proxy.recordResponses
|
|
1947
|
+
);
|
|
1948
|
+
}
|
|
1949
|
+
return resolveLocalRecordResponses(
|
|
1950
|
+
this.recordResponsesOverride ?? this.config.recordResponses
|
|
1951
|
+
);
|
|
1952
|
+
}
|
|
1953
|
+
|
|
1777
1954
|
/**
|
|
1778
1955
|
* Enable Mockifyer at runtime. All subsequent requests will go through Mockifyer
|
|
1779
1956
|
* (mock lookup, recording, dashboard/Redis proxy, etc.).
|
|
@@ -1816,6 +1993,9 @@ class MockifyerClass {
|
|
|
1816
1993
|
|
|
1817
1994
|
async reloadMockData(syncFromProject: boolean = true): Promise<void> {
|
|
1818
1995
|
await this.databaseProviderInitPromise;
|
|
1996
|
+
// `$pool` fixtures are cached write-once for RN (no Node fs). Clear so a reload
|
|
1997
|
+
// picks up updated pool response bodies from the provider / Metro sync.
|
|
1998
|
+
this.poolResponseCache.clear();
|
|
1819
1999
|
// If provider has a reload method, use it (for ExpoFileSystemProvider with caching)
|
|
1820
2000
|
// For HybridProvider, this will also sync files from project folder to device
|
|
1821
2001
|
if (this.databaseProvider && typeof (this.databaseProvider as any).reload === 'function') {
|
|
@@ -1856,6 +2036,10 @@ export interface MockifyerInstance extends HTTPClient {
|
|
|
1856
2036
|
clearAllMocks: () => Promise<void>;
|
|
1857
2037
|
setClientId: (lane: string) => void;
|
|
1858
2038
|
getClientId: () => string | undefined;
|
|
2039
|
+
setRecordMode: (enabled: boolean) => void;
|
|
2040
|
+
isRecordMode: () => boolean;
|
|
2041
|
+
setRecordResponses: (enabled: boolean) => void;
|
|
2042
|
+
isRecordResponses: () => boolean;
|
|
1859
2043
|
enableMockifyer: () => void;
|
|
1860
2044
|
disableMockifyer: () => void;
|
|
1861
2045
|
isMockifyerEnabled: () => boolean;
|
|
@@ -1923,10 +2107,15 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1923
2107
|
const originalFetchForPatched = (global as any).__mockifyer_original_fetch || originalFetch;
|
|
1924
2108
|
|
|
1925
2109
|
global.fetch = async function(input: string | Request | URL, init?: RequestInit): Promise<Response> {
|
|
2110
|
+
// Disabled means the real network: do not rebuild the call. The interceptor
|
|
2111
|
+
// bypass flag still runs FetchHTTPClient, which JSON.parses `{`/`[` bodies
|
|
2112
|
+
// (throwing on invalid JSON), JSON.stringifies FormData/Blob/URLSearchParams,
|
|
2113
|
+
// and drops credentials, abort signals, and Request-only method/headers/body.
|
|
2114
|
+
if (!mockifyerInstance.isMockifyerEnabled()) {
|
|
2115
|
+
return await originalFetchForPatched(input, init);
|
|
2116
|
+
}
|
|
2117
|
+
|
|
1926
2118
|
const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
|
|
1927
|
-
const method = init?.method || 'GET';
|
|
1928
|
-
const headers = init?.headers || {};
|
|
1929
|
-
const body = init?.body;
|
|
1930
2119
|
|
|
1931
2120
|
// Skip Mockifyer sync endpoints, dashboard plumbing, and Resend API
|
|
1932
2121
|
if (
|
|
@@ -1936,17 +2125,20 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1936
2125
|
) {
|
|
1937
2126
|
return await originalFetchForPatched(input, init);
|
|
1938
2127
|
}
|
|
2128
|
+
|
|
2129
|
+
const resolved = await resolvePatchedFetchRequest(input, init);
|
|
2130
|
+
const method = resolved.method;
|
|
1939
2131
|
|
|
1940
|
-
const simpleRequestKey = `${method}:${url}`;
|
|
2132
|
+
const simpleRequestKey = `${method}:${resolved.url}`;
|
|
1941
2133
|
const isProcessing = (mockifyerInstance as any).processingRequests?.has(simpleRequestKey);
|
|
1942
2134
|
if (isProcessing) {
|
|
1943
2135
|
return await originalFetchForPatched(input, init);
|
|
1944
2136
|
}
|
|
1945
2137
|
|
|
1946
2138
|
let params: Record<string, string> | undefined = undefined;
|
|
1947
|
-
let baseUrl = url;
|
|
2139
|
+
let baseUrl = resolved.url;
|
|
1948
2140
|
try {
|
|
1949
|
-
const urlObj = new URL(url);
|
|
2141
|
+
const urlObj = new URL(resolved.url);
|
|
1950
2142
|
if (urlObj.search) {
|
|
1951
2143
|
params = {};
|
|
1952
2144
|
urlObj.searchParams.forEach((value, key) => {
|
|
@@ -1959,26 +2151,13 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1959
2151
|
// URL parsing failed, use URL as-is
|
|
1960
2152
|
}
|
|
1961
2153
|
|
|
1962
|
-
let headersObj: Record<string, string> = {};
|
|
1963
|
-
if (headers instanceof Headers) {
|
|
1964
|
-
headers.forEach((value, key) => {
|
|
1965
|
-
headersObj[key] = value;
|
|
1966
|
-
});
|
|
1967
|
-
} else if (Array.isArray(headers)) {
|
|
1968
|
-
headers.forEach(([key, value]) => {
|
|
1969
|
-
headersObj[key] = value;
|
|
1970
|
-
});
|
|
1971
|
-
} else {
|
|
1972
|
-
headersObj = { ...(headers as Record<string, string>) };
|
|
1973
|
-
}
|
|
1974
|
-
|
|
1975
2154
|
try {
|
|
1976
2155
|
const requestConfig = {
|
|
1977
2156
|
url: baseUrl,
|
|
1978
2157
|
method: method as any,
|
|
1979
|
-
headers:
|
|
2158
|
+
headers: resolved.headers,
|
|
1980
2159
|
params: params,
|
|
1981
|
-
data:
|
|
2160
|
+
data: resolved.body
|
|
1982
2161
|
};
|
|
1983
2162
|
|
|
1984
2163
|
const response = await httpClient.request(requestConfig);
|
|
@@ -2033,6 +2212,10 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
2033
2212
|
extendedClient.clearAllMocks = () => mockifyer.clearAllMocks();
|
|
2034
2213
|
extendedClient.setClientId = (lane: string) => mockifyer.setClientId(lane);
|
|
2035
2214
|
extendedClient.getClientId = () => mockifyer.getClientId();
|
|
2215
|
+
extendedClient.setRecordMode = (enabled: boolean) => mockifyer.setRecordMode(enabled);
|
|
2216
|
+
extendedClient.isRecordMode = () => mockifyer.isRecordMode();
|
|
2217
|
+
extendedClient.setRecordResponses = (enabled: boolean) => mockifyer.setRecordResponses(enabled);
|
|
2218
|
+
extendedClient.isRecordResponses = () => mockifyer.isRecordResponses();
|
|
2036
2219
|
extendedClient.enableMockifyer = () => mockifyer.enableMockifyer();
|
|
2037
2220
|
extendedClient.disableMockifyer = () => mockifyer.disableMockifyer();
|
|
2038
2221
|
extendedClient.isMockifyerEnabled = () => mockifyer.isMockifyerEnabled();
|