@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
|
@@ -67,6 +67,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
67
67
|
})();
|
|
68
68
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
69
69
|
exports.bufferAtlasBodySpill = bufferAtlasBodySpill;
|
|
70
|
+
exports.persistAtlasRenderBodySpills = persistAtlasRenderBodySpills;
|
|
70
71
|
exports.createMockSyncMiddleware = createMockSyncMiddleware;
|
|
71
72
|
exports.startAutoSync = startAutoSync;
|
|
72
73
|
exports.stopAutoSync = stopAutoSync;
|
|
@@ -253,90 +254,111 @@ function collectRequestBodyUtf8(req, onDone, maxBytes = MAX_METRO_POST_BODY_BYTE
|
|
|
253
254
|
});
|
|
254
255
|
req.on("error", (e) => finish(e, ""));
|
|
255
256
|
}
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
257
|
+
/**
|
|
258
|
+
* Scenario folder names the dashboard accepts (one path segment).
|
|
259
|
+
* `pool` is the fixture-pool directory and is not a scenario.
|
|
260
|
+
*/
|
|
261
|
+
const SAFE_SCENARIO_NAME = /^[a-zA-Z0-9_-]+$/;
|
|
262
|
+
const FIXTURE_POOL_DIR_NAME = "pool";
|
|
263
|
+
/** True when `candidate` is `root` or a file/directory inside it. */
|
|
264
|
+
function isInsideDirectory(root, candidate) {
|
|
265
|
+
const rootResolved = path.resolve(root);
|
|
266
|
+
const target = path.resolve(candidate);
|
|
267
|
+
const prefix = rootResolved.endsWith(path.sep)
|
|
268
|
+
? rootResolved
|
|
269
|
+
: rootResolved + path.sep;
|
|
270
|
+
return target === rootResolved || target.startsWith(prefix);
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Accept a scenario name that can be used as a single directory under mock-data.
|
|
274
|
+
* Rejects traversal (`..`, slashes), absolute paths, and the reserved `pool` directory.
|
|
275
|
+
*/
|
|
276
|
+
function sanitizeScenarioName(raw) {
|
|
277
|
+
if (typeof raw !== "string") {
|
|
278
|
+
return null;
|
|
265
279
|
}
|
|
266
|
-
|
|
267
|
-
|
|
280
|
+
const trimmed = raw.trim();
|
|
281
|
+
if (!trimmed ||
|
|
282
|
+
trimmed === FIXTURE_POOL_DIR_NAME ||
|
|
283
|
+
!SAFE_SCENARIO_NAME.test(trimmed)) {
|
|
284
|
+
return null;
|
|
268
285
|
}
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
if (
|
|
275
|
-
|
|
276
|
-
remainingSegments = pathSegments.slice(graphqlIdx + 1);
|
|
286
|
+
return trimmed;
|
|
287
|
+
}
|
|
288
|
+
/** Absolute scenario directory, or null when `scenario` would escape mock-data. */
|
|
289
|
+
function resolveScenarioDirectory(mockDataPath, scenario) {
|
|
290
|
+
const name = sanitizeScenarioName(scenario);
|
|
291
|
+
if (!name) {
|
|
292
|
+
return null;
|
|
277
293
|
}
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
294
|
+
const dir = path.resolve(mockDataPath, name);
|
|
295
|
+
if (!isInsideDirectory(mockDataPath, dir)) {
|
|
296
|
+
return null;
|
|
281
297
|
}
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
298
|
+
return dir;
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Relative `.json` path under a scenario folder (for example `redis/<hash>.json`).
|
|
302
|
+
* Rejects absolute paths and `.` / `..` segments.
|
|
303
|
+
*/
|
|
304
|
+
function sanitizeMockRelativePath(raw) {
|
|
305
|
+
const normalized = raw.trim().replace(/\\/g, "/").replace(/^\/+/, "");
|
|
306
|
+
if (!normalized.endsWith(".json") || normalized.includes("\0")) {
|
|
307
|
+
return null;
|
|
285
308
|
}
|
|
286
|
-
|
|
287
|
-
if (
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
identifier = identifier.replace(/[^a-zA-Z0-9_-]/g, "_").substring(0, 60);
|
|
304
|
-
const dir = [hostSafe, type, ...remainingSegments].filter(Boolean).join("/");
|
|
305
|
-
const filename = identifier
|
|
306
|
-
? `${method}_${identifier}_${dateStr}.json`
|
|
307
|
-
: `${method}_${dateStr}.json`;
|
|
308
|
-
return { dir, filename };
|
|
309
|
+
const segments = normalized.split("/");
|
|
310
|
+
if (segments.some((seg) => seg.length === 0 || seg === "." || seg === "..")) {
|
|
311
|
+
return null;
|
|
312
|
+
}
|
|
313
|
+
return normalized;
|
|
314
|
+
}
|
|
315
|
+
/** Absolute mock file path inside `scenarioDir`, or null when the relative path escapes. */
|
|
316
|
+
function resolveMockFilePath(scenarioDir, relativePath) {
|
|
317
|
+
const rel = sanitizeMockRelativePath(relativePath);
|
|
318
|
+
if (!rel) {
|
|
319
|
+
return null;
|
|
320
|
+
}
|
|
321
|
+
const filePath = path.resolve(scenarioDir, rel);
|
|
322
|
+
if (!isInsideDirectory(scenarioDir, filePath) || filePath === path.resolve(scenarioDir)) {
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
325
|
+
return filePath;
|
|
309
326
|
}
|
|
310
327
|
/**
|
|
311
|
-
* Get current scenario from scenario-config.json
|
|
328
|
+
* Get current scenario from env or scenario-config.json.
|
|
329
|
+
* Unsafe names (path traversal, reserved `pool`) are ignored.
|
|
312
330
|
*/
|
|
313
331
|
function getCurrentScenario(mockDataPath) {
|
|
314
|
-
|
|
315
|
-
if (
|
|
316
|
-
return
|
|
332
|
+
const fromEnv = sanitizeScenarioName(process.env.MOCKIFYER_SCENARIO);
|
|
333
|
+
if (fromEnv) {
|
|
334
|
+
return fromEnv;
|
|
317
335
|
}
|
|
318
|
-
// Try to load from scenario-config.json
|
|
319
336
|
try {
|
|
320
337
|
const configPath = path.join(mockDataPath, "scenario-config.json");
|
|
321
338
|
if (fs.existsSync(configPath)) {
|
|
322
339
|
const fileContent = fs.readFileSync(configPath, "utf-8");
|
|
323
340
|
const config = JSON.parse(fileContent);
|
|
324
|
-
|
|
325
|
-
|
|
341
|
+
const fromFile = sanitizeScenarioName(config.currentScenario);
|
|
342
|
+
if (fromFile) {
|
|
343
|
+
return fromFile;
|
|
326
344
|
}
|
|
327
345
|
}
|
|
328
346
|
}
|
|
329
|
-
catch
|
|
347
|
+
catch {
|
|
330
348
|
// Silently fail - file might not exist or be invalid
|
|
331
349
|
}
|
|
332
350
|
return DEFAULT_SCENARIO;
|
|
333
351
|
}
|
|
334
352
|
/**
|
|
335
|
-
*
|
|
353
|
+
* Scenario folder under mock-data. Throws when `scenario` is not a safe single segment
|
|
354
|
+
* so a poisoned name cannot mkdir outside the mock-data tree.
|
|
336
355
|
*/
|
|
337
356
|
function getScenarioPath(scenario, mockDataPath) {
|
|
338
|
-
|
|
339
|
-
|
|
357
|
+
const dir = resolveScenarioDirectory(mockDataPath, scenario);
|
|
358
|
+
if (!dir) {
|
|
359
|
+
throw new Error(`Invalid scenario name: ${scenario}`);
|
|
360
|
+
}
|
|
361
|
+
return dir;
|
|
340
362
|
}
|
|
341
363
|
/**
|
|
342
364
|
* Get test generation config from options or environment variables
|
|
@@ -492,7 +514,7 @@ function saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig
|
|
|
492
514
|
.replace(/T/, "_")
|
|
493
515
|
.replace(/\..+/, "")
|
|
494
516
|
.replace(/:/g, "-");
|
|
495
|
-
const { dir, filename } =
|
|
517
|
+
const { dir, filename } = (0, mockifyer_core_1.getMockFilePath)(mockData, dateStr);
|
|
496
518
|
const fullDir = path.join(scenarioPath, dir);
|
|
497
519
|
const filePath = path.join(fullDir, filename);
|
|
498
520
|
// Check if file already exists - skip saving if it does
|
|
@@ -543,17 +565,22 @@ function saveProxyMirrorMockToProject(mockData, projectRoot, mockDataPath, scena
|
|
|
543
565
|
error: "Mock data contains nested Mockifyer sync requests",
|
|
544
566
|
};
|
|
545
567
|
}
|
|
546
|
-
const id = scenarioName
|
|
568
|
+
const id = sanitizeScenarioName(scenarioName);
|
|
547
569
|
if (!id) {
|
|
548
|
-
return { success: false, error: "scenarioName
|
|
570
|
+
return { success: false, error: "Invalid scenarioName" };
|
|
549
571
|
}
|
|
550
|
-
const normalized = relativePath
|
|
572
|
+
const normalized = sanitizeMockRelativePath(relativePath);
|
|
551
573
|
if (!normalized) {
|
|
552
|
-
return { success: false, error: "relativePath
|
|
574
|
+
return { success: false, error: "Invalid relativePath" };
|
|
575
|
+
}
|
|
576
|
+
const scenarioPath = resolveScenarioDirectory(mockDataPath, id);
|
|
577
|
+
const filePath = scenarioPath
|
|
578
|
+
? resolveMockFilePath(scenarioPath, normalized)
|
|
579
|
+
: null;
|
|
580
|
+
if (!scenarioPath || !filePath) {
|
|
581
|
+
return { success: false, error: "Invalid relativePath" };
|
|
553
582
|
}
|
|
554
|
-
const scenarioPath = getScenarioPath(id, mockDataPath);
|
|
555
583
|
fs.mkdirSync(scenarioPath, { recursive: true });
|
|
556
|
-
const filePath = path.join(scenarioPath, normalized);
|
|
557
584
|
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
558
585
|
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
559
586
|
if (testConfig) {
|
|
@@ -1063,6 +1090,19 @@ function bufferAtlasBodySpill(relativePath, text) {
|
|
|
1063
1090
|
}
|
|
1064
1091
|
return { success: true, relativePath: buffered };
|
|
1065
1092
|
}
|
|
1093
|
+
/**
|
|
1094
|
+
* Write hop bodies for an Atlas HTML render.
|
|
1095
|
+
*
|
|
1096
|
+
* Device uploads sit in the Metro spill buffer and are often omitted from the
|
|
1097
|
+
* render POST (`bodySpills` is capped at 2MB, so a max-size body never fits).
|
|
1098
|
+
* Flush that buffer before writing the payload. Buffering the payload first
|
|
1099
|
+
* evicts older spills once the in-memory cap is hit, and those files are then
|
|
1100
|
+
* missing from disk.
|
|
1101
|
+
*/
|
|
1102
|
+
function persistAtlasRenderBodySpills(outDir, bodySpills) {
|
|
1103
|
+
const flushed = (0, mockifyer_core_2.flushNetworkBodySpillsToDir)(outDir);
|
|
1104
|
+
return flushed + (0, mockifyer_core_2.writeNetworkBodySpillMap)(outDir, bodySpills);
|
|
1105
|
+
}
|
|
1066
1106
|
const ATLAS_HTML_CONTENT_TYPES = {
|
|
1067
1107
|
".html": "text/html; charset=utf-8",
|
|
1068
1108
|
".htm": "text/html; charset=utf-8",
|
|
@@ -1601,8 +1641,14 @@ function createMockSyncMiddleware(options) {
|
|
|
1601
1641
|
const params = new URLSearchParams(query);
|
|
1602
1642
|
const scenarioParam = params.get("scenario");
|
|
1603
1643
|
const scenarioName = scenarioParam && scenarioParam.trim() !== ""
|
|
1604
|
-
? scenarioParam
|
|
1644
|
+
? sanitizeScenarioName(scenarioParam)
|
|
1605
1645
|
: getCurrentScenario(mockDataPath);
|
|
1646
|
+
if (!scenarioName) {
|
|
1647
|
+
res.statusCode = 400;
|
|
1648
|
+
res.setHeader("Content-Type", "application/json");
|
|
1649
|
+
res.end(JSON.stringify({ success: false, error: "Invalid scenario name" }));
|
|
1650
|
+
return;
|
|
1651
|
+
}
|
|
1606
1652
|
const rules = (0, mockifyer_core_2.readDomainPathRulesFile)(mockDataPath, scenarioName);
|
|
1607
1653
|
res.setHeader("Content-Type", "application/json");
|
|
1608
1654
|
res.end(JSON.stringify({ success: true, scenario: scenarioName, rules }));
|
|
@@ -1618,11 +1664,39 @@ function createMockSyncMiddleware(options) {
|
|
|
1618
1664
|
try {
|
|
1619
1665
|
const parsed = JSON.parse(body);
|
|
1620
1666
|
const scenarioName = typeof parsed.scenario === "string" && parsed.scenario.trim() !== ""
|
|
1621
|
-
? parsed.scenario
|
|
1667
|
+
? sanitizeScenarioName(parsed.scenario)
|
|
1622
1668
|
: getCurrentScenario(mockDataPath);
|
|
1669
|
+
if (!scenarioName) {
|
|
1670
|
+
res.statusCode = 400;
|
|
1671
|
+
res.setHeader("Content-Type", "application/json");
|
|
1672
|
+
res.end(JSON.stringify({ success: false, error: "Invalid scenario name" }));
|
|
1673
|
+
return;
|
|
1674
|
+
}
|
|
1675
|
+
if (parsed.replace === true) {
|
|
1676
|
+
const updates = (0, mockifyer_core_2.parseDomainPathRules)(parsed.rules ?? {});
|
|
1677
|
+
// Re-read to pick up concurrent new keys, then apply recordResponses updates.
|
|
1678
|
+
const existing = (0, mockifyer_core_2.readDomainPathRulesFile)(mockDataPath, scenarioName);
|
|
1679
|
+
const merged = { ...updates };
|
|
1680
|
+
// Add any new keys that were discovered concurrently but preserve the recordResponses updates.
|
|
1681
|
+
for (const [key, rule] of Object.entries(existing)) {
|
|
1682
|
+
if (!merged[key]) {
|
|
1683
|
+
merged[key] = { ...rule };
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
(0, mockifyer_core_2.writeDomainPathRulesFile)(mockDataPath, scenarioName, merged);
|
|
1687
|
+
res.setHeader("Content-Type", "application/json");
|
|
1688
|
+
res.end(JSON.stringify({
|
|
1689
|
+
success: true,
|
|
1690
|
+
changed: true,
|
|
1691
|
+
replaced: true,
|
|
1692
|
+
scenario: scenarioName,
|
|
1693
|
+
rules: merged,
|
|
1694
|
+
}));
|
|
1695
|
+
return;
|
|
1696
|
+
}
|
|
1623
1697
|
const upserts = (0, mockifyer_core_2.parseDomainPathRules)(parsed.upserts ?? parsed.rules ?? {});
|
|
1624
1698
|
const existing = (0, mockifyer_core_2.readDomainPathRulesFile)(mockDataPath, scenarioName);
|
|
1625
|
-
const { rules, changed } = (0, mockifyer_core_2.
|
|
1699
|
+
const { rules, changed } = (0, mockifyer_core_2.mergeDiscoveredDomainPathUpserts)(existing, upserts);
|
|
1626
1700
|
if (changed) {
|
|
1627
1701
|
(0, mockifyer_core_2.writeDomainPathRulesFile)(mockDataPath, scenarioName, rules);
|
|
1628
1702
|
}
|
|
@@ -1892,7 +1966,7 @@ function createMockSyncMiddleware(options) {
|
|
|
1892
1966
|
}
|
|
1893
1967
|
(0, mockifyer_core_2.setAtlasDocMap)(doc);
|
|
1894
1968
|
(0, mockifyer_core_2.setAtlasDocHtmlOutputPath)(outDir);
|
|
1895
|
-
const spillWritten = (
|
|
1969
|
+
const spillWritten = persistAtlasRenderBodySpills(outDir, parsed.bodySpills);
|
|
1896
1970
|
const events = Array.isArray(parsed.events) ? parsed.events : [];
|
|
1897
1971
|
const written = (0, mockifyer_core_2.writeAtlasDocHtml)(outDir, doc, events);
|
|
1898
1972
|
const relativeFromRoot = path
|
|
@@ -2062,8 +2136,10 @@ function createMockSyncMiddleware(options) {
|
|
|
2062
2136
|
try {
|
|
2063
2137
|
// Check environment variable first (highest priority)
|
|
2064
2138
|
if (process.env.MOCKIFYER_SCENARIO) {
|
|
2065
|
-
|
|
2066
|
-
|
|
2139
|
+
const fromEnv = sanitizeScenarioName(process.env.MOCKIFYER_SCENARIO) ||
|
|
2140
|
+
DEFAULT_SCENARIO;
|
|
2141
|
+
mockifyer_core_1.logger.debug(`[MetroSyncMiddleware] Using scenario from MOCKIFYER_SCENARIO env var: ${fromEnv}`);
|
|
2142
|
+
writeScenarioResponse(fromEnv);
|
|
2067
2143
|
return;
|
|
2068
2144
|
}
|
|
2069
2145
|
const configPath = path.join(mockDataPath, "scenario-config.json");
|
|
@@ -2074,7 +2150,7 @@ function createMockSyncMiddleware(options) {
|
|
|
2074
2150
|
const fileContent = fs.readFileSync(configPath, "utf-8");
|
|
2075
2151
|
mockifyer_core_1.logger.debug(`[MetroSyncMiddleware] File content: ${fileContent}`);
|
|
2076
2152
|
const config = JSON.parse(fileContent);
|
|
2077
|
-
const scenario = config.currentScenario || DEFAULT_SCENARIO;
|
|
2153
|
+
const scenario = sanitizeScenarioName(config.currentScenario) || DEFAULT_SCENARIO;
|
|
2078
2154
|
mockifyer_core_1.logger.debug(`[MetroSyncMiddleware] Found scenario in config: ${scenario} (from file: ${JSON.stringify(config)})`);
|
|
2079
2155
|
writeScenarioResponse(scenario);
|
|
2080
2156
|
}
|
|
@@ -2100,6 +2176,16 @@ function createMockSyncMiddleware(options) {
|
|
|
2100
2176
|
req.on("end", () => {
|
|
2101
2177
|
try {
|
|
2102
2178
|
const config = JSON.parse(body);
|
|
2179
|
+
if (config &&
|
|
2180
|
+
typeof config === "object" &&
|
|
2181
|
+
typeof config.currentScenario === "string" &&
|
|
2182
|
+
config.currentScenario.trim() !== "" &&
|
|
2183
|
+
!sanitizeScenarioName(config.currentScenario)) {
|
|
2184
|
+
res.statusCode = 400;
|
|
2185
|
+
res.setHeader("Content-Type", "application/json");
|
|
2186
|
+
res.end(JSON.stringify({ success: false, error: "Invalid scenario name" }));
|
|
2187
|
+
return;
|
|
2188
|
+
}
|
|
2103
2189
|
const configPath = path.join(mockDataPath, "scenario-config.json");
|
|
2104
2190
|
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
|
|
2105
2191
|
res.setHeader("Content-Type", "application/json");
|
package/dist/react-native.d.ts
CHANGED
|
@@ -15,6 +15,10 @@ export interface MockifyerInstance extends HTTPClient {
|
|
|
15
15
|
clearAllMocks: () => Promise<void>;
|
|
16
16
|
setClientId: (lane: string) => void;
|
|
17
17
|
getClientId: () => string | undefined;
|
|
18
|
+
setRecordMode: (enabled: boolean) => void;
|
|
19
|
+
isRecordMode: () => boolean;
|
|
20
|
+
setRecordResponses: (enabled: boolean) => void;
|
|
21
|
+
isRecordResponses: () => boolean;
|
|
18
22
|
enableMockifyer: () => void;
|
|
19
23
|
disableMockifyer: () => void;
|
|
20
24
|
isMockifyerEnabled: () => boolean;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolve `fetch(input, init)` into the HTTPClient shape used by the global fetch patch.
|
|
3
|
+
*
|
|
4
|
+
* Native fetch reads method/headers/body from a `Request` argument when `init` omits them.
|
|
5
|
+
* The patch historically only inspected `init`, so `fetch(new Request(url, { method, headers, body }))`
|
|
6
|
+
* was treated as GET with no headers or body.
|
|
7
|
+
*/
|
|
8
|
+
export interface ResolvedPatchedFetchRequest {
|
|
9
|
+
url: string;
|
|
10
|
+
method: string;
|
|
11
|
+
headers: Record<string, string>;
|
|
12
|
+
body: unknown;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Parse JSON text when it looks like an object/array; keep invalid JSON as the original string
|
|
16
|
+
* so the request still proceeds (native fetch does not throw on unparsable bodies).
|
|
17
|
+
*/
|
|
18
|
+
export declare function decodeFetchBodyText(text: string): unknown;
|
|
19
|
+
/**
|
|
20
|
+
* Method, headers, and body as native `fetch(input, init)` would use them.
|
|
21
|
+
* `init` fields override the `Request` argument (Fetch spec). Relative URL strings
|
|
22
|
+
* are left unchanged — `new Request('/path')` throws in Node without a base URL.
|
|
23
|
+
*/
|
|
24
|
+
export declare function resolvePatchedFetchRequest(input: RequestInfo | URL, init?: RequestInit): Promise<ResolvedPatchedFetchRequest>;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Resolve `fetch(input, init)` into the HTTPClient shape used by the global fetch patch.
|
|
4
|
+
*
|
|
5
|
+
* Native fetch reads method/headers/body from a `Request` argument when `init` omits them.
|
|
6
|
+
* The patch historically only inspected `init`, so `fetch(new Request(url, { method, headers, body }))`
|
|
7
|
+
* was treated as GET with no headers or body.
|
|
8
|
+
*/
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.decodeFetchBodyText = decodeFetchBodyText;
|
|
11
|
+
exports.resolvePatchedFetchRequest = resolvePatchedFetchRequest;
|
|
12
|
+
function isRequest(input) {
|
|
13
|
+
return typeof Request !== 'undefined' && input instanceof Request;
|
|
14
|
+
}
|
|
15
|
+
function headersToRecord(headers) {
|
|
16
|
+
const out = {};
|
|
17
|
+
if (!headers) {
|
|
18
|
+
return out;
|
|
19
|
+
}
|
|
20
|
+
if (headers instanceof Headers) {
|
|
21
|
+
headers.forEach((value, key) => {
|
|
22
|
+
out[key] = value;
|
|
23
|
+
});
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
if (Array.isArray(headers)) {
|
|
27
|
+
for (const [key, value] of headers) {
|
|
28
|
+
out[key] = value;
|
|
29
|
+
}
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
32
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
33
|
+
if (value !== undefined && value !== null) {
|
|
34
|
+
out[key] = String(value);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Parse JSON text when it looks like an object/array; keep invalid JSON as the original string
|
|
41
|
+
* so the request still proceeds (native fetch does not throw on unparsable bodies).
|
|
42
|
+
*/
|
|
43
|
+
function decodeFetchBodyText(text) {
|
|
44
|
+
const start = text.trimStart();
|
|
45
|
+
if (start.startsWith('{') || start.startsWith('[')) {
|
|
46
|
+
try {
|
|
47
|
+
return JSON.parse(text);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return text;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return text;
|
|
54
|
+
}
|
|
55
|
+
function decodeFetchBodyInit(body) {
|
|
56
|
+
if (typeof body === 'string') {
|
|
57
|
+
return decodeFetchBodyText(body);
|
|
58
|
+
}
|
|
59
|
+
return body;
|
|
60
|
+
}
|
|
61
|
+
function urlFromFetchInput(input) {
|
|
62
|
+
if (typeof input === 'string') {
|
|
63
|
+
return input;
|
|
64
|
+
}
|
|
65
|
+
if (input instanceof URL) {
|
|
66
|
+
return input.toString();
|
|
67
|
+
}
|
|
68
|
+
return input.url;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Method, headers, and body as native `fetch(input, init)` would use them.
|
|
72
|
+
* `init` fields override the `Request` argument (Fetch spec). Relative URL strings
|
|
73
|
+
* are left unchanged — `new Request('/path')` throws in Node without a base URL.
|
|
74
|
+
*/
|
|
75
|
+
async function resolvePatchedFetchRequest(input, init) {
|
|
76
|
+
const url = urlFromFetchInput(input);
|
|
77
|
+
const method = String(init?.method || (isRequest(input) ? input.method : 'GET') || 'GET');
|
|
78
|
+
const headers = headersToRecord(init?.headers !== undefined ? init.headers : isRequest(input) ? input.headers : undefined);
|
|
79
|
+
let body;
|
|
80
|
+
if (init !== undefined && init.body !== undefined && init.body !== null) {
|
|
81
|
+
body = decodeFetchBodyInit(init.body);
|
|
82
|
+
}
|
|
83
|
+
else if (isRequest(input) && method.toUpperCase() !== 'GET' && method.toUpperCase() !== 'HEAD') {
|
|
84
|
+
const text = await input.clone().text();
|
|
85
|
+
body = text ? decodeFetchBodyText(text) : undefined;
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
body = undefined;
|
|
89
|
+
}
|
|
90
|
+
return { url, method, headers, body };
|
|
91
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sgedda/mockifyer-fetch",
|
|
3
|
-
"version": "1.8.
|
|
3
|
+
"version": "1.8.106",
|
|
4
4
|
"description": "Mockifyer for Fetch - API mocking and logging utility for storing and replaying API responses",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
},
|
|
50
50
|
"license": "MIT",
|
|
51
51
|
"dependencies": {
|
|
52
|
-
"@sgedda/mockifyer-core": "^1.10.
|
|
52
|
+
"@sgedda/mockifyer-core": "^1.10.190"
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
55
|
"@types/node": "^20.11.24",
|
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
},
|
|
58
58
|
"peerDependencies": {
|
|
59
59
|
"@sgedda/mockifyer-axios": "*",
|
|
60
|
-
"axios": "^1.6.0 || ^1.7.0",
|
|
60
|
+
"axios": "^1.6.0 || ^1.7.0 || ^1.20.0",
|
|
61
61
|
"react-native-launch-arguments": ">=4.0.0"
|
|
62
62
|
},
|
|
63
63
|
"peerDependenciesMeta": {
|
|
@@ -12,6 +12,61 @@ import {
|
|
|
12
12
|
} from '@sgedda/mockifyer-core';
|
|
13
13
|
import { performDashboardProxyRequest } from '../core-proxy';
|
|
14
14
|
|
|
15
|
+
function headerContentType(headers: Headers): string | undefined {
|
|
16
|
+
const contentType = headers.get('content-type');
|
|
17
|
+
return contentType ? contentType.toLowerCase() : undefined;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Native Fetch body types that must not be JSON.stringified (bypass / direct upstream). */
|
|
21
|
+
function isNativeFetchBody(value: unknown): value is BodyInit {
|
|
22
|
+
return (
|
|
23
|
+
typeof value === 'string' ||
|
|
24
|
+
(typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) ||
|
|
25
|
+
(typeof FormData !== 'undefined' && value instanceof FormData) ||
|
|
26
|
+
(typeof Blob !== 'undefined' && value instanceof Blob) ||
|
|
27
|
+
(typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) ||
|
|
28
|
+
(typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(value))
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function plainObjectToUrlEncoded(body: Record<string, unknown>): URLSearchParams {
|
|
33
|
+
const params = new URLSearchParams();
|
|
34
|
+
for (const [key, value] of Object.entries(body)) {
|
|
35
|
+
if (value === undefined || value === null) continue;
|
|
36
|
+
params.append(key, String(value));
|
|
37
|
+
}
|
|
38
|
+
return params;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Build a RequestInit body for direct (non-proxy) fetch.
|
|
43
|
+
* JSON.stringify on URLSearchParams/FormData yields "{}" and corrupts OAuth/uploads on bypass paths.
|
|
44
|
+
*/
|
|
45
|
+
function buildDirectFetchBody(
|
|
46
|
+
data: unknown,
|
|
47
|
+
method: string,
|
|
48
|
+
headers: Headers
|
|
49
|
+
): BodyInit | undefined {
|
|
50
|
+
const upperMethod = method.toUpperCase();
|
|
51
|
+
if (upperMethod === 'GET' || upperMethod === 'HEAD' || data === undefined || data === null) {
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (isNativeFetchBody(data)) {
|
|
56
|
+
return data;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (
|
|
60
|
+
typeof data === 'object' &&
|
|
61
|
+
!Array.isArray(data) &&
|
|
62
|
+
headerContentType(headers)?.includes('application/x-www-form-urlencoded')
|
|
63
|
+
) {
|
|
64
|
+
return plainObjectToUrlEncoded(data as Record<string, unknown>);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return JSON.stringify(data);
|
|
68
|
+
}
|
|
69
|
+
|
|
15
70
|
export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
|
|
16
71
|
private baseUrl?: string;
|
|
17
72
|
private defaultHeaders: Record<string, string>;
|
|
@@ -117,7 +172,7 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
|
|
|
117
172
|
const requestConfig: RequestInit = {
|
|
118
173
|
method: config.method || 'GET',
|
|
119
174
|
headers,
|
|
120
|
-
body: config.data
|
|
175
|
+
body: buildDirectFetchBody(config.data, config.method || 'GET', headers),
|
|
121
176
|
};
|
|
122
177
|
|
|
123
178
|
// Use original fetch if available (when global fetch is patched), otherwise use global fetch
|
|
@@ -201,6 +256,16 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
|
|
|
201
256
|
};
|
|
202
257
|
}
|
|
203
258
|
|
|
259
|
+
/** Update whether `/api/proxy` sends `record` (record-on-miss). */
|
|
260
|
+
setProxyRecordOnMiss(recordOnMiss: boolean | undefined): void {
|
|
261
|
+
this.proxyRecordOnMiss = recordOnMiss;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Update whether `/api/proxy` asks the dashboard to store response bodies. */
|
|
265
|
+
setProxyRecordResponses(recordResponses: boolean): void {
|
|
266
|
+
this.proxyRecordResponses = recordResponses;
|
|
267
|
+
}
|
|
268
|
+
|
|
204
269
|
protected getDefaultHeaders(): Record<string, string> {
|
|
205
270
|
return this.defaultHeaders;
|
|
206
271
|
}
|