@sgedda/mockifyer-fetch 1.8.98 → 1.8.104

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.
@@ -419,25 +419,110 @@ function getMockFilePathLocal(
419
419
  }
420
420
 
421
421
  /**
422
- * Get current scenario from scenario-config.json
422
+ * Scenario folder names the dashboard accepts (one path segment).
423
+ * `pool` is the fixture-pool directory and is not a scenario.
424
+ */
425
+ const SAFE_SCENARIO_NAME = /^[a-zA-Z0-9_-]+$/;
426
+ const FIXTURE_POOL_DIR_NAME = "pool";
427
+
428
+ /** True when `candidate` is `root` or a file/directory inside it. */
429
+ function isInsideDirectory(root: string, candidate: string): boolean {
430
+ const rootResolved = path.resolve(root);
431
+ const target = path.resolve(candidate);
432
+ const prefix = rootResolved.endsWith(path.sep)
433
+ ? rootResolved
434
+ : rootResolved + path.sep;
435
+ return target === rootResolved || target.startsWith(prefix);
436
+ }
437
+
438
+ /**
439
+ * Accept a scenario name that can be used as a single directory under mock-data.
440
+ * Rejects traversal (`..`, slashes), absolute paths, and the reserved `pool` directory.
441
+ */
442
+ function sanitizeScenarioName(raw: unknown): string | null {
443
+ if (typeof raw !== "string") {
444
+ return null;
445
+ }
446
+ const trimmed = raw.trim();
447
+ if (
448
+ !trimmed ||
449
+ trimmed === FIXTURE_POOL_DIR_NAME ||
450
+ !SAFE_SCENARIO_NAME.test(trimmed)
451
+ ) {
452
+ return null;
453
+ }
454
+ return trimmed;
455
+ }
456
+
457
+ /** Absolute scenario directory, or null when `scenario` would escape mock-data. */
458
+ function resolveScenarioDirectory(
459
+ mockDataPath: string,
460
+ scenario: string,
461
+ ): string | null {
462
+ const name = sanitizeScenarioName(scenario);
463
+ if (!name) {
464
+ return null;
465
+ }
466
+ const dir = path.resolve(mockDataPath, name);
467
+ if (!isInsideDirectory(mockDataPath, dir)) {
468
+ return null;
469
+ }
470
+ return dir;
471
+ }
472
+
473
+ /**
474
+ * Relative `.json` path under a scenario folder (for example `redis/<hash>.json`).
475
+ * Rejects absolute paths and `.` / `..` segments.
476
+ */
477
+ function sanitizeMockRelativePath(raw: string): string | null {
478
+ const normalized = raw.trim().replace(/\\/g, "/").replace(/^\/+/, "");
479
+ if (!normalized.endsWith(".json") || normalized.includes("\0")) {
480
+ return null;
481
+ }
482
+ const segments = normalized.split("/");
483
+ if (segments.some((seg) => seg.length === 0 || seg === "." || seg === "..")) {
484
+ return null;
485
+ }
486
+ return normalized;
487
+ }
488
+
489
+ /** Absolute mock file path inside `scenarioDir`, or null when the relative path escapes. */
490
+ function resolveMockFilePath(
491
+ scenarioDir: string,
492
+ relativePath: string,
493
+ ): string | null {
494
+ const rel = sanitizeMockRelativePath(relativePath);
495
+ if (!rel) {
496
+ return null;
497
+ }
498
+ const filePath = path.resolve(scenarioDir, rel);
499
+ if (!isInsideDirectory(scenarioDir, filePath) || filePath === path.resolve(scenarioDir)) {
500
+ return null;
501
+ }
502
+ return filePath;
503
+ }
504
+
505
+ /**
506
+ * Get current scenario from env or scenario-config.json.
507
+ * Unsafe names (path traversal, reserved `pool`) are ignored.
423
508
  */
424
509
  function getCurrentScenario(mockDataPath: string): string {
425
- // Check environment variable first
426
- if (process.env.MOCKIFYER_SCENARIO) {
427
- return process.env.MOCKIFYER_SCENARIO;
510
+ const fromEnv = sanitizeScenarioName(process.env.MOCKIFYER_SCENARIO);
511
+ if (fromEnv) {
512
+ return fromEnv;
428
513
  }
429
514
 
430
- // Try to load from scenario-config.json
431
515
  try {
432
516
  const configPath = path.join(mockDataPath, "scenario-config.json");
433
517
  if (fs.existsSync(configPath)) {
434
518
  const fileContent = fs.readFileSync(configPath, "utf-8");
435
519
  const config = JSON.parse(fileContent);
436
- if (config.currentScenario) {
437
- return config.currentScenario;
520
+ const fromFile = sanitizeScenarioName(config.currentScenario);
521
+ if (fromFile) {
522
+ return fromFile;
438
523
  }
439
524
  }
440
- } catch (error) {
525
+ } catch {
441
526
  // Silently fail - file might not exist or be invalid
442
527
  }
443
528
 
@@ -445,11 +530,15 @@ function getCurrentScenario(mockDataPath: string): string {
445
530
  }
446
531
 
447
532
  /**
448
- * Get scenario folder path
533
+ * Scenario folder under mock-data. Throws when `scenario` is not a safe single segment
534
+ * so a poisoned name cannot mkdir outside the mock-data tree.
449
535
  */
450
536
  function getScenarioPath(scenario: string, mockDataPath: string): string {
451
- // Always create scenario subfolder, even for 'default'
452
- return path.join(mockDataPath, scenario);
537
+ const dir = resolveScenarioDirectory(mockDataPath, scenario);
538
+ if (!dir) {
539
+ throw new Error(`Invalid scenario name: ${scenario}`);
540
+ }
541
+ return dir;
453
542
  }
454
543
 
455
544
  /**
@@ -731,17 +820,22 @@ function saveProxyMirrorMockToProject(
731
820
  error: "Mock data contains nested Mockifyer sync requests",
732
821
  };
733
822
  }
734
- const id = scenarioName.trim();
823
+ const id = sanitizeScenarioName(scenarioName);
735
824
  if (!id) {
736
- return { success: false, error: "scenarioName is required" };
825
+ return { success: false, error: "Invalid scenarioName" };
737
826
  }
738
- const normalized = relativePath.replace(/\\/g, "/").replace(/^\//, "");
827
+ const normalized = sanitizeMockRelativePath(relativePath);
739
828
  if (!normalized) {
740
- return { success: false, error: "relativePath is required" };
829
+ return { success: false, error: "Invalid relativePath" };
830
+ }
831
+ const scenarioPath = resolveScenarioDirectory(mockDataPath, id);
832
+ const filePath = scenarioPath
833
+ ? resolveMockFilePath(scenarioPath, normalized)
834
+ : null;
835
+ if (!scenarioPath || !filePath) {
836
+ return { success: false, error: "Invalid relativePath" };
741
837
  }
742
- const scenarioPath = getScenarioPath(id, mockDataPath);
743
838
  fs.mkdirSync(scenarioPath, { recursive: true });
744
- const filePath = path.join(scenarioPath, normalized);
745
839
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
746
840
  fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
747
841
  if (testConfig) {
@@ -1397,6 +1491,23 @@ export function bufferAtlasBodySpill(
1397
1491
  return { success: true, relativePath: buffered };
1398
1492
  }
1399
1493
 
1494
+ /**
1495
+ * Write hop bodies for an Atlas HTML render.
1496
+ *
1497
+ * Device uploads sit in the Metro spill buffer and are often omitted from the
1498
+ * render POST (`bodySpills` is capped at 2MB, so a max-size body never fits).
1499
+ * Flush that buffer before writing the payload. Buffering the payload first
1500
+ * evicts older spills once the in-memory cap is hit, and those files are then
1501
+ * missing from disk.
1502
+ */
1503
+ export function persistAtlasRenderBodySpills(
1504
+ outDir: string,
1505
+ bodySpills: Record<string, string> | undefined,
1506
+ ): number {
1507
+ const flushed = flushNetworkBodySpillsToDir(outDir);
1508
+ return flushed + writeNetworkBodySpillMap(outDir, bodySpills);
1509
+ }
1510
+
1400
1511
  const ATLAS_HTML_CONTENT_TYPES: Record<string, string> = {
1401
1512
  ".html": "text/html; charset=utf-8",
1402
1513
  ".htm": "text/html; charset=utf-8",
@@ -2053,8 +2164,16 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
2053
2164
  const scenarioParam = params.get("scenario");
2054
2165
  const scenarioName =
2055
2166
  scenarioParam && scenarioParam.trim() !== ""
2056
- ? scenarioParam.trim()
2167
+ ? sanitizeScenarioName(scenarioParam)
2057
2168
  : getCurrentScenario(mockDataPath);
2169
+ if (!scenarioName) {
2170
+ res.statusCode = 400;
2171
+ res.setHeader("Content-Type", "application/json");
2172
+ res.end(
2173
+ JSON.stringify({ success: false, error: "Invalid scenario name" }),
2174
+ );
2175
+ return;
2176
+ }
2058
2177
  const rules = readDomainPathRulesFile(mockDataPath, scenarioName);
2059
2178
  res.setHeader("Content-Type", "application/json");
2060
2179
  res.end(JSON.stringify({ success: true, scenario: scenarioName, rules }));
@@ -2073,11 +2192,47 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
2073
2192
  scenario?: string;
2074
2193
  upserts?: DomainPathRulesMap;
2075
2194
  rules?: DomainPathRulesMap;
2195
+ /** When true, replace the scenario file with `rules` (enable-record migrations). */
2196
+ replace?: boolean;
2076
2197
  };
2077
2198
  const scenarioName =
2078
2199
  typeof parsed.scenario === "string" && parsed.scenario.trim() !== ""
2079
- ? parsed.scenario.trim()
2200
+ ? sanitizeScenarioName(parsed.scenario)
2080
2201
  : getCurrentScenario(mockDataPath);
2202
+ if (!scenarioName) {
2203
+ res.statusCode = 400;
2204
+ res.setHeader("Content-Type", "application/json");
2205
+ res.end(
2206
+ JSON.stringify({ success: false, error: "Invalid scenario name" }),
2207
+ );
2208
+ return;
2209
+ }
2210
+
2211
+ if (parsed.replace === true) {
2212
+ const updates = parseDomainPathRules(parsed.rules ?? {});
2213
+ // Re-read to pick up concurrent new keys, then apply recordResponses updates.
2214
+ const existing = readDomainPathRulesFile(mockDataPath, scenarioName);
2215
+ const merged: DomainPathRulesMap = { ...updates };
2216
+ // Add any new keys that were discovered concurrently but preserve the recordResponses updates.
2217
+ for (const [key, rule] of Object.entries(existing)) {
2218
+ if (!merged[key]) {
2219
+ merged[key] = { ...rule };
2220
+ }
2221
+ }
2222
+ writeDomainPathRulesFile(mockDataPath, scenarioName, merged);
2223
+ res.setHeader("Content-Type", "application/json");
2224
+ res.end(
2225
+ JSON.stringify({
2226
+ success: true,
2227
+ changed: true,
2228
+ replaced: true,
2229
+ scenario: scenarioName,
2230
+ rules: merged,
2231
+ }),
2232
+ );
2233
+ return;
2234
+ }
2235
+
2081
2236
  const upserts = parseDomainPathRules(
2082
2237
  parsed.upserts ?? parsed.rules ?? {},
2083
2238
  );
@@ -2447,7 +2602,10 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
2447
2602
  }
2448
2603
  setAtlasDocMap(doc);
2449
2604
  setAtlasDocHtmlOutputPath(outDir);
2450
- const spillWritten = writeNetworkBodySpillMap(outDir, parsed.bodySpills);
2605
+ const spillWritten = persistAtlasRenderBodySpills(
2606
+ outDir,
2607
+ parsed.bodySpills,
2608
+ );
2451
2609
  const events = Array.isArray(parsed.events) ? parsed.events : [];
2452
2610
  const written = writeAtlasDocHtml(outDir, doc, events);
2453
2611
  const relativeFromRoot = path
@@ -2654,10 +2812,13 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
2654
2812
  try {
2655
2813
  // Check environment variable first (highest priority)
2656
2814
  if (process.env.MOCKIFYER_SCENARIO) {
2815
+ const fromEnv =
2816
+ sanitizeScenarioName(process.env.MOCKIFYER_SCENARIO) ||
2817
+ DEFAULT_SCENARIO;
2657
2818
  logger.debug(
2658
- `[MetroSyncMiddleware] Using scenario from MOCKIFYER_SCENARIO env var: ${process.env.MOCKIFYER_SCENARIO}`,
2819
+ `[MetroSyncMiddleware] Using scenario from MOCKIFYER_SCENARIO env var: ${fromEnv}`,
2659
2820
  );
2660
- writeScenarioResponse(process.env.MOCKIFYER_SCENARIO);
2821
+ writeScenarioResponse(fromEnv);
2661
2822
  return;
2662
2823
  }
2663
2824
 
@@ -2674,7 +2835,8 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
2674
2835
  const fileContent = fs.readFileSync(configPath, "utf-8");
2675
2836
  logger.debug(`[MetroSyncMiddleware] File content: ${fileContent}`);
2676
2837
  const config = JSON.parse(fileContent);
2677
- const scenario = config.currentScenario || DEFAULT_SCENARIO;
2838
+ const scenario =
2839
+ sanitizeScenarioName(config.currentScenario) || DEFAULT_SCENARIO;
2678
2840
  logger.debug(
2679
2841
  `[MetroSyncMiddleware] Found scenario in config: ${scenario} (from file: ${JSON.stringify(config)})`,
2680
2842
  );
@@ -2708,6 +2870,20 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
2708
2870
  req.on("end", () => {
2709
2871
  try {
2710
2872
  const config = JSON.parse(body);
2873
+ if (
2874
+ config &&
2875
+ typeof config === "object" &&
2876
+ typeof config.currentScenario === "string" &&
2877
+ config.currentScenario.trim() !== "" &&
2878
+ !sanitizeScenarioName(config.currentScenario)
2879
+ ) {
2880
+ res.statusCode = 400;
2881
+ res.setHeader("Content-Type", "application/json");
2882
+ res.end(
2883
+ JSON.stringify({ success: false, error: "Invalid scenario name" }),
2884
+ );
2885
+ return;
2886
+ }
2711
2887
  const configPath = path.join(mockDataPath, "scenario-config.json");
2712
2888
  fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
2713
2889
  res.setHeader("Content-Type", "application/json");
@@ -36,6 +36,10 @@ export interface MockifyerInstance extends HTTPClient {
36
36
  clearAllMocks: () => Promise<void>;
37
37
  setClientId: (lane: string) => void;
38
38
  getClientId: () => string | undefined;
39
+ setRecordMode: (enabled: boolean) => void;
40
+ isRecordMode: () => boolean;
41
+ setRecordResponses: (enabled: boolean) => void;
42
+ isRecordResponses: () => boolean;
39
43
  enableMockifyer: () => void;
40
44
  disableMockifyer: () => void;
41
45
  isMockifyerEnabled: () => boolean;
@@ -44,7 +48,7 @@ export interface MockifyerInstance extends HTTPClient {
44
48
  /**
45
49
  * Outcome of {@link setupMockifyerForReactNative}.
46
50
  *
47
- * - **`not_activated`** — `fetch` was not patched this run (see **`MOCKIFYER_MODE`** / `runtimeMode`: `off`, or `launch_client` without a launch-arg lane).
51
+ * - **`not_activated`** — `fetch` was not patched this run (see **`MOCKIFYER_MODE`** / `runtimeMode`: `off`, or `launch_client` without a launch-arg lane or scenario).
48
52
  * Not the same as “permanently off” unless mode is **`off`** (then launch args do not activate).
49
53
  * - **`active`** — Mockifyer initialized and patched `global.fetch`.
50
54
  * - **`failed_no_bundled_mocks`** — Activation criteria were met and `isDev` was false, but bundled mock data was missing or empty.
@@ -95,7 +99,9 @@ export interface ReactNativeMockifyerConfig {
95
99
  /**
96
100
  * When true, reads `scenario` from `react-native-launch-arguments` (optional peer).
97
101
  * Highest priority over MOCKIFYER_SCENARIO, config.scenarios, Metro scenario sync, and scenario-config.json.
98
- * When a launch `scenario` is present, Mockifyer also **starts enabled** (even with `runtimeMode: 'manual'`).
102
+ * When a launch `scenario` is present, Mockifyer **activates** (also under `launch_client`, no lane needed),
103
+ * **starts enabled** (even with `runtimeMode: 'manual'`), and sends it as the dashboard proxy scenario
104
+ * (unless `proxyScenario` is set). `runtimeMode: 'off'` still wins.
99
105
  * Set to `false` to ignore launch scenario args entirely.
100
106
  * Default: auto-detect when a non-empty launch `scenario` is present.
101
107
  */
@@ -147,21 +153,20 @@ export interface ReactNativeMockifyerConfig {
147
153
 
148
154
  /**
149
155
  * Apply scenario from launch arguments and/or defaultScenario (highest priority in getCurrentScenario).
150
- * @returns `true` when a native launch-argument `scenario` was applied (forces runtime toggle on).
156
+ * @returns The native launch-argument `scenario` when one was applied (activates Mockifyer, forces runtime toggle on,
157
+ * and is sent as the proxy scenario); otherwise `undefined`.
151
158
  */
152
- function applyReactNativeScenarioOptions(options: ReactNativeMockifyerConfig): boolean {
153
- let appliedFromLaunchArgs = false;
154
-
159
+ function applyReactNativeScenarioOptions(options: ReactNativeMockifyerConfig): string | undefined {
155
160
  // Auto-detect launch `scenario` when present (E2E). Opt out with useLaunchArgumentsScenario: false.
156
161
  if (options.useLaunchArgumentsScenario !== false) {
157
162
  const scenarioFromLaunch = tryGetScenarioFromLaunchArguments();
158
163
  if (scenarioFromLaunch) {
159
164
  setScenarioLaunchOverride(scenarioFromLaunch, { fromLaunchArguments: true });
160
- appliedFromLaunchArgs = true;
165
+ return scenarioFromLaunch;
161
166
  }
162
167
  }
163
168
 
164
- if (!appliedFromLaunchArgs && options.defaultScenario !== undefined && options.defaultScenario !== null) {
169
+ if (options.defaultScenario !== undefined && options.defaultScenario !== null) {
165
170
  const t = String(options.defaultScenario).trim();
166
171
  if (t !== '') {
167
172
  // App config default — not a native launch arg; do not force runtime toggle on.
@@ -169,7 +174,7 @@ function applyReactNativeScenarioOptions(options: ReactNativeMockifyerConfig): b
169
174
  }
170
175
  }
171
176
 
172
- return appliedFromLaunchArgs;
177
+ return undefined;
173
178
  }
174
179
 
175
180
  // Lazy load bundled data (only used in production builds)
@@ -279,7 +284,11 @@ export async function setupMockifyerForReactNative(
279
284
  }
280
285
 
281
286
  // Apply scenario launch override early so we know if E2E forced a scenario.
282
- const launchScenarioApplied = applyReactNativeScenarioOptions(options);
287
+ const launchScenario = applyReactNativeScenarioOptions(options);
288
+ const launchScenarioApplied = launchScenario !== undefined;
289
+ // Launch `scenario` travels on every dashboard proxy request (body override wins over lane / global scenario),
290
+ // so E2E does not need a lane mapped in the dashboard. An explicit `proxyScenario` still wins.
291
+ const effectiveProxyScenario = proxyScenario ?? launchScenario;
283
292
  if (launchScenarioApplied) {
284
293
  // Launch `scenario` arg → start enabled (wins over persisted off for this session).
285
294
  initialRuntimeEnabled = true;
@@ -309,8 +318,7 @@ export async function setupMockifyerForReactNative(
309
318
  return 'React Native dev · hybrid (device + Metro)';
310
319
  };
311
320
 
312
- // Patch fetch for on / manual; launch_client only when lane id is present.
313
- // Launch `scenario` forces runtime toggle on after activation — it does not replace client id.
321
+ // Patch fetch for on / manual; launch_client when a launch lane id or launch scenario is present.
314
322
  const isEnabled = shouldActivateMockifyerForReactNative({
315
323
  runtimeMode: resolvedRuntimeMode,
316
324
  hasLaunchClientId: Boolean(clientIdFromLaunchArgs),
@@ -387,7 +395,7 @@ export async function setupMockifyerForReactNative(
387
395
  strictProxyEnabled && proxyBaseUrl
388
396
  ? {
389
397
  baseUrl: proxyBaseUrl,
390
- scenario: proxyScenario,
398
+ scenario: effectiveProxyScenario,
391
399
  recordOnMiss: proxyShouldRecordOnMiss,
392
400
  recordResponses: proxyShouldRecordResponses,
393
401
  }
@@ -457,7 +465,7 @@ export async function setupMockifyerForReactNative(
457
465
  proxy: proxyBaseUrl
458
466
  ? {
459
467
  baseUrl: proxyBaseUrl,
460
- scenario: proxyScenario,
468
+ scenario: effectiveProxyScenario,
461
469
  recordOnMiss: proxyShouldRecordOnMiss,
462
470
  recordResponses: proxyShouldRecordResponses,
463
471
  }
@@ -0,0 +1,105 @@
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
+
9
+ export interface ResolvedPatchedFetchRequest {
10
+ url: string;
11
+ method: string;
12
+ headers: Record<string, string>;
13
+ body: unknown;
14
+ }
15
+
16
+ function isRequest(input: unknown): input is Request {
17
+ return typeof Request !== 'undefined' && input instanceof Request;
18
+ }
19
+
20
+ function headersToRecord(headers: HeadersInit | undefined): Record<string, string> {
21
+ const out: Record<string, string> = {};
22
+ if (!headers) {
23
+ return out;
24
+ }
25
+ if (headers instanceof Headers) {
26
+ headers.forEach((value, key) => {
27
+ out[key] = value;
28
+ });
29
+ return out;
30
+ }
31
+ if (Array.isArray(headers)) {
32
+ for (const [key, value] of headers) {
33
+ out[key] = value;
34
+ }
35
+ return out;
36
+ }
37
+ for (const [key, value] of Object.entries(headers)) {
38
+ if (value !== undefined && value !== null) {
39
+ out[key] = String(value);
40
+ }
41
+ }
42
+ return out;
43
+ }
44
+
45
+ /**
46
+ * Parse JSON text when it looks like an object/array; keep invalid JSON as the original string
47
+ * so the request still proceeds (native fetch does not throw on unparsable bodies).
48
+ */
49
+ export function decodeFetchBodyText(text: string): unknown {
50
+ const start = text.trimStart();
51
+ if (start.startsWith('{') || start.startsWith('[')) {
52
+ try {
53
+ return JSON.parse(text);
54
+ } catch {
55
+ return text;
56
+ }
57
+ }
58
+ return text;
59
+ }
60
+
61
+ function decodeFetchBodyInit(body: BodyInit): unknown {
62
+ if (typeof body === 'string') {
63
+ return decodeFetchBodyText(body);
64
+ }
65
+ return body;
66
+ }
67
+
68
+ function urlFromFetchInput(input: RequestInfo | URL): string {
69
+ if (typeof input === 'string') {
70
+ return input;
71
+ }
72
+ if (input instanceof URL) {
73
+ return input.toString();
74
+ }
75
+ return input.url;
76
+ }
77
+
78
+ /**
79
+ * Method, headers, and body as native `fetch(input, init)` would use them.
80
+ * `init` fields override the `Request` argument (Fetch spec). Relative URL strings
81
+ * are left unchanged — `new Request('/path')` throws in Node without a base URL.
82
+ */
83
+ export async function resolvePatchedFetchRequest(
84
+ input: RequestInfo | URL,
85
+ init?: RequestInit
86
+ ): Promise<ResolvedPatchedFetchRequest> {
87
+ const url = urlFromFetchInput(input);
88
+ const method = String(init?.method || (isRequest(input) ? input.method : 'GET') || 'GET');
89
+
90
+ const headers = headersToRecord(
91
+ init?.headers !== undefined ? init.headers : isRequest(input) ? input.headers : undefined
92
+ );
93
+
94
+ let body: unknown;
95
+ if (init !== undefined && init.body !== undefined && init.body !== null) {
96
+ body = decodeFetchBodyInit(init.body);
97
+ } else if (isRequest(input) && method.toUpperCase() !== 'GET' && method.toUpperCase() !== 'HEAD') {
98
+ const text = await input.clone().text();
99
+ body = text ? decodeFetchBodyText(text) : undefined;
100
+ } else {
101
+ body = undefined;
102
+ }
103
+
104
+ return { url, method, headers, body };
105
+ }