UNPKG

@copilotkit/shared

Version:

<img src="https://github.com/user-attachments/assets/0a6b64d9-e193-4940-a3f6-60334ac34084" alt="banner" style="border-radius: 12px; border: 2px solid #d6d4fa;" />

1 lines 3.58 kB
{"version":3,"sources":["../src/utils/requests.ts"],"sourcesContent":["/**\n * Safely read a Response/Request body with sensible defaults:\n * - clones the response/request to avoid consuming the original response/request\n * - Skips GET/HEAD\n * - Tries JSON first regardless of content-type\n * - Falls back to text and optionally parses when it \"looks\" like JSON\n */\nexport async function readBody<T extends Response | Request>(r: T): Promise<unknown> {\n // skip GET/HEAD requests (unchanged)\n const method = \"method\" in r ? r.method.toUpperCase() : undefined;\n if (method === \"GET\" || method === \"HEAD\") {\n return undefined;\n }\n\n // no body at all → undefined (unchanged)\n if (!(\"body\" in r) || r.body == null) {\n return undefined;\n }\n\n // 1) try JSON (unchanged)\n try {\n return await r.clone().json();\n } catch {\n // 2) try text (unchanged + your whitespace/JSON-heuristic)\n try {\n const text = await r.clone().text();\n const trimmed = text.trim();\n\n if (trimmed.length === 0) return text;\n\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n try {\n return JSON.parse(trimmed);\n } catch {\n return text;\n }\n }\n return text;\n } catch {\n // 3) FINAL FALLBACK: manual read that accepts string or bytes\n try {\n const c = r.clone();\n const stream: ReadableStream | null = c.body ?? null;\n if (!stream) return undefined;\n\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let out = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (typeof value === \"string\") {\n out += value; // accept string chunks\n } else {\n out += decoder.decode(value, { stream: true }); // bytes\n }\n }\n out += decoder.decode(); // flush\n\n const trimmed = out.trim();\n if (trimmed.length === 0) return out;\n\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n try {\n return JSON.parse(trimmed);\n } catch {\n return out;\n }\n }\n return out;\n } catch {\n return undefined; // same \"give up\" behavior you had\n }\n }\n }\n}\n"],"mappings":";AAOA,eAAsB,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