Body viewer and decode fixes (#812)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Gregory SchierandClaude Opus 5.5 authored and GitHub committed 2026-11-04 21:21:05 -07:00
1 parent 87a30200f9
commit 4ad0533901
26 files changed
+1633 -91

No files matched your search

@@ -1,13 +1,14 @@
import type { WebsocketEvent, WebsocketRequest } from "@yaakapp-internal/models";
import {
HStack,
hexdump,
HexdumpViewer,
Icon,
LoadingIcon,
VStack,
useStateWithDeps,
languageFromContentType,
} from "@yaakapp-internal/ui";
import { hexy } from "hexy";
import { useAtomValue } from "jotai";
import { useMemo, useState } from "react";
import { useFormatText } from "../hooks/useFormatText";
@@ -19,6 +20,7 @@ import {
} from "../hooks/usePinnedWebsocketConnection";
import { Button } from "./core/Button";
import { Editor } from "./core/Editor/LazyEditor";
import { renderEditor } from "./core/Editor/renderEditor";
import { type EventDetailAction, EventDetailHeader, EventViewer } from "./core/EventViewer";
import { EventViewerRow } from "./core/EventViewerRow";
import { HotkeyList } from "./core/HotkeyList";
@@ -122,10 +124,10 @@ function WebsocketEventRow({
messageType === "error"
? "alert_triangle"
: messageType === "close" || messageType === "open"
? "info"
: isServer
? "arrow_big_down_dash"
: "arrow_big_up_dash";
? "info"
: isServer
? "arrow_big_down_dash"
: "arrow_big_up_dash";
const content =
messageType === "close" ? (
@@ -172,7 +174,7 @@ function WebsocketEventDetail({
}) {
const message = useMemo(() => {
if (hexDump) {
return event.message ? hexy(event.message) : "";
return event.message ? hexdump(event.message) : "";
}
return event.message ? new TextDecoder("utf-8").decode(Uint8Array.from(event.message)) : "";
}, [event.message, hexDump]);
@@ -232,6 +234,8 @@ function WebsocketEventDetail({
</VStack>
) : event.message.length === 0 ? (
<EmptyStateText>No Content</EmptyStateText>
) : hexDump ? (
<HexdumpViewer data={event.message} renderEditor={renderEditor} />
) : (
<Editor
language={language}
+3 -1
View File
@@ -1,5 +1,7 @@
import { useQuery } from "@tanstack/react-query";
import type { HttpResponse } from "@yaakapp-internal/models";
import { decodeBodyText } from "@yaakapp-internal/lib/decodeBodyText";
import { getContentTypeFromHeaders } from "../lib/model_util";
import { rpc } from "../lib/rpc";
export function useHttpRequestBody(response: HttpResponse | null) {
@@ -27,6 +29,6 @@ export async function getRequestBodyText(response: HttpResponse | null) {
}
const body = new Uint8Array(data);
const bodyText = new TextDecoder("utf-8", { fatal: false }).decode(body);
const bodyText = decodeBodyText(body, getContentTypeFromHeaders(response.requestHeaders));
return { body, bodyText };
}
-9
View File
@@ -5,7 +5,6 @@ import type {
HttpResponseEvent,
HttpResponseHeader,
} from "@yaakapp-internal/models";
import { getMimeTypeFromContentType } from "./contentType";
export const BODY_TYPE_NONE = null;
export const BODY_TYPE_GRAPHQL = "graphql";
@@ -46,14 +45,6 @@ export function getContentTypeFromHeaders(headers: HttpResponseHeader[] | null):
return headers?.find((h) => h.name.toLowerCase() === "content-type")?.value ?? null;
}
export function getCharsetFromContentType(headers: HttpResponseHeader[]): string | null {
const contentType = getContentTypeFromHeaders(headers);
if (contentType == null) return null;
const mimeType = getMimeTypeFromContentType(contentType);
return mimeType.parameters.get("charset") ?? null;
}
export function isBaseEnvironment(environment: Environment): boolean {
return environment.parentModel === "workspace";
}
+4 -1
View File
@@ -3,7 +3,9 @@ import type { FilterResponse } from "@yaakapp-internal/plugins";
import type { ServerSentEvent, SseSummary } from "@yaakapp-internal/sse";
import { candidateJsonPayloadsFromSseText, computeSseSummary } from "@yaakapp-internal/sse";
import { rpc } from "./rpc";
import { decodeBodyText } from "@yaakapp-internal/lib/decodeBodyText";
import { platform } from "@yaakapp-internal/platform";
import { getContentTypeFromHeaders } from "./model_util";
/**
* Reading a response body means naming the response, never the file it lives
@@ -74,5 +76,6 @@ export async function getResponseBodyBytes(
async function getResponseBodyDecoded(response: HttpResponse): Promise<string | null> {
const bytes = await getResponseBodyBytes(response);
return bytes == null ? null : new TextDecoder("utf-8").decode(bytes);
if (bytes == null) return null;
return decodeBodyText(bytes, getContentTypeFromHeaders(response.headers));
}
-1
View File
@@ -48,7 +48,6 @@
"focus-trap-react": "^12.0.3",
"fuzzbunny": "^1.0.1",
"graphql": "^17.0.2",
"hexy": "^0.4.0",
"history": "^5.3.0",
"jotai": "^2.18.0",
"jotai-family": "^1.0.1",
+79 -35
View File
@@ -3,7 +3,10 @@ import { formatSize } from "@yaakapp-internal/lib/formatSize";
import type { Flow, FlowBody } from "@yaakapp-internal/proxy-lib";
import {
Banner,
Button,
CsvViewer,
HexdumpViewer,
Icon,
ImageViewer,
languageFromContentType,
LoadingIcon,
@@ -14,16 +17,17 @@ import {
} from "@yaakapp-internal/ui";
import type { CodeEditorProps } from "@yaakapp-internal/ui/editor";
import type { ReactNode } from "react";
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
base64ToBytes,
bytesToText,
bodyAsText,
bodyImageType,
filterText,
findHeader,
flowBodyQueryOptions,
formatText,
mimeEssence,
} from "../lib/body";
import { rpc } from "../lib/rpc";
import { useSaveFlowBody } from "../lib/flowActions";
interface Props {
flow: Flow;
@@ -32,18 +36,7 @@ interface Props {
}
export function useFlowBody(flow: Flow, which: FlowBody, enabled = true) {
return useQuery({
enabled,
queryKey: ["get_flow_body", flow.id, which, flow.updatedAt],
queryFn: async () => {
const res = await rpc("get_flow_body", { flowId: flow.id, which });
return {
bytes: base64ToBytes(res.data),
truncated: res.truncated,
storedSize: res.storedSize,
};
},
});
return useQuery({ ...flowBodyQueryOptions(flow, which), enabled });
}
export function FlowBodyViewer({ flow, which, pretty }: Props) {
@@ -60,8 +53,8 @@ export function FlowBodyViewer({ flow, which, pretty }: Props) {
return <Banner color="danger">{body.error.message}</Banner>;
}
const { bytes, truncated, storedSize } = body.data;
if (bytes.length === 0) {
const { bytes, truncated, storedSize, decodeError } = body.data;
if (bytes.length === 0 && decodeError == null) {
return <EmptyState>{which === "request" ? "No request body" : "Empty"}</EmptyState>;
}
@@ -70,12 +63,16 @@ export function FlowBodyViewer({ flow, which, pretty }: Props) {
const mime = mimeEssence(contentType) ?? "";
const wireSize = which === "request" ? flow.requestSize : flow.responseSize;
const wireTruncated = which === "request" ? flow.requestTruncated : flow.responseTruncated;
// An image by its bytes or type, else text whatever the content type says, so a page sent with
// an odd one still reads: `viewerText`'s rule.
const imageType = decodeError == null ? bodyImageType(bytes, truncated, contentType) : null;
const text =
decodeError == null && imageType == null ? bodyAsText(bytes, truncated, contentType) : null;
let viewer: ReactNode;
if (mime.startsWith("image/svg")) {
viewer = <SvgViewer text={bytesToText(bytes, truncated) ?? ""} />;
} else if (mime.startsWith("image/")) {
viewer = <ImageBody bytes={bytes} mime={mime} />;
if (decodeError != null) {
// What failed to decode is as it was on the wire, compressed, so never text.
viewer = <BinaryBody flow={flow} which={which} bytes={bytes} />;
} else if (mime.startsWith("multipart/") && pretty) {
const boundary = contentType?.match(/;\s*boundary="?([^";]+)"?/i)?.[1] ?? "unknown";
viewer = (
@@ -86,14 +83,17 @@ export function FlowBodyViewer({ flow, which, pretty }: Props) {
textViewerProps={{ formatText }}
/>
);
} else if (imageType != null) {
viewer = <ImageBody bytes={bytes} mime={imageType} />;
} else if (text == null) {
viewer = <BinaryBody flow={flow} which={which} bytes={bytes} />;
} else if (mime.startsWith("image/svg")) {
viewer = <SvgViewer text={text} />;
} else if (/csv|tab-separated/.test(mime) && pretty) {
viewer = <CsvViewer text={bytesToText(bytes, truncated)} className="pb-2" />;
viewer = <CsvViewer text={text} className="pb-2" />;
} else {
const text = bytesToText(bytes, truncated);
const language = languageFromContentType(contentType, text);
if (text == null) {
viewer = <EmptyState>Binary body, {formatSize(bytes.length)}</EmptyState>;
} else if (language === "html" && pretty && which === "response") {
if (language === "html" && pretty && which === "response") {
viewer = <WebPageViewer html={text} baseUrl={flow.url} />;
} else {
viewer = (
@@ -102,16 +102,60 @@ export function FlowBodyViewer({ flow, which, pretty }: Props) {
}
}
if (!truncated) return viewer;
if (!truncated && decodeError == null) return viewer;
return (
<div className="h-full grid grid-rows-[auto_minmax(0,1fr)] gap-2">
<Banner color="notice" className="text-sm">
{wireTruncated
? `Showing the first ${formatSize(storedSize)} of ${formatSize(wireSize)}, the capture limit. The app received all of it.`
: `Showing the first ${formatSize(bytes.length)} of the decoded body, the capture limit. The app received all of it.`}
</Banner>
<div className="min-h-0">{viewer}</div>
<div className="h-full grid grid-rows-[auto_auto_minmax(0,1fr)]">
{decodeError != null && (
<Banner color="danger" className="text-sm mb-2">
{decodeError}. Showing the body as it was on the wire.
</Banner>
)}
{truncated && (
<Banner color="notice" className="text-sm mb-2">
{wireTruncated || decodeError != null
? `Showing the first ${formatSize(storedSize)} of ${formatSize(wireSize)}, the capture limit. The app received all of it.`
: `Showing the first ${formatSize(bytes.length)} of the decoded body, the capture limit. The app received all of it.`}
</Banner>
)}
<div className="min-h-0 row-start-3">{viewer}</div>
</div>
);
}
/** Bytes shown in the hexdump; the rest are in the saved file */
const HEXDUMP_LIMIT = 256 * 1024;
/** A body that isn't text: a hexdump, and a way to save it */
function BinaryBody({
flow,
which,
bytes,
}: {
flow: Flow;
which: FlowBody;
bytes: Uint8Array<ArrayBuffer>;
}) {
const saveBody = useSaveFlowBody();
const shown = useMemo(() => bytes.subarray(0, HEXDUMP_LIMIT), [bytes]);
return (
<div className="h-full grid grid-rows-[auto_minmax(0,1fr)] gap-1">
<div className="flex items-center justify-between gap-2 text-sm text-text-subtle">
<span>
Binary body, {formatSize(bytes.length)}
{shown.length < bytes.length && `, first ${formatSize(shown.length)} shown`}
</span>
<Button
size="2xs"
variant="border"
leftSlot={<Icon icon="download" size="xs" />}
onClick={() => saveBody(flow, which)}
>
Save to File
</Button>
</div>
<HexdumpViewer data={shown} className="-mr-2 bg-surface" />
</div>
);
}
+209 -2
View File
@@ -1,5 +1,17 @@
import { describe, expect, test } from "vite-plus/test";
import { bytesToText } from "./body";
import { QueryClient, QueryObserver } from "@tanstack/react-query";
import type { Flow } from "@yaakapp-internal/proxy-lib";
import { describe, expect, test, vi } from "vite-plus/test";
import {
bodyAsText,
bodyFileName,
bodyImageType,
bytesToText,
flowBodyQueryOptions,
viewerText,
} from "./body";
import { rpc } from "./rpc";
vi.mock("./rpc", () => ({ rpc: vi.fn() }));
const encode = (text: string) => new TextEncoder().encode(text);
@@ -18,3 +30,198 @@ describe("bytesToText", () => {
expect(bytesToText(cut, true)).toBe("abc");
});
});
describe("bodyAsText", () => {
test("reads UTF-8 as text", () => {
expect(bodyAsText(encode("<h1>Forbidden</h1>\n\tcafé"))).toBe("<h1>Forbidden</h1>\n\tcafé");
});
test("reads unlabeled Latin-1 text as text, as windows-1252", () => {
const page = "<p>Accès refusé : vous n'avez pas l'autorisation d'accéder à cette page.</p>";
const latin1 = Uint8Array.from(page, (c) => c.charCodeAt(0));
expect(bodyAsText(latin1)).toBe(page);
});
test("reads bytes UTF-8 can't read as binary, though windows-1252 reads every one", () => {
let seed = 7;
const random = Uint8Array.from({ length: 600 }, () => {
seed = (seed * 1103515245 + 12345) & 0x7fffffff;
return seed >> 16;
});
expect(bodyAsText(random)).toBeNull();
// All high bytes: letters and symbols in windows-1252, none of them UTF-8
const high = Uint8Array.from({ length: 600 }, (_, i) => 0xa0 + (i % 96));
expect(bodyAsText(high)).toBeNull();
expect(bodyAsText(high, false, "text/plain")).toBeNull();
});
test("reads protobuf and other binary as binary, even when it is valid UTF-8", () => {
// Field tags, lengths and varints: control characters between short strings.
const protobuf = new Uint8Array([
0x0a, 0x04, 0x6b, 0x65, 0x79, 0x31, 0x12, 0x02, 0x08, 0x01, 0x1a, 0x03, 0x10, 0x96, 0x01,
0x22, 0x00, 0x2a, 0x02, 0x18, 0x07,
]);
expect(bodyAsText(protobuf)).toBeNull();
expect(bodyAsText(new Uint8Array([0x01, 0x02, 0x03, 0x04, 0x41, 0x42]))).toBeNull();
expect(bodyAsText(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))).toBeNull();
});
});
describe("viewerText", () => {
// A PNG signature, then a tEXt chunk of printable metadata far longer than the image
const png = new Uint8Array([
0x89,
...encode("PNG\r\n"),
0x1a,
0x0a,
0x00,
0x00,
0x12,
0xc0,
...encode(`tEXtDescription\0${"A long printable description. ".repeat(160)}`),
]);
test("keeps an image with printable metadata an image", () => {
expect(bodyAsText(png)).not.toBeNull();
expect(viewerText(png, false, "image/png")).toBeNull();
});
test("reads text sent as an image as text, and other types text first", () => {
expect(viewerText(encode("<h1>Forbidden</h1>"), false, "image/png")).toBe("<h1>Forbidden</h1>");
expect(bodyImageType(encode("<h1>Forbidden</h1>"), false, "image/png")).toBeNull();
expect(viewerText(encode("<svg/>"), false, "image/svg+xml")).toBe("<svg/>");
expect(bodyImageType(encode("<svg/>"), false, "image/svg+xml")).toBeNull();
const bmwText = encode("BMW sells cars.\n");
expect(viewerText(bmwText, false, "text/plain")).toBe("BMW sells cars.\n");
});
// A 1×1 black 24-bit BMP: every byte below 0x80, so valid UTF-8
// File header, then the 40-byte DIB header, then one pixel padded to four bytes
// prettier-ignore
const bmp = new Uint8Array([
0x42, 0x4d, 58, 0, 0, 0, 0, 0, 0, 0, 54, 0, 0, 0,
40, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 24, 0, 0, 0, 0, 0, 4, 0, 0, 0,
0x13, 0x0b, 0, 0, 0x13, 0x0b, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
]);
test("keeps an image that is valid UTF-8 an image", () => {
expect(bytesToText(bmp)).not.toBeNull();
expect(bodyImageType(bmp, false, "image/bmp")).toBe("image/bmp");
expect(viewerText(bmp, false, "image/bmp")).toBeNull();
});
test("previews an image by its signature whatever its content type", () => {
expect(bodyImageType(bmp, false, "application/octet-stream")).toBe("image/bmp");
expect(bodyImageType(png, false, "application/octet-stream")).toBe("image/png");
expect(bodyImageType(png, false, null)).toBe("image/png");
expect(viewerText(png, false, "application/octet-stream")).toBeNull();
const gif = encode("GIF89a\x01\0\x01\0");
expect(bodyImageType(gif, false, "text/plain")).toBe("image/gif");
});
test("previews formats not every webview draws only when their content type says so", () => {
const tiff = new Uint8Array([0x49, 0x49, 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00, 0xff, 0x80]);
const heic = new Uint8Array([0, 0, 0, 0x18, ...encode("ftypheic"), 0, 0, 0, 0, 0xff, 0x80]);
for (const image of [tiff, heic]) {
expect(bodyImageType(image, false, "application/octet-stream")).toBeNull();
expect(viewerText(image, false, "application/octet-stream")).toBeNull();
}
expect(bodyImageType(tiff, false, "image/tiff")).toBe("image/tiff");
expect(bodyImageType(heic, false, "image/heic")).toBe("image/heic");
});
test("reads text in the charset its content type names", () => {
const page = "Accès refusé : vous n'avez pas l'autorisation d'accéder à cette page.";
const latin1 = Uint8Array.from(page, (c) => c.charCodeAt(0));
expect(viewerText(latin1, false, "text/html; charset=iso-8859-1")).toBe(page);
// "こんにちは、世界" in Shift_JIS
const shiftJis = new Uint8Array([
0x82, 0xb1, 0x82, 0xf1, 0x82, 0xc9, 0x82, 0xbf, 0x82, 0xcd, 0x81, 0x41, 0x90, 0xa2, 0x8a,
0x45,
]);
expect(viewerText(shiftJis, false, "text/plain; charset=shift_jis")).toBe("こんにちは、世界");
});
test("reads unlabeled Latin-1 as windows-1252, and UTF-8 as UTF-8", () => {
const page = "Accès refusé : vous n'avez pas l'autorisation d'accéder à cette page.";
const latin1 = Uint8Array.from(page, (c) => c.charCodeAt(0));
expect(viewerText(latin1, false, "application/octet-stream")).toBe(page);
expect(viewerText(encode(page), false, "application/octet-stream")).toBe(page);
expect(viewerText(encode(page), false, "text/plain; charset=utf-8")).toBe(page);
});
});
const flow = (url: string, contentType: string | null) =>
({
id: "fl_1",
url,
updatedAt: "2026-11-04T00:00:00",
requestHeaders: contentType == null ? [] : [{ name: "Content-Type", value: contentType }],
responseHeaders: contentType == null ? [] : [{ name: "content-type", value: contentType }],
}) as unknown as Flow;
describe("bodyFileName", () => {
test("uses the URL's file name for a response", () => {
expect(bodyFileName(flow("https://a.test/img/logo%20big.png?v=2", null), "response")).toBe(
"logo big.png",
);
});
test("names a body from its content type otherwise", () => {
const protobuf = flow("https://a.test/v1:GetModels", "application/x-protobuf");
expect(bodyFileName(protobuf, "request")).toBe("request.protobuf");
expect(bodyFileName(protobuf, "response")).toBe("response.protobuf");
expect(bodyFileName(flow("https://a.test/", "text/plain; charset=utf-8"), "response")).toBe(
"response.txt",
);
expect(bodyFileName(flow("https://a.test/api", "application/problem+json"), "response")).toBe(
"response.json",
);
expect(bodyFileName(flow("https://a.test/data.json", null), "request")).toBe("request.bin");
expect(bodyFileName(flow("not a url", "application/octet-stream"), "response")).toBe(
"response.bin",
);
});
});
describe("flowBodyQueryOptions", () => {
test("shows a body that fails to read at once, without retrying", async () => {
vi.mocked(rpc).mockRejectedValue(new Error("No flow fl_1"));
// React Query retries three times in a browser, and not at all where there is no window.
const client = new QueryClient({ defaultOptions: { queries: { retry: 3 } } });
const observer = new QueryObserver(
client,
flowBodyQueryOptions(flow("https://a.test/", null), "response"),
);
const failed = new Promise<string>((resolve) => {
const unsubscribe = observer.subscribe((result) => {
if (result.status === "error") {
unsubscribe();
resolve(result.error.message);
}
});
});
// React Query's default retries would keep it pending for seconds.
const timeout = new Promise<string>((resolve) => setTimeout(() => resolve("pending"), 500));
expect(await Promise.race([failed, timeout])).toBe("No flow fl_1");
expect(rpc).toHaveBeenCalledTimes(1);
client.clear();
});
test("passes on why a body failed to decode, with its bytes as they were", async () => {
vi.mocked(rpc).mockResolvedValue({
data: btoa("\x78\x9c\x01"),
truncated: false,
storedSize: 3,
decodeError: "Failed to decode Deflate body: deflate decompression error",
});
const client = new QueryClient();
const body = await client.fetchQuery(
flowBodyQueryOptions(flow("https://a.test/", null), "request"),
);
expect(Array.from(body.bytes)).toEqual([0x78, 0x9c, 0x01]);
expect(body.decodeError).toBe("Failed to decode Deflate body: deflate decompression error");
client.clear();
});
});
+146 -10
View File
@@ -1,8 +1,32 @@
import type { FilterLanguage, FlowBody } from "@yaakapp-internal/proxy-lib";
import { queryOptions } from "@tanstack/react-query";
import {
contentTypeCharset,
decodeBodyText,
strictUtf8Text,
} from "@yaakapp-internal/lib/decodeBodyText";
import type { FilterLanguage, Flow, FlowBody } from "@yaakapp-internal/proxy-lib";
import type { CodeEditorProps } from "@yaakapp-internal/ui/editor";
import vkBeautify from "vkbeautify";
import { rpc } from "./rpc";
/** A flow's body for the viewer: decoded, or as it was on the wire when `decodeError` is set */
export function flowBodyQueryOptions(flow: Flow, which: FlowBody) {
return queryOptions({
queryKey: ["get_flow_body", flow.id, which, flow.updatedAt],
queryFn: async () => {
const res = await rpc("get_flow_body", { flowId: flow.id, which });
return {
bytes: base64ToBytes(res.data),
truncated: res.truncated,
storedSize: res.storedSize,
decodeError: res.decodeError ?? null,
};
},
// Reading a stored body fails the same way every time, so the error shows at once.
retry: false,
});
}
export function base64ToBytes(data: string): Uint8Array<ArrayBuffer> {
const binary = atob(data);
const bytes = new Uint8Array(binary.length);
@@ -16,19 +40,104 @@ export function base64ToBytes(data: string): Uint8Array<ArrayBuffer> {
* The text of a body, or null when it isn't valid UTF-8. A truncated body may end partway
* through a character, so up to three trailing bytes are dropped before giving up on it.
*/
export function bytesToText(bytes: Uint8Array, truncated = false): string | null {
const decoder = new TextDecoder("utf-8", { fatal: true });
const maxTrim = truncated ? Math.min(3, bytes.length) : 0;
for (let trim = 0; trim <= maxTrim; trim++) {
try {
return decoder.decode(bytes.subarray(0, bytes.length - trim));
} catch {
// Try again without the last byte
}
export const bytesToText = strictUtf8Text;
/** Characters looked at to tell text from binary */
const TEXT_SAMPLE = 64 * 1024;
/** The share of those that may be control characters or undecodable bytes in text */
const MAX_UNPRINTABLE = 0.1;
/**
* The body as text, whatever its content type says, or null when it is binary. It is decoded in
* its content type's charset, or else as UTF-8, or windows-1252 when it isn't valid UTF-8. It is
* binary when it is full of control characters, as protobuf is, or, without a charset, of bytes
* UTF-8 can't read: windows-1252 reads every byte as something, compressed data included.
*/
export function bodyAsText(
bytes: Uint8Array,
truncated = false,
contentType: string | null = null,
): string | null {
const text = decodeBodyText(bytes, contentType, { truncated });
const judged =
contentTypeCharset(contentType) != null
? text
: (strictUtf8Text(bytes, truncated) ?? new TextDecoder("utf-8").decode(bytes));
let total = 0;
let unprintable = 0;
for (const char of judged) {
if (total === TEXT_SAMPLE) break;
total++;
const code = char.codePointAt(0) ?? 0;
const control = code < 0x20 && code !== 0x09 && code !== 0x0a && code !== 0x0d;
if (control || code === 0x7f || code === 0xfffd) unprintable++;
}
return unprintable <= total * MAX_UNPRINTABLE ? text : null;
}
const ascii = (bytes: Uint8Array, start: number, text: string) =>
Array.from(text).every((c, i) => bytes[start + i] === c.charCodeAt(0));
/**
* The image type a body's first bytes name, or null when they name none. Only types every
* platform's webview draws, so a body sniffed as an image always previews: TIFF, HEIC and AVIF
* preview only when their content type says so.
*/
export function imageSignature(bytes: Uint8Array): string | null {
const b = bytes;
if (b.length < 4) return null;
if (b[0] === 0x89 && ascii(b, 1, "PNG\r\n\x1a\n")) return "image/png";
if (b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return "image/jpeg";
if (ascii(b, 0, "GIF87a") || ascii(b, 0, "GIF89a")) return "image/gif";
if (ascii(b, 0, "RIFF") && ascii(b, 8, "WEBP")) return "image/webp";
if (ascii(b, 0, "\0\0\x01\0") && b.length >= 6 && (b[4] ?? 0) + (b[5] ?? 0) > 0) {
return "image/x-icon";
}
// "BM" alone starts plenty of text, so the reserved bytes and DIB header size must fit too.
const dibSize = (b[14] ?? 0) | ((b[15] ?? 0) << 8) | ((b[16] ?? 0) << 16) | ((b[17] ?? 0) << 24);
if (
ascii(b, 0, "BM") &&
ascii(b, 6, "\0\0\0\0") &&
[12, 40, 52, 56, 64, 108, 124].includes(dibSize)
) {
return "image/bmp";
}
return null;
}
/**
* The image type to preview a body as, or null when it isn't one: what its first bytes name,
* whatever its content type, or else an `image/*` content type other than SVG, unless the body
* is genuinely text, as an error page sent with the image's type is.
*/
export function bodyImageType(
bytes: Uint8Array,
truncated: boolean,
contentType: string | null,
): string | null {
const signed = imageSignature(bytes);
if (signed != null) return signed;
const mime = mimeEssence(contentType) ?? "";
if (!mime.startsWith("image/") || mime.startsWith("image/svg")) return null;
const genuineText =
strictUtf8Text(bytes, truncated) != null && bodyAsText(bytes, truncated, contentType) != null;
return genuineText ? null : mime;
}
/**
* The body as the viewer reads it: text first, whatever its content type, except an image, which
* is never text.
*/
export function viewerText(
bytes: Uint8Array,
truncated: boolean,
contentType: string | null,
): string | null {
if (bodyImageType(bytes, truncated, contentType) != null) return null;
return bodyAsText(bytes, truncated, contentType);
}
export async function formatText(
text: string,
language: CodeEditorProps["language"],
@@ -81,6 +190,33 @@ export function shortContentType(contentType: string | null): string | null {
return suffix.replace(/^x-/, "");
}
/** Extensions for media types whose subtype isn't one */
const EXTENSIONS: Record<string, string> = {
"application/javascript": "js",
"application/octet-stream": "bin",
"image/jpeg": "jpg",
"image/svg+xml": "svg",
"text/javascript": "js",
"text/markdown": "md",
"text/plain": "txt",
};
/** A name to offer for a saved body: the URL's file name, or one from the content type */
export function bodyFileName(flow: Flow, which: FlowBody): string {
let last = "";
try {
last = decodeURIComponent(new URL(flow.url).pathname.split("/").pop() ?? "");
} catch {
// Not a URL, or not encoded properly
}
if (which === "response" && /^[^\\/:*?"<>|]+\.[a-z0-9]+$/i.test(last)) return last;
const headers = which === "request" ? flow.requestHeaders : flow.responseHeaders;
const contentType = findHeader(headers, "content-type");
const essence = mimeEssence(contentType);
const extension = (essence == null ? null : EXTENSIONS[essence]) ?? shortContentType(contentType);
return `${which}.${extension?.replace(/[^a-z0-9-]/gi, "") || "bin"}`;
}
export function findHeader(headers: { name: string; value: string }[], name: string) {
const lower = name.toLowerCase();
return headers.find((h) => h.name.toLowerCase() === lower)?.value ?? null;
+45 -2
View File
@@ -1,9 +1,10 @@
import type { ExportHarRequest, Flow, FlowBody } from "@yaakapp-internal/proxy-lib";
import type { DropdownItem } from "@yaakapp-internal/ui";
import { save } from "@tauri-apps/plugin-dialog";
import { formatSize } from "@yaakapp-internal/lib/formatSize";
import { atom, useSetAtom } from "jotai";
import { useCallback } from "react";
import { base64ToBytes } from "./body";
import { base64ToBytes, bodyFileName } from "./body";
import { curlBodyText, toCurl } from "./curl";
import { rpc } from "./rpc";
import { useShowToast } from "./toast";
@@ -14,10 +15,35 @@ export const saveDialogFlowAtom = atom<Flow | null>(null);
/** A body as text, decoding what is not UTF-8 lossily, or null when there is none */
async function bodyText(flow: Flow, which: FlowBody): Promise<string | null> {
const res = await rpc("get_flow_body", { flowId: flow.id, which });
if (res.decodeError != null) throw new Error(res.decodeError);
const bytes = base64ToBytes(res.data);
return bytes.length === 0 ? null : new TextDecoder().decode(bytes);
}
/** Writes a flow's body to a file the person picks, as the viewer shows it */
export function useSaveFlowBody(): (flow: Flow, which: FlowBody) => Promise<void> {
const showToast = useShowToast();
return useCallback(
async (flow: Flow, which: FlowBody) => {
try {
const path = await save({ defaultPath: bodyFileName(flow, which) });
if (path == null) return;
const saved = await rpc("save_flow_body", { flowId: flow.id, which, path });
const notes = [
saved.raw ? "as it was on the wire, since it failed to decode" : null,
saved.truncated ? "cut at the capture limit" : null,
].filter((n) => n != null);
showToast({
message: `Saved ${formatSize(saved.size)}${notes.length > 0 ? `, ${notes.join(", ")}` : ""}`,
});
} catch (err) {
showToast({ message: `Failed to save the ${which} body: ${String(err)}`, color: "danger" });
}
},
[showToast],
);
}
/**
* Writes flows to a HAR file the person picks: `ids`, or every flow `filter` covers. Returns how
* many were written, or null when the save panel was cancelled.
@@ -38,6 +64,7 @@ export async function exportHar(
export function useFlowActions(): (flow: Flow) => DropdownItem[] {
const showToast = useShowToast();
const openSave = useSetAtom(saveDialogFlowAtom);
const saveBody = useSaveFlowBody();
return useCallback(
(flow: Flow) => {
@@ -75,6 +102,10 @@ export function useFlowActions(): (flow: Flow) => DropdownItem[] {
showToast({ message: `Failed to copy cURL: ${String(err)}`, color: "danger" });
return;
}
if (res.decodeError != null) {
showToast({ message: `Failed to copy cURL: ${res.decodeError}`, color: "danger" });
return;
}
body = curlBodyText(base64ToBytes(res.data), res.truncated);
// A command that sends other bytes than the app did would mislead.
if (body == null) {
@@ -102,6 +133,18 @@ export function useFlowActions(): (flow: Flow) => DropdownItem[] {
onSelect: () => copy("response body", () => bodyText(flow, "response")),
},
{ type: "separator" },
{
label: "Save Request Body to File",
icon: "download",
disabled: flow.requestSize === 0,
onSelect: () => saveBody(flow, "request"),
},
{
label: "Save Response Body to File",
icon: "download",
disabled: noResponse || flow.responseSize === 0,
onSelect: () => saveBody(flow, "response"),
},
{
label: "Export HAR",
icon: "download",
@@ -116,6 +159,6 @@ export function useFlowActions(): (flow: Flow) => DropdownItem[] {
},
];
},
[openSave, showToast],
[openSave, saveBody, showToast],
);
}