The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import { msg } from "gt-i18n"; |
| 2 | import { translatableError } from "./errors/translatable.ts"; |
| 3 | import { decodeFilePreviewText, FILE_TEXT_PREVIEW_MAX_BYTES } from "@t3tools/shared/filePreview"; |
| 4 | |
| 5 | /** Consume only a bounded prefix, even when a host ignores the requested HTTP range. */ |
| 6 | export async function readFilePreviewResponse( |
| 7 | response: Pick<Response, "ok" | "body">, |
| 8 | signal: AbortSignal, |
| 9 | ) { |
| 10 | if (!response.ok) { |
| 11 | // A streamed error body holds the connection open until GC otherwise. |
| 12 | void response.body?.cancel().catch(() => undefined); |
| 13 | throw translatableError(msg("The file could not be loaded. Reconnect and try again.")); |
| 14 | } |
| 15 | if (signal.aborted) throw translatableError(msg("Preview cancelled.")); |
| 16 | const limit = FILE_TEXT_PREVIEW_MAX_BYTES + 1; |
| 17 | const reader = response.body?.getReader(); |
| 18 | if (!reader) |
| 19 | throw translatableError(msg("Streaming file previews are unavailable in this runtime.")); |
| 20 | const cancel = () => { |
| 21 | void reader.cancel().catch(() => undefined); |
| 22 | }; |
| 23 | signal.addEventListener("abort", cancel, { once: true }); |
| 24 | const chunks: Uint8Array[] = []; |
| 25 | let length = 0; |
| 26 | try { |
| 27 | while (length < limit) { |
| 28 | if (signal.aborted) throw translatableError(msg("Preview cancelled.")); |
| 29 | const next = await reader.read(); |
| 30 | if (next.done) break; |
| 31 | const chunk = next.value.subarray(0, limit - length); |
| 32 | chunks.push(chunk); |
| 33 | length += chunk.length; |
| 34 | } |
| 35 | } finally { |
| 36 | signal.removeEventListener("abort", cancel); |
| 37 | await reader.cancel(); |
| 38 | } |
| 39 | if (signal.aborted) throw translatableError(msg("Preview cancelled.")); |
| 40 | const bytes = new Uint8Array(length); |
| 41 | let offset = 0; |
| 42 | for (const chunk of chunks) { |
| 43 | bytes.set(chunk, offset); |
| 44 | offset += chunk.length; |
| 45 | } |
| 46 | return decodeFilePreviewText(bytes); |
| 47 | } |