Compare commits

..
Author SHA1 Message Date
Gregory Schier 448d349af8 Address response bodies by response id instead of a filesystem path
The body commands took a path from the client, so a token holder could
read any file the process could. They now take a response id and resolve
the location themselves, and the UI never sees a path at all: the desktop
host asks the backend where the file is, and the bridge fetches
/responses/:id/body.

Ephemeral responses (GraphQL introspection) never reach the database, so
resolution falls back to the path send writes them to.
2026-08-14 17:02:05 -07:00
Gregory SchierandClaude Fable 5 99a318224f Add the Yaak Bridge so a browser tab can run the real engine
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 15:17:26 -07:00
70 changed files with 2034 additions and 3330 deletions

No files matched your search

Generated
-18
View File
@@ -11106,7 +11106,6 @@ dependencies = [
"yaak-models",
"yaak-plugins",
"yaak-rpc",
"yaak-rpc-schema",
"yaak-sse",
"yaak-sync",
"yaak-system-appearance",
@@ -11444,22 +11443,6 @@ dependencies = [
"ts-rs",
]
[[package]]
name = "yaak-rpc-schema"
version = "0.0.0"
dependencies = [
"serde",
"ts-rs",
"yaak-git",
"yaak-grpc",
"yaak-models",
"yaak-plugins",
"yaak-sse",
"yaak-sync",
"yaak-templates",
"yaak-ws",
]
[[package]]
name = "yaak-server"
version = "0.1.0"
@@ -11490,7 +11473,6 @@ dependencies = [
"yaak-models",
"yaak-plugins",
"yaak-rpc",
"yaak-rpc-schema",
"yaak-sse",
"yaak-templates",
]
-2
View File
@@ -5,7 +5,6 @@ members = [
# Common/foundation crates
"crates/common/yaak-database",
"crates/common/yaak-rpc",
"crates/common/yaak-rpc-schema",
# Shared crates (no Tauri dependency)
"crates/yaak-core",
"crates/yaak-common",
@@ -66,7 +65,6 @@ ts-rs = "11.1.0"
# Internal crates - common/foundation
yaak-database = { path = "crates/common/yaak-database" }
yaak-rpc = { path = "crates/common/yaak-rpc" }
yaak-rpc-schema = { path = "crates/common/yaak-rpc-schema" }
# Internal crates - shared
yaak-core = { path = "crates/yaak-core" }
@@ -410,7 +410,7 @@ function EnsureCompleteResponse({
Component,
}: {
response: HttpResponse;
Component: ComponentType<{ bodyUrl: string }>;
Component: ComponentType<{ url: string }>;
}) {
// Wait until the response has been fully-downloaded before asking for it
const complete = response.state === "closed";
@@ -432,7 +432,7 @@ function EnsureCompleteResponse({
return <div>Empty response body</div>;
}
return <Component bodyUrl={bodyUrl.data} />;
return <Component url={bodyUrl.data} />;
}
function HttpSvgViewer({ response }: { response: HttpResponse }) {
+39 -121
View File
@@ -1,138 +1,56 @@
import { platform } from "@yaakapp-internal/platform";
import { Icon, VStack } from "@yaakapp-internal/ui";
import classNames from "classnames";
import { useEffect, useRef, useState } from "react";
import { VStack } from "@yaakapp-internal/ui";
import { useState } from "react";
import { useLocalStorage } from "react-use";
import { CommercialUseBanner } from "./CommercialUseBanner";
import { Button } from "./core/Button";
import { PlainInput } from "./core/PlainInput";
import { SelectFile } from "./SelectFile";
interface Props {
importFile: (filePath: string) => Promise<void>;
importUrl: (url: string) => Promise<void>;
importData: (filePath: string) => Promise<void>;
}
/**
* An absolute or relative path is unambiguously a file. Everything else is treated as a URL, so a
* bare host like `example.com/openapi.json` still works (the backend defaults it to https).
*/
function isFilePath(value: string): boolean {
return (
value.startsWith("/") ||
value.startsWith("./") ||
value.startsWith("../") ||
value.startsWith("~/") ||
value.startsWith("\\\\") ||
/^[a-zA-Z]:[\\/]/.test(value)
);
}
function fileName(path: string): string {
return path.split(/[/\\]/).at(-1) || path;
}
export function ImportDataDialog({ importFile, importUrl }: Props) {
export function ImportDataDialog({ importData }: Props) {
const [isLoading, setIsLoading] = useState<boolean>(false);
// A file path or a URL. Both inputs write here, so there is only ever one thing to import
const [source, setSource] = useLocalStorage<string | null>("importPathOrUrl", null);
const [forceUpdateKey, setForceUpdateKey] = useState<number>(0);
const [isHovering, setIsHovering] = useState<boolean>(false);
const ref = useRef<HTMLDivElement>(null);
const trimmedSource = source?.trim() ?? "";
const filePath = isFilePath(trimmedSource) ? trimmedSource : null;
const selectSource = (value: string) => {
setSource(value);
// Remount the input so it shows the path of the newly-picked file
setForceUpdateKey((k) => k + 1);
};
// Accept a file dropped anywhere on the dialog, the way SelectFile does for its button
useEffect(() => {
return platform.window.onDragDrop((event) => {
if (event.type === "over") {
const p = event.position;
const r = ref.current?.getBoundingClientRect();
if (r == null) return;
setIsHovering(p.x >= r.left && p.x <= r.right && p.y >= r.top && p.y <= r.bottom);
} else if (event.type === "drop" && isHovering) {
const p = event.paths[0];
if (p) selectSource(p);
setIsHovering(false);
} else {
setIsHovering(false);
}
});
}, [isHovering, setSource]);
const handleSelectFile = async () => {
const selected = await platform.dialog.open({ title: "Select File", multiple: false });
if (selected == null) return;
selectSource(selected);
};
const handleImport = async () => {
setIsLoading(true);
try {
if (filePath != null) {
await importFile(filePath);
} else {
await importUrl(trimmedSource);
}
} finally {
setIsLoading(false);
}
};
const [filePath, setFilePath] = useLocalStorage<string | null>("importFilePath", null);
return (
<VStack ref={ref} space={4} className="pb-4">
<VStack space={5} className="pb-4">
<CommercialUseBanner source="data-import" title="Importing work data?" />
<button
type="button"
onClick={handleSelectFile}
className={classNames(
"w-full rounded-lg border border-dashed px-4 py-6",
"flex flex-col items-center gap-1 text-center",
isHovering ? "border-notice bg-surface-highlight" : "border-border hover:border-text",
)}
>
<Icon icon="folder_input" className="text-text-subtlest w-8! h-8! mb-2" />
{/* Fixed height so the region doesn't resize between the empty and selected states */}
<div className="h-6 w-full flex items-center justify-center">
{filePath == null ? (
<div className="text-text">
<strong className="font-semibold">Choose a file</strong> or drag it here
</div>
) : (
<div className="text-text font-mono text-xs max-w-full truncate" title={filePath}>
{fileName(filePath)}
</div>
)}
</div>
<div className="text-xs text-text-subtlest">
Supports OpenAPI, Swagger, Postman, Insomnia, and curl
</div>
</button>
<VStack space={1}>
<ul className="list-disc pl-5">
<li>OpenAPI 3.0, 3.1</li>
<li>Postman Collection v2, v2.1</li>
<li>Insomnia v4+</li>
<li>Swagger 2.0</li>
<li>
Curl commands <em className="text-text-subtle">(or paste into URL)</em>
</li>
</ul>
</VStack>
<VStack space={2}>
<PlainInput
label="Or enter a file path or URL"
size="sm"
placeholder="https://example.com/openapi.json"
defaultValue={source ?? ""}
forceUpdateKey={String(forceUpdateKey)}
onChange={setSource}
<SelectFile
filePath={filePath ?? null}
onChange={({ filePath }) => setFilePath(filePath)}
/>
<Button
color="primary"
disabled={trimmedSource === "" || isLoading}
isLoading={isLoading}
size="sm"
onClick={handleImport}
>
{isLoading ? "Importing" : "Import"}
</Button>
{filePath && (
<Button
color="primary"
disabled={!filePath || isLoading}
isLoading={isLoading}
size="sm"
onClick={async () => {
setIsLoading(true);
try {
await importData(filePath);
} finally {
setIsLoading(false);
}
}}
>
{isLoading ? "Importing" : "Import"}
</Button>
)}
</VStack>
</VStack>
);
+13 -85
View File
@@ -36,16 +36,12 @@ import { fireAndForget } from "../../lib/fireAndForget";
import { ErrorBoundary } from "../ErrorBoundary";
import { Button } from "./Button";
import { Hotkey } from "./Hotkey";
import { IconButton } from "./IconButton";
import type { SeparatorAction } from "./Separator";
import { Separator } from "./Separator";
export type DropdownItemSeparator = {
type: "separator";
label?: ReactNode;
hidden?: boolean;
/** A control shown beside the label, eg. revealing the labelled file on disk. */
action?: SeparatorAction;
};
export type DropdownItemContent = {
@@ -70,12 +66,6 @@ export type DropdownItemDefault = {
submenu?: DropdownItem[];
/** If true, submenu opens on click instead of hover */
submenuOpenOnClick?: boolean;
/**
* How the submenu opens. "row" (default) opens it from the row itself (hover, or click
* with submenuOpenOnClick). "button" keeps the row selectable via onSelect and renders
* a dedicated button on the right that opens the submenu.
*/
submenuTrigger?: "row" | "button";
icon?: IconProps["icon"];
};
@@ -512,15 +502,9 @@ const Menu = forwardRef<Omit<DropdownRef, "open" | "isOpen" | "toggle" | "items"
}
}
if (!item.keepOpenOnSelect) {
handleCloseAll();
} else if (isSubmenu) {
// Keep the parent menu open, but close this submenu — its items may no
// longer describe the row after the action (e.g. Pin → Unpin, Remove)
handleClose();
}
if (!item.keepOpenOnSelect) handleCloseAll();
},
[handleCloseAll, handleClose, isSubmenu, setSelectedIndex],
[handleCloseAll, setSelectedIndex],
);
useImperativeHandle(ref, () => {
@@ -645,7 +629,7 @@ const Menu = forwardRef<Omit<DropdownRef, "open" | "isOpen" | "toggle" | "items"
const item = filteredItems[selectedIndex ?? -1];
if (!item || item.type === "separator" || item.type === "content") return;
e.preventDefault();
if (item.submenu && item.submenuTrigger !== "button") {
if (item.submenu) {
const parent = document.activeElement as HTMLButtonElement;
if (parent) {
setActiveSubmenu({ item, parent, viaKeyboard: true });
@@ -664,11 +648,9 @@ const Menu = forwardRef<Omit<DropdownRef, "open" | "isOpen" | "toggle" | "items"
clearTimeout(submenuTimeoutRef.current);
}
if (item.submenu && !item.submenuOpenOnClick && item.submenuTrigger !== "button") {
if (item.submenu && !item.submenuOpenOnClick) {
setActiveSubmenu({ item, parent });
} else if (activeSubmenu && activeSubmenu.item !== item) {
// Hovering the row that owns the open submenu must not dismiss it — the
// pointer travels across the row on its way to a button-triggered submenu
} else if (activeSubmenu) {
submenuTimeoutRef.current = window.setTimeout(() => {
const submenuEl = submenuRef.current;
if (!submenuEl || !activeSubmenu) {
@@ -794,7 +776,6 @@ const Menu = forwardRef<Omit<DropdownRef, "open" | "isOpen" | "toggle" | "items"
// oxlint-disable-next-line no-array-index-key -- Nothing else available
key={i}
className={classNames("my-1.5", item.label ? "ml-2" : null)}
action={item.action}
>
{item.label}
</Separator>
@@ -816,7 +797,6 @@ const Menu = forwardRef<Omit<DropdownRef, "open" | "isOpen" | "toggle" | "items"
onFocus={handleFocus}
onSelect={handleSelect}
onHover={handleItemHover}
onOpenSubmenu={(item, el) => setActiveSubmenu({ item, parent: el })}
// oxlint-disable-next-line no-array-index-key -- It's fine
key={i}
item={item}
@@ -888,7 +868,6 @@ interface MenuItemProps {
onSelect: (item: DropdownItemDefault, el?: HTMLButtonElement) => Promise<void>;
onFocus: (item: DropdownItemDefault) => void;
onHover: (item: DropdownItemDefault, el: HTMLButtonElement) => void;
onOpenSubmenu: (item: DropdownItemDefault, el: HTMLButtonElement) => void;
focused: boolean;
isParentOfActiveSubmenu?: boolean;
}
@@ -900,7 +879,6 @@ function MenuItem({
onHover,
item,
onSelect,
onOpenSubmenu,
isParentOfActiveSubmenu,
...props
}: MenuItemProps) {
@@ -936,22 +914,19 @@ function MenuItem({
e.currentTarget.focus();
};
const hasButtonSubmenu = item.submenu != null && item.submenuTrigger === "button";
const rightSlot = item.submenu ? (
<Icon icon="chevron_right" color="secondary" />
) : (
(item.rightSlot ?? <Hotkey variant="text" action={item.hotKeyAction ?? null} />)
);
const rightSlot =
item.submenu && !hasButtonSubmenu ? (
<Icon icon="chevron_right" color="secondary" />
) : (
(item.rightSlot ?? <Hotkey variant="text" action={item.hotKeyAction ?? null} />)
);
const button = (
return (
<Button
ref={initRef}
size="sm"
tabIndex={-1}
onMouseEnter={hasButtonSubmenu ? undefined : handleMouseEnter}
onMouseLeave={hasButtonSubmenu ? undefined : (e) => e.currentTarget.blur()}
onMouseEnter={handleMouseEnter}
onMouseLeave={(e) => e.currentTarget.blur()}
disabled={item.disabled}
onFocus={handleFocus}
onClick={handleClick}
@@ -972,7 +947,6 @@ function MenuItem({
"min-w-32 outline-hidden px-2 mx-1.5 flex whitespace-nowrap",
"focus:bg-surface-highlight focus:text rounded-sm focus:outline-hidden focus-visible:outline-1",
isParentOfActiveSubmenu && "bg-surface-highlight text rounded-sm",
hasButtonSubmenu && "pr-8",
item.color === "danger" && "text-danger!",
item.color === "primary" && "text-primary!",
item.color === "success" && "text-success!",
@@ -985,52 +959,6 @@ function MenuItem({
<div className={classNames("truncate min-w-20")}>{item.label}</div>
</Button>
);
if (!hasButtonSubmenu) {
return button;
}
// The submenu trigger overlays the row as a sibling (not a child) because the row is
// itself a button and buttons cannot nest. Hover handling lives on this wrapper so the
// row keeps its focus highlight while the mouse is over the trigger.
return (
<div
className="relative grid group/menuitem"
onMouseEnter={() => {
const el = buttonRef.current;
if (el == null) return;
onHover(item, el);
el.focus();
}}
onMouseLeave={() => buttonRef.current?.blur()}
>
{button}
<div
className={classNames(
"absolute right-1.5 inset-y-0 flex items-center",
"opacity-0 group-hover/menuitem:opacity-100 group-focus-within/menuitem:opacity-100",
)}
>
<IconButton
color="custom"
size="2xs"
tabIndex={-1}
icon="ellipsis_vertical"
iconColor="secondary"
title="More actions"
className="h-full! w-7!"
onMouseDown={(e) => {
// Prevent the trigger from stealing focus, which would unhighlight the row
e.preventDefault();
}}
onClick={(e) => {
e.stopPropagation();
onOpenSubmenu(item, e.currentTarget);
}}
/>
</div>
</div>
);
}
interface MenuItemHotKeyProps {
@@ -1,31 +1,13 @@
import type { Color } from "@yaakapp-internal/plugins";
import type { IconProps } from "@yaakapp-internal/ui";
import { IconButton } from "@yaakapp-internal/ui";
import classNames from "classnames";
import type { ReactNode } from "react";
/**
* A single control attached to a labelled separator, rendered between the label
* and the rule.
*
* Declared rather than passed as a node so the separator keeps ownership of the
* things that are easy to get wrong by hand: matching the label's colour, and
* staying out of the rule's way when the label is long.
*/
export interface SeparatorAction {
icon: IconProps["icon"];
/** Tooltip and accessible name. Required — the control is icon-only. */
title: string;
onClick: () => void;
}
interface Props {
orientation?: "horizontal" | "vertical";
dashed?: boolean;
className?: string;
children?: ReactNode;
color?: Color;
action?: SeparatorAction;
}
export function Separator({
@@ -34,31 +16,15 @@ export function Separator({
dashed,
orientation = "horizontal",
children,
action,
}: Props) {
return (
<div role="presentation" className={classNames(className, "flex items-center w-full")}>
{children && (
<div className="text-sm text-text-subtlest mr-2 whitespace-nowrap">{children}</div>
)}
{action && (
<IconButton
size="2xs"
iconSize="xs"
className="shrink-0 mr-2 -ml-1"
// Forced, because the button itself sets `text-text` at full strength.
iconClassName="text-text-subtlest!"
icon={action.icon}
title={action.title}
onClick={action.onClick}
/>
)}
<div
className={classNames(
"opacity-60",
// Keep a stub of the line visible no matter how long the label is —
// `w-full` alone gets squeezed to nothing by a wide label.
orientation === "horizontal" && "min-w-8",
color == null && "border-border",
color === "primary" && "border-primary",
color === "secondary" && "border-secondary",
@@ -1,5 +1,4 @@
import type { HttpRequest } from "@yaakapp-internal/models";
import { platform } from "@yaakapp-internal/platform";
import { useAtom } from "jotai";
import { useCallback, useEffect, useMemo } from "react";
@@ -12,7 +11,6 @@ import type { DropdownItem } from "../core/Dropdown";
import { Dropdown } from "../core/Dropdown";
import type { EditorProps } from "../core/Editor/Editor";
import { Editor } from "../core/Editor/LazyEditor";
import { IconButton } from "../core/IconButton";
import type { RadioDropdownItem } from "../core/RadioDropdown";
import { RadioDropdown } from "../core/RadioDropdown";
import { Banner, FormattedError, Icon } from "@yaakapp-internal/ui";
@@ -20,7 +18,6 @@ import { Separator } from "../core/Separator";
import { tryFormatGraphql } from "../../lib/formatters";
import { parseGraphQLOperationNames } from "../../lib/graphqlOperationNames";
import { normalizeGraphQLBody } from "../../lib/requestBodyConversion";
import { revealInFinderText } from "../../lib/reveal";
import { showGraphQLDocExplorerAtom } from "./graphqlAtoms";
type Props = Pick<EditorProps, "heightMode" | "className" | "forceUpdateKey"> & {
@@ -31,10 +28,6 @@ type Props = Pick<EditorProps, "heightMode" | "className" | "forceUpdateKey"> &
const OPERATION_NAME_NOT_SPECIFIED = "";
// How much of the end of a schema filename is pinned when middle-truncating it.
// Enough to keep the extension and a little of the name before it.
const FILE_NAME_TAIL_CHARS = 12;
export function GraphQLEditor(props: Props) {
// There's some weirdness with stale onChange being called when switching requests, so we'll
// key on the request ID as a workaround for now.
@@ -45,41 +38,9 @@ function GraphQLEditorInner({ request, onChange, baseRequest, ...extraEditorProp
const [autoIntrospectDisabled, setAutoIntrospectDisabled] = useLocalStorage<
Record<string, boolean>
>("graphQLAutoIntrospectDisabled", {});
const {
schema,
isLoading,
error,
refetch,
clear,
loadFromFile,
reloadFromFile,
removeSchemaFile,
filePath,
} = useIntrospectGraphQL(baseRequest, {
const { schema, isLoading, error, refetch, clear } = useIntrospectGraphQL(baseRequest, {
disabled: autoIntrospectDisabled?.[baseRequest.id],
});
// Last path segment, for display only. The host owns real path semantics; this
// just needs something short enough to label the divider with.
const fileName = useMemo(() => filePath?.split(/[/\\]/).pop() || filePath, [filePath]);
// Selecting a file is all it takes — the request's source becomes that file,
// which is what keeps automatic introspection from overwriting it.
const handleLoadFromFile = useCallback(async () => {
const selected = await platform.dialog.open({
title: "Load GraphQL Schema",
multiple: false,
filters: [
{
name: "GraphQL Schema",
extensions: ["graphql", "graphqls", "gql", "json"],
},
],
});
if (selected == null) return;
await loadFromFile(selected);
}, [loadFromFile]);
const [currentBody, setCurrentBody] = useStateWithDeps<{
query: string;
variables: string | undefined;
@@ -199,37 +160,14 @@ function GraphQLEditorInner({ request, onChange, baseRequest, ...extraEditorProp
...((schema != null
? [
{
label: "Clear Schema",
label: "Clear",
onSelect: clear,
color: "danger",
leftSlot: <Icon icon="trash" />,
},
{ type: "separator" },
]
: []) satisfies DropdownItem[]),
{
// Labels the source actions below it, so the menu says where the
// schema came from without spending a row on it.
type: "separator",
hidden: schema == null && filePath == null,
label:
fileName == null || filePath == null ? undefined : (
// Middle truncation: the head shrinks and ellipsizes while the
// tail is pinned, so the extension always survives. Full path
// on hover.
<div className="flex min-w-0 max-w-[16rem] font-mono text-xs" title={filePath}>
<span className="truncate">{fileName.slice(0, -FILE_NAME_TAIL_CHARS)}</span>
<span className="shrink-0">{fileName.slice(-FILE_NAME_TAIL_CHARS)}</span>
</div>
),
action:
filePath == null
? undefined
: {
icon: "folder_symlink",
title: revealInFinderText,
onClick: () => platform.revealItemInDir(filePath),
},
},
{
hidden: !error,
label: (
@@ -272,33 +210,25 @@ function GraphQLEditorInner({ request, onChange, baseRequest, ...extraEditorProp
type: "content",
},
{
// One refresh action for either source: re-read the file, or
// re-introspect the server.
label: "Reload Schema",
leftSlot: <Icon icon="refresh" spin={isLoading} />,
keepOpenOnSelect: true,
// Failures surface through the hook's error state either way.
onSelect: async () => {
if (filePath != null) await reloadFromFile();
else await refetch();
hidden: schema == null,
label: `${isDocOpen ? "Hide" : "Show"} Documentation`,
leftSlot: <Icon icon="book_open_text" />,
onSelect: () => {
setGraphqlDocStateAtomValue((v) => ({
...v,
[request.id]: isDocOpen ? undefined : null,
}));
},
},
{
label: filePath == null ? "Load Schema from File…" : "Load a Different File…",
leftSlot: <Icon icon="import" />,
onSelect: handleLoadFromFile,
label: "Introspect Schema",
leftSlot: <Icon icon="refresh" spin={isLoading} />,
keepOpenOnSelect: true,
onSelect: refetch,
},
{ type: "separator", label: "Setting" },
{
hidden: filePath == null,
label: "Stop Using File",
leftSlot: <Icon icon="x" />,
onSelect: removeSchemaFile,
},
{ type: "separator", label: "Settings" },
{
// Governs both sources: re-introspecting the server, and
// re-reading the file when the request is opened.
label: filePath == null ? "Automatic Introspection" : "Automatic Reload",
label: "Automatic Introspection",
keepOpenOnSelect: true,
onSelect: () => {
setAutoIntrospectDisabled({
@@ -331,29 +261,6 @@ function GraphQLEditorInner({ request, onChange, baseRequest, ...extraEditorProp
</Dropdown>
)}
</div>,
// Sits after the schema control it depends on. Always rendered, disabled
// without a schema, so the row never changes shape.
<div key="documentation" className="opacity-100!">
<IconButton
size="sm"
variant="border"
icon="book_open_text"
disabled={schema == null}
title={
schema == null
? "Documentation unavailable without a schema"
: isDocOpen
? "Hide Documentation"
: "Show Documentation"
}
onClick={() => {
setGraphqlDocStateAtomValue((v) => ({
...v,
[request.id]: isDocOpen ? undefined : null,
}));
}}
/>
</div>,
],
[
schema,
@@ -365,11 +272,6 @@ function GraphQLEditorInner({ request, onChange, baseRequest, ...extraEditorProp
isLoading,
operationNames,
refetch,
handleLoadFromFile,
reloadFromFile,
removeSchemaFile,
filePath,
fileName,
autoIntrospectDisabled,
baseRequest.id,
setGraphqlDocStateAtomValue,
@@ -1,18 +1,18 @@
import { useEffect, useState } from "react";
interface Props {
/** A URL for the body the host already stored. */
bodyUrl?: string;
/** A URL the host resolved, for a body it already stored. */
url?: string;
data?: Uint8Array;
mimeType?: string;
}
export function AudioViewer({ bodyUrl, data, mimeType }: Props) {
export function AudioViewer({ url, data, mimeType }: Props) {
const [src, setSrc] = useState<string>();
useEffect(() => {
if (bodyUrl) {
setSrc(bodyUrl);
if (url) {
setSrc(url);
} else if (data) {
// The type matters here in a way it doesn't for an image: a media element goes by what
// the blob declares rather than sniffing it, so an Ogg labelled as MP3 won't play
@@ -23,7 +23,7 @@ export function AudioViewer({ bodyUrl, data, mimeType }: Props) {
} else {
setSrc(undefined);
}
}, [bodyUrl, data, mimeType]);
}, [url, data, mimeType]);
// oxlint-disable-next-line jsx-a11y/media-has-caption
return <audio className="w-full" controls src={src} />;
@@ -1,9 +1,7 @@
import type { HttpResponse } from "@yaakapp-internal/models";
import { useQueryClient } from "@tanstack/react-query";
import { useCallback } from "react";
import { useMemo, useState } from "react";
import { useCopyHttpResponse } from "../../hooks/useCopyHttpResponse";
import { responseBodyTextQuery, useResponseBodyText } from "../../hooks/useResponseBodyText";
import { useResponseFilter } from "../../hooks/useResponseFilter";
import { useResponseBodyText } from "../../hooks/useResponseBodyText";
import { useSaveResponse } from "../../hooks/useSaveResponse";
import { languageFromContentType } from "../../lib/contentType";
import { getContentTypeFromHeaders } from "../../lib/model_util";
@@ -54,25 +52,30 @@ interface HttpTextViewerProps {
}
function HttpTextViewer({ response, text, language, pretty, className }: HttpTextViewerProps) {
const queryClient = useQueryClient();
const filter = useResponseFilter({
stateKey: `response.body.${response.requestId}`,
// Shares the display query's cache entry, so the verdict costs no extra RPC
runFilter: useCallback(
(f: string) => queryClient.fetchQuery(responseBodyTextQuery({ response, filter: f })),
[queryClient, response],
),
});
const filteredBody = useResponseBodyText({ response, filter: filter.appliedFilter });
const [currentFilter, setCurrentFilter] = useState<string | null>(null);
const filteredBody = useResponseBodyText({ response, filter: currentFilter });
const saveResponse = useSaveResponse(response);
const copyResponse = useCopyHttpResponse(response);
const actionsDisabled = response.state !== "closed" && response.status >= 100;
const filterCallback = useMemo(
() => (filter: string) => {
setCurrentFilter(filter);
return {
data: filteredBody.data,
isPending: filteredBody.isPending,
error: !!filteredBody.error,
};
},
[filteredBody],
);
return (
<TextViewer
text={text}
language={language}
stateKey={`response.body.${response.id}`}
filterStateKey={`response.body.${response.requestId}`}
pretty={pretty}
className={className}
footerActions={[
@@ -95,12 +98,7 @@ function HttpTextViewer({ response, text, language, pretty, className }: HttpTex
className="border !border-border-subtle"
/>,
]}
filter={filter}
filterResult={{
data: filteredBody.data,
isPending: filteredBody.isPending,
error: !!filteredBody.error,
}}
onFilter={filterCallback}
/>
);
}
@@ -3,8 +3,8 @@ import { useEffect, useState } from "react";
type Props = { className?: string; mimeType?: string } & (
| {
/** A URL for the body the host already stored. */
bodyUrl: string;
/** A URL the host resolved, for a body it already stored. */
url: string;
}
| {
data: ArrayBuffer;
@@ -13,12 +13,12 @@ type Props = { className?: string; mimeType?: string } & (
export function ImageViewer({ className, mimeType, ...props }: Props) {
const [src, setSrc] = useState<string>();
const bodyUrl = "bodyUrl" in props ? props.bodyUrl : null;
const url = "url" in props ? props.url : null;
const data = "data" in props ? props.data : null;
useEffect(() => {
if (bodyUrl != null) {
setSrc(bodyUrl);
if (url != null) {
setSrc(url);
} else if (data != null) {
const blob = new Blob([data], { type: mimeType ?? "image/png" });
const objectUrl = URL.createObjectURL(blob);
@@ -27,7 +27,7 @@ export function ImageViewer({ className, mimeType, ...props }: Props) {
} else {
setSrc(undefined);
}
}, [bodyUrl, data, mimeType]);
}, [url, data, mimeType]);
return (
<img
@@ -17,8 +17,8 @@ fireAndForget(
);
interface Props {
/** A URL for the body the host already stored. */
bodyUrl?: string;
/** A URL the host resolved, for a body it already stored. */
url?: string;
data?: Uint8Array;
}
@@ -27,7 +27,7 @@ const options = {
standardFontDataUrl: "/standard_fonts/",
};
export function PdfViewer({ bodyUrl, data }: Props) {
export function PdfViewer({ url, data }: Props) {
const containerRef = useRef<HTMLDivElement>(null);
const [numPages, setNumPages] = useState<number>();
@@ -36,8 +36,8 @@ export function PdfViewer({ bodyUrl, data }: Props) {
// During render, not in an effect: an effect leaves the first paint with no file, and
// `Document` renders its "Failed to load PDF file" state for that frame before recovering
const src = useMemo(() => {
if (bodyUrl) {
return bodyUrl;
if (url) {
return url;
}
if (data) {
// Create a copy to avoid "Buffer is already detached" errors
@@ -45,7 +45,7 @@ export function PdfViewer({ bodyUrl, data }: Props) {
return { data: new Uint8Array(data) };
}
return undefined;
}, [bodyUrl, data]);
}, [url, data]);
const onDocumentLoadSuccess = ({ numPages: nextNumPages }: PDFDocumentProxy): void => {
setNumPages(nextNumPages);
@@ -1,96 +0,0 @@
import { Icon } from "@yaakapp-internal/ui";
import type { RecentFilter } from "../../hooks/useRecentFilters";
import { Dropdown, type DropdownItem } from "../core/Dropdown";
import { IconButton } from "../core/IconButton";
interface Props {
recentFilters: RecentFilter[];
activeFilter: string | null;
onSelect: (value: string) => void;
onRemove: (value: string) => void;
onTogglePin: (value: string) => void;
onClear: () => void;
}
export function RecentFiltersDropdown({
recentFilters,
activeFilter,
onSelect,
onRemove,
onTogglePin,
onClear,
}: Props) {
const pinned = recentFilters.filter((f) => f.pinned);
const unpinned = recentFilters.filter((f) => !f.pinned);
const toItem = (filter: RecentFilter): DropdownItem => ({
label: (
<div className="font-mono text-sm truncate max-w-sm" title={filter.value}>
{filter.value}
</div>
),
leftSlot: <Icon icon={filter.value === activeFilter ? "check" : "empty"} />,
onSelect: () => onSelect(filter.value),
submenuTrigger: "button",
submenu: [
{
label: filter.pinned ? "Unpin" : "Pin",
icon: filter.pinned ? "unpin" : "pin",
keepOpenOnSelect: true,
onSelect: () => onTogglePin(filter.value),
},
{
label: "Remove",
icon: "trash",
color: "danger",
keepOpenOnSelect: true,
onSelect: () => onRemove(filter.value),
},
],
});
const items: DropdownItem[] = [];
if (recentFilters.length === 0) {
items.push({
type: "content",
label: (
<span className="block px-4 py-1 text-sm text-text-subtle">
Filters you use are remembered here
</span>
),
});
}
if (pinned.length > 0) {
items.push({ type: "separator", label: "Pinned" }, ...pinned.map(toItem));
}
if (unpinned.length > 0) {
items.push({ type: "separator", label: "Recent" }, ...unpinned.map(toItem));
}
if (recentFilters.length > 0) {
items.push(
{ type: "separator" },
{
label: "Clear All",
leftSlot: <Icon icon="trash" />,
color: "danger",
onSelect: onClear,
},
);
}
return (
<Dropdown items={items}>
<IconButton
size="xs"
icon="filter"
title="Recent filters"
iconColor="secondary"
className="w-8 ml-0.5 mr-1 h-auto!"
/>
</Dropdown>
);
}
@@ -1,15 +1,14 @@
import classNames from "classnames";
import type { ReactNode } from "react";
import { Children, useCallback, useMemo } from "react";
import { Banner, HStack, Icon, InlineCode } from "@yaakapp-internal/ui";
import { createGlobalState } from "react-use";
import { useDebouncedValue } from "@yaakapp-internal/ui";
import { useFormatText } from "../../hooks/useFormatText";
import type { ResponseFilterApi } from "../../hooks/useResponseFilter";
import { Button } from "../core/Button";
import type { EditorProps } from "../core/Editor/Editor";
import { hyperlink } from "../core/Editor/hyperlink/extension";
import { Editor } from "../core/Editor/LazyEditor";
import { IconButton } from "../core/IconButton";
import { Input } from "../core/Input";
import { RecentFiltersDropdown } from "./RecentFiltersDropdown";
const extraExtensions = [hyperlink];
@@ -17,45 +16,57 @@ interface Props {
text: string;
language: EditorProps["language"];
stateKey: string | null;
filterStateKey?: string | null;
pretty?: boolean;
className?: string;
footerActions?: ReactNode;
filter?: ResponseFilterApi;
filterResult?: {
onFilter?: (filter: string) => {
data: string | null | undefined;
isPending: boolean;
error: boolean;
};
}
const useFilterText = createGlobalState<Record<string, string | null>>({});
export function TextViewer({
language,
text,
stateKey,
filterStateKey,
pretty,
className,
footerActions,
filter,
filterResult,
onFilter,
}: Props) {
const canFilter =
filter != null && (language === "json" || language === "xml" || language === "html");
const isSearching = filter?.isSearching ?? false;
const appliedFilter = filter?.appliedFilter ?? null;
const resultError = filterResult?.error ?? false;
const handleFilterKeyDown = useCallback(
(e: KeyboardEvent) => {
if (filter == null) return;
if (e.key === "Escape") {
filter.toggleSearch();
} else if (e.key === "Enter" && filter.filterText != null) {
filter.applyFilter(filter.filterText);
}
const filterKey = filterStateKey ?? stateKey;
const [filterTextMap, setFilterTextMap] = useFilterText();
const filterText = filterKey ? (filterTextMap[filterKey] ?? null) : null;
const debouncedFilterText = useDebouncedValue(filterText);
const setFilterText = useCallback(
(v: string | null) => {
if (!filterKey) return;
setFilterTextMap((m) => ({ ...m, [filterKey]: v }));
},
[filter],
[filterKey, setFilterTextMap],
);
const isSearching = filterText != null;
const filteredResponse =
onFilter && debouncedFilterText
? onFilter(debouncedFilterText)
: { data: null, isPending: false, error: false };
const toggleSearch = useCallback(() => {
if (isSearching) {
setFilterText(null);
} else {
setFilterText("");
}
}, [isSearching, setFilterText]);
const canFilter = onFilter && (language === "json" || language === "xml" || language === "html");
const actions = useMemo<ReactNode[]>(() => {
const nodes: ReactNode[] = isSearching ? [] : Children.toArray(footerActions);
@@ -65,8 +76,8 @@ export function TextViewer({
nodes.push(
<div key="input" className="w-full opacity-100!">
<Input
key={filter.stateKey ?? "filter"}
validate={!resultError}
key={filterKey ?? "filter"}
validate={!filteredResponse.error}
hideLabel
autoFocus
containerClassName="bg-surface"
@@ -74,62 +85,39 @@ export function TextViewer({
placeholder={language === "json" ? "JSONPath expression" : "XPath expression"}
label="Filter expression"
name="filter"
defaultValue={filter.filterText}
forceUpdateKey={filter.filterUpdateKey}
onKeyDown={handleFilterKeyDown}
onChange={filter.setFilterText}
stateKey={filter.stateKey ? `filter.${filter.stateKey}` : null}
leftSlot={
<div className="py-0.5 flex">
<RecentFiltersDropdown
recentFilters={filter.recentFilters}
activeFilter={filter.appliedFilter}
onSelect={filter.replaceFilter}
onRemove={filter.removeRecentFilter}
onTogglePin={filter.togglePinRecentFilter}
onClear={filter.clearRecentFilters}
/>
</div>
}
rightSlot={
<div className="py-0.5 flex">
<IconButton
size="xs"
icon="x"
title="Close filter"
iconColor="secondary"
onClick={filter.toggleSearch}
className="w-8 mr-0.5 h-auto!"
/>
</div>
}
defaultValue={filterText}
onKeyDown={(e) => e.key === "Escape" && toggleSearch()}
onChange={setFilterText}
stateKey={filterKey ? `filter.${filterKey}` : null}
/>
</div>,
);
} else {
nodes.push(
<IconButton
key="icon"
size="sm"
isLoading={filterResult?.isPending ?? false}
icon="filter"
title="Filter response"
onClick={filter.toggleSearch}
className="border border-border-subtle!"
/>,
);
}
nodes.push(
<IconButton
key="icon"
size="sm"
isLoading={filteredResponse.isPending}
icon={isSearching ? "x" : "filter"}
title={isSearching ? "Close filter" : "Filter response"}
onClick={toggleSearch}
className={classNames("border border-border-subtle!", isSearching && "opacity-100!")}
/>,
);
return nodes;
}, [
canFilter,
footerActions,
filter,
filterResult?.isPending,
resultError,
filterKey,
filterText,
filteredResponse.error,
filteredResponse.isPending,
isSearching,
language,
handleFilterKeyDown,
setFilterText,
toggleSearch,
]);
const formattedBody = useFormatText({ text, language, pretty: pretty ?? false });
@@ -138,11 +126,11 @@ export function TextViewer({
}
let body: string;
if (appliedFilter) {
if (resultError) {
if (isSearching && filterText?.length > 0) {
if (filteredResponse.error) {
body = "";
} else {
body = filterResult?.data != null ? filterResult.data : "";
body = filteredResponse.data != null ? filteredResponse.data : "";
}
} else {
body = formattedBody;
@@ -155,61 +143,15 @@ export function TextViewer({
}
return (
<div className="grid grid-rows-[auto_minmax(0,1fr)] h-full w-full">
{appliedFilter && filter != null ? (
<AppliedFilterBar
filter={appliedFilter}
error={resultError}
onClear={() => filter.replaceFilter("")}
/>
) : (
<span />
)}
<Editor
readOnly
className={className}
defaultValue={body}
language={language}
actions={actions}
extraExtensions={extraExtensions}
stateKey={stateKey}
/>
</div>
);
}
/**
* Shows what's actually filtering the body, which the filter box below can't convey
* once it holds an edited expression that hasn't been applied yet.
*/
function AppliedFilterBar({
filter,
error,
onClear,
}: {
filter: string;
error: boolean;
onClear: () => void;
}) {
return (
<Banner color={error ? "danger" : "info"} className="py-1! mb-2! text-sm">
<HStack space={2} className="min-w-0">
<Icon icon="filter" size="xs" className="shrink-0 opacity-70" />
<span className="truncate min-w-0" title={filter}>
Response filtered by <InlineCode>{filter}</InlineCode>
{error && " (invalid expression)"}
</span>
<Button
size="2xs"
variant="border"
color={error ? "danger" : "info"}
className="ml-auto shrink-0"
onClick={onClear}
>
Clear
</Button>
</HStack>
</Banner>
<Editor
readOnly
className={className}
defaultValue={body}
language={language}
actions={actions}
extraExtensions={extraExtensions}
stateKey={stateKey}
/>
);
}
@@ -1,18 +1,18 @@
import { useEffect, useState } from "react";
interface Props {
/** A URL for the body the host already stored. */
bodyUrl?: string;
/** A URL the host resolved, for a body it already stored. */
url?: string;
data?: Uint8Array;
mimeType?: string;
}
export function VideoViewer({ bodyUrl, data, mimeType }: Props) {
export function VideoViewer({ url, data, mimeType }: Props) {
const [src, setSrc] = useState<string>();
useEffect(() => {
if (bodyUrl) {
setSrc(bodyUrl);
if (url) {
setSrc(url);
} else if (data) {
// As in AudioViewer: a media element trusts the declared type instead of sniffing
const blob = new Blob([new Uint8Array(data)], { type: mimeType ?? "video/mp4" });
@@ -22,7 +22,7 @@ export function VideoViewer({ bodyUrl, data, mimeType }: Props) {
} else {
setSrc(undefined);
}
}, [bodyUrl, data, mimeType]);
}, [url, data, mimeType]);
// oxlint-disable-next-line jsx-a11y/media-has-caption
return <video className="w-full" controls src={src} />;
@@ -1,18 +0,0 @@
import { useKeyValue } from "./useKeyValue";
// The file a request's GraphQL schema is loaded from, or null when the schema
// comes from an introspection request.
//
// This is the *source*, not the schema. The introspection row it produces is a
// cache that expires on its own; this outlives it and regenerates it, the same
// way gRPC keeps its proto file list separate from a reflection result.
export function graphqlSchemaFileArgs(requestId: string | null) {
return {
namespace: "global" as const,
key: ["graphql_schema_file", requestId ?? "n/a"],
};
}
export function useGraphQLSchemaFile(requestId: string | null) {
return useKeyValue<string | null>({ ...graphqlSchemaFileArgs(requestId), fallback: null });
}
+8 -120
View File
@@ -1,14 +1,13 @@
import { useQuery, useQueryClient } from "@tanstack/react-query";
import type { GraphQlIntrospection, HttpRequest } from "@yaakapp-internal/models";
import { platform } from "@yaakapp-internal/platform";
import type { GraphQLSchema, IntrospectionQuery } from "graphql";
import { buildClientSchema, getIntrospectionQuery } from "graphql";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { tryBuildIntrospectionFromFile } from "../lib/graphqlSchema";
import { useCallback, useEffect, useMemo, useState } from "react";
import { minPromiseMillis } from "../lib/minPromiseMillis";
import { getResponseBodyText } from "../lib/responseBody";
import { sendEphemeralRequest } from "../lib/sendEphemeralRequest";
import { useActiveEnvironment } from "./useActiveEnvironment";
import { useGraphQLSchemaFile } from "./useGraphQLSchemaFile";
import { useDebouncedValue } from "@yaakapp-internal/ui";
import { rpc } from "../lib/rpc";
@@ -32,11 +31,6 @@ export function useIntrospectGraphQL(
const introspection = useIntrospectionResult(baseRequest);
// The schema's source. Outlives the introspection row it produces, so a
// request configured with a file keeps working after the row is swept.
const schemaFile = useGraphQLSchemaFile(baseRequest.id);
const filePath = schemaFile.value ?? null;
const upsertIntrospection = useCallback(
async (content: string | null) => {
const v = await rpc<GraphQlIntrospection>("models_upsert_graphql_introspection", {
@@ -61,7 +55,7 @@ export function useIntrospectGraphQL(
bodyType: "application/json",
body: { text: introspectionRequestBody },
};
const { response, body } = await minPromiseMillis(
const response = await minPromiseMillis(
sendEphemeralRequest(args, activeEnvironment?.id ?? null),
700,
);
@@ -70,16 +64,14 @@ export function useIntrospectGraphQL(
return setError(response.error);
}
// The send hands back the only copy of the body — an unsaved response has
// nothing on disk and no row to read it back from
const bodyText = new TextDecoder("utf-8").decode(new Uint8Array(body));
const bodyText = await getResponseBodyText({ response, filter: null });
if (response.status < 200 || response.status >= 300) {
return setError(
`Request failed with status ${response.status}.\nThe response text is:\n\n${bodyText}`,
);
}
if (bodyText === "") {
if (bodyText === null) {
return setError("Empty body returned in response");
}
@@ -99,109 +91,15 @@ export function useIntrospectGraphQL(
return;
}
// A request pointed at a file gets its schema from that file. Introspecting
// here would overwrite it on the next URL edit.
if (filePath != null) {
return;
}
refetch().catch(console.error);
}, [
baseRequest.id,
debouncedRequest.url,
debouncedRequest.method,
activeEnvironment?.id,
filePath,
]);
}, [baseRequest.id, debouncedRequest.url, debouncedRequest.method, activeEnvironment?.id]);
// Clears the schema, not the source. Removing a file source is a separate
// action, because the source is what would rebuild this a moment later.
const clear = useCallback(async () => {
setError("");
setSchema(null);
await upsertIntrospection(null);
}, [upsertIntrospection]);
// Reads a schema file and produces an introspection row from it, the same way
// `refetch` produces one from a server. Does not touch the stored source.
const introspectFromFile = useCallback(
async (path: string): Promise<{ ok: true } | { ok: false; error: string }> => {
try {
setIsLoading(true);
setError(undefined);
const fileContent = await platform.files.readText(path);
const result = tryBuildIntrospectionFromFile(fileContent);
if ("error" in result) {
setError(result.error);
return { ok: false, error: result.error };
}
await upsertIntrospection(result.content);
return { ok: true };
} catch (err) {
// The host rejects with a bare string for a missing or unreadable path,
// so this can't assume an Error.
const message = err instanceof Error ? err.message : String(err);
setError(message);
return { ok: false, error: message };
} finally {
setIsLoading(false);
}
},
[upsertIntrospection],
);
// Points the request at a file and immediately builds its schema from it.
const loadFromFile = useCallback(
async (path: string) => {
const result = await introspectFromFile(path);
if (result.ok) await schemaFile.set(path);
return result;
},
[introspectFromFile, schemaFile],
);
const reloadFromFile = useCallback(async () => {
if (filePath == null) return { ok: false as const, error: "No schema file to reload" };
return introspectFromFile(filePath);
}, [filePath, introspectFromFile]);
// The file-source counterpart of automatic introspection: re-read the file
// when the request is opened, so an edited schema is picked up without asking.
//
// A missing row is repaired even with the setting off — that is recovering
// from the 7-day sweep, not keeping the schema fresh, and skipping it would
// make the schema disappear with no visible cause.
const reloadedFor = useRef<string | null>(null);
useEffect(() => {
if (filePath == null || introspection.isLoading) return;
// Only attempt once per path, so an unreadable file doesn't spin.
if (reloadedFor.current === filePath) return;
const hasContent = (introspection.data?.content ?? "") !== "";
if (hasContent && options.disabled) return;
reloadedFor.current = filePath;
introspectFromFile(filePath).catch(console.error);
}, [
filePath,
introspection.data?.content,
introspection.isLoading,
introspectFromFile,
options.disabled,
]);
// Stops using the file. The schema goes with it, since the file is what
// produced it; introspection repopulates if it's set to run automatically.
const removeSchemaFile = useCallback(async () => {
setError("");
setSchema(null);
await schemaFile.set(null);
await upsertIntrospection(null);
}, [schemaFile, upsertIntrospection]);
useEffect(() => {
if (introspection.data?.content == null || introspection.data.content === "") {
return;
@@ -215,17 +113,7 @@ export function useIntrospectGraphQL(
}
}, [introspection.data?.content]);
return {
schema,
isLoading,
error,
refetch,
clear,
loadFromFile,
reloadFromFile,
removeSchemaFile,
filePath,
};
return { schema, isLoading, error, refetch, clear };
}
function useIntrospectionResult(request: HttpRequest) {
@@ -1,67 +0,0 @@
import { useCallback } from "react";
import { useKeyValue } from "./useKeyValue";
export interface RecentFilter {
value: string;
pinned?: boolean;
}
const MAX_RECENT_FILTERS = 20;
const kvKey = (filterStateKey: string) => `recent_filters::${filterStateKey}`;
const namespace = "global";
const fallback: RecentFilter[] = [];
export function useRecentFilters(filterStateKey: string | null) {
const { value, set } = useKeyValue<RecentFilter[]>({
key: kvKey(filterStateKey ?? "n/a"),
namespace,
fallback,
});
const addFilter = useCallback(
async (rawValue: string) => {
const value = rawValue.trim();
if (filterStateKey == null || value === "") return;
await set((prev) => {
// Returning the same reference skips the write, so re-committing the
// expression already at the top (on every blur) costs nothing
if (prev[0]?.value === value) return prev;
const existing = prev.find((f) => f.value === value);
const rest = prev.filter((f) => f.value !== value);
return trim([{ value, pinned: existing?.pinned }, ...rest]);
});
},
[filterStateKey, set],
);
const removeFilter = useCallback(
async (value: string) => set((prev) => prev.filter((f) => f.value !== value)),
[set],
);
const togglePin = useCallback(
async (value: string) =>
set((prev) => prev.map((f) => (f.value === value ? { ...f, pinned: !f.pinned } : f))),
[set],
);
const clearFilters = useCallback(async () => set([]), [set]);
return { recentFilters: value ?? fallback, addFilter, removeFilter, togglePin, clearFilters };
}
/** Bound the list, evicting the oldest unpinned entries before any pinned ones */
function trim(filters: RecentFilter[]): RecentFilter[] {
const excess = filters.length - MAX_RECENT_FILTERS;
if (excess <= 0) return filters;
const evicted = new Set<number>();
for (let i = filters.length - 1; i >= 0 && evicted.size < excess; i--) {
if (!filters[i]?.pinned) evicted.add(i);
}
for (let i = filters.length - 1; i >= 0 && evicted.size < excess; i--) {
evicted.add(i);
}
return filters.filter((_, i) => !evicted.has(i));
}
+8 -20
View File
@@ -2,25 +2,6 @@ import { useQuery } from "@tanstack/react-query";
import type { HttpResponse } from "@yaakapp-internal/models";
import { getResponseBodyBytes, getResponseBodyText } from "../lib/responseBody";
export function responseBodyTextQuery({
response,
filter,
}: {
response: HttpResponse;
filter: string | null;
}) {
return {
queryKey: [
"response_body_text",
response.id,
response.updatedAt,
response.contentLength,
filter ?? "",
],
queryFn: () => getResponseBodyText({ response, filter }),
};
}
export function useResponseBodyText({
response,
filter,
@@ -30,7 +11,14 @@ export function useResponseBodyText({
}) {
return useQuery({
placeholderData: (prev) => prev, // Keep previous data on refetch
...responseBodyTextQuery({ response, filter }),
queryKey: [
"response_body_text",
response.id,
response.updatedAt,
response.contentLength,
filter ?? "",
],
queryFn: () => getResponseBodyText({ response, filter }),
});
}
+1 -2
View File
@@ -18,7 +18,6 @@ export function useResponseBodyUrl(response: HttpResponse | null) {
return useQuery({
queryKey: ["response_body_url", responseId, response?.updatedAt ?? ""],
enabled: responseId != null,
// A response body is stored under the response's own id
queryFn: () => (responseId == null ? null : platform.blobs.url(responseId)),
queryFn: () => (responseId == null ? null : platform.files.responseBodyUrl(responseId)),
});
}
-129
View File
@@ -1,129 +0,0 @@
import { useCallback, useState } from "react";
import { createGlobalState } from "react-use";
import type { RecentFilter } from "./useRecentFilters";
import { useRecentFilters } from "./useRecentFilters";
/** What's typed in the filter box. `null` means the filter box is closed */
const useFilterTextMap = createGlobalState<Record<string, string | null>>({});
/** What's actually applied to the response. Only changes on an explicit apply */
const useAppliedFilterMap = createGlobalState<Record<string, string | null>>({});
export interface ResponseFilterApi {
stateKey: string | null;
/** Draft text in the filter box, or `null` when the box is closed */
filterText: string | null;
/** The expression currently filtering the response */
appliedFilter: string | null;
isSearching: boolean;
/** The box holds an expression that isn't the one currently applied */
isDirty: boolean;
/** Bumped when the (uncontrolled) filter input must re-read its defaultValue */
filterUpdateKey: number;
setFilterText: (value: string | null) => void;
/** Apply the expression to the response, recording it if the filter accepts it */
applyFilter: (value: string) => void;
/** Like applyFilter, but also replaces what's shown in the filter box */
replaceFilter: (value: string) => void;
toggleSearch: () => void;
recentFilters: RecentFilter[];
removeRecentFilter: (value: string) => void;
togglePinRecentFilter: (value: string) => void;
clearRecentFilters: () => void;
}
/**
* Draft/applied state and history for a response filter (JSONPath/XPath).
*
* History records at most one entry per apply gesture, and only after `runFilter`
* confirms the plugin accepts the expression — the plugin is the sole judge of
* validity. Because nothing but the gesture ever writes, refetches can't resurrect
* deleted entries and a gesture can't record into another request's history.
*/
export function useResponseFilter({
stateKey,
runFilter,
}: {
stateKey: string | null;
/** Evaluate an expression, rejecting if the filter plugin reports an error */
runFilter: (filter: string) => Promise<unknown>;
}): ResponseFilterApi {
const [filterTextMap, setFilterTextMap] = useFilterTextMap();
const [appliedFilterMap, setAppliedFilterMap] = useAppliedFilterMap();
const filterText = stateKey ? (filterTextMap[stateKey] ?? null) : null;
const appliedFilter = stateKey ? (appliedFilterMap[stateKey] ?? null) : null;
const setFilterText = useCallback(
(v: string | null) => {
if (!stateKey) return;
setFilterTextMap((m) => ({ ...m, [stateKey]: v }));
},
[stateKey, setFilterTextMap],
);
const setAppliedFilter = useCallback(
(v: string | null) => {
if (!stateKey) return;
setAppliedFilterMap((m) => ({ ...m, [stateKey]: v }));
},
[stateKey, setAppliedFilterMap],
);
const {
recentFilters,
addFilter,
removeFilter: removeRecentFilter,
togglePin: togglePinRecentFilter,
clearFilters: clearRecentFilters,
} = useRecentFilters(stateKey);
const applyFilter = useCallback(
(value: string) => {
setFilterText(value);
const applied = value.trim() === "" ? null : value.trim();
setAppliedFilter(applied);
if (applied == null) return;
runFilter(applied).then(
() => addFilter(applied),
() => {}, // Rejected by the filter plugin — don't record
);
},
[setFilterText, setAppliedFilter, runFilter, addFilter],
);
const [filterUpdateKey, setFilterUpdateKey] = useState(0);
const replaceFilter = useCallback(
(value: string) => {
applyFilter(value);
setFilterUpdateKey((k) => k + 1);
},
[applyFilter],
);
const isSearching = filterText != null;
const toggleSearch = useCallback(() => {
if (isSearching) {
setFilterText(null);
setAppliedFilter(null);
} else {
setFilterText("");
}
}, [isSearching, setFilterText, setAppliedFilter]);
return {
stateKey,
filterText,
appliedFilter,
isSearching,
isDirty: filterText != null && filterText.trim() !== (appliedFilter ?? ""),
filterUpdateKey,
setFilterText,
applyFilter,
replaceFilter,
toggleSearch,
recentFilters,
removeRecentFilter,
togglePinRecentFilter,
clearRecentFilters,
};
}
@@ -25,10 +25,6 @@ export function useSaveResponse(response: HttpResponse | null) {
defaultPath: ext ? `${slug}.${ext}` : slug,
title: "Save Response",
});
if (filepath == null) {
return; // Cancelled
}
await rpc("cmd_save_response", { responseId: response.id, filepath });
showToast({
message: (
@@ -1,85 +0,0 @@
import { buildSchema, introspectionFromSchema } from "graphql";
import { describe, expect, test } from "vite-plus/test";
import { tryBuildIntrospectionFromFile } from "./graphqlSchema";
const sdl = `
type Query {
hello: String!
user(id: ID!): User
}
type User {
id: ID!
name: String
}
`;
const introspection = introspectionFromSchema(buildSchema(sdl));
describe("tryBuildIntrospectionFromFile", () => {
test("accepts introspection JSON wrapped in { data: ... }", () => {
const input = JSON.stringify({ data: introspection });
const result = tryBuildIntrospectionFromFile(input);
expect("schema" in result).toBe(true);
if ("schema" in result) {
expect(result.schema.getQueryType()?.getFields()).toHaveProperty("hello");
// Output content is the normalized, persistable shape.
expect(JSON.parse(result.content)).toHaveProperty("data.__schema");
}
});
test("accepts bare introspection JSON without a data wrapper", () => {
const input = JSON.stringify(introspection);
const result = tryBuildIntrospectionFromFile(input);
expect("schema" in result).toBe(true);
if ("schema" in result) {
expect(result.schema.getQueryType()?.getFields()).toHaveProperty("user");
// Bare input is wrapped on the way out.
expect(JSON.parse(result.content)).toHaveProperty("data.__schema");
}
});
test("accepts a GraphQL SDL string", () => {
const result = tryBuildIntrospectionFromFile(sdl);
expect("schema" in result).toBe(true);
if ("schema" in result) {
const fields = result.schema.getQueryType()?.getFields() ?? {};
expect(fields).toHaveProperty("hello");
expect(fields).toHaveProperty("user");
// SDL is converted to introspection JSON for storage.
expect(JSON.parse(result.content)).toHaveProperty("data.__schema");
}
});
test("returns an error for JSON that is neither introspection nor SDL", () => {
const result = tryBuildIntrospectionFromFile('{"unrelated":"value"}');
expect("error" in result).toBe(true);
if ("error" in result) {
expect(result.error).toMatch(/Could not parse file as introspection JSON or GraphQL SDL/);
}
});
test("returns an error for content that is neither valid JSON nor valid SDL", () => {
const result = tryBuildIntrospectionFromFile("not a schema!@#$");
expect("error" in result).toBe(true);
if ("error" in result) {
expect(result.error).toMatch(/Could not parse file as introspection JSON or GraphQL SDL/);
}
});
test("returns an error when introspection JSON has a malformed __schema", () => {
// Has the data.__schema shape but the contents are invalid for buildClientSchema.
const input = JSON.stringify({ data: { __schema: { broken: true } } });
const result = tryBuildIntrospectionFromFile(input);
expect("error" in result).toBe(true);
if ("error" in result) {
expect(result.error).toMatch(/Failed to build schema from introspection JSON/);
}
});
});
-51
View File
@@ -1,51 +0,0 @@
import type { GraphQLSchema, IntrospectionQuery } from "graphql";
import { buildClientSchema, buildSchema, introspectionFromSchema } from "graphql";
// Accepts either a GraphQL introspection JSON ({ data: { __schema } } or
// { __schema }) or an SDL string and normalizes both into the wrapped
// { data: <introspection> } JSON shape used by the introspection store.
export function tryBuildIntrospectionFromFile(
fileContent: string,
): { schema: GraphQLSchema; content: string } | { error: string } {
let parsedJson: unknown;
try {
parsedJson = JSON.parse(fileContent);
} catch {
parsedJson = undefined;
}
if (parsedJson != null && typeof parsedJson === "object") {
const candidates: unknown[] = [(parsedJson as { data?: unknown }).data, parsedJson];
for (const candidate of candidates) {
if (
candidate != null &&
typeof candidate === "object" &&
"__schema" in (candidate as Record<string, unknown>)
) {
try {
const schema = buildClientSchema(candidate as IntrospectionQuery, {});
return { schema, content: JSON.stringify({ data: candidate }) };
} catch (e) {
return {
error: `Failed to build schema from introspection JSON: ${errorMessage(e)}`,
};
}
}
}
}
try {
const schema = buildSchema(fileContent);
const introspection = introspectionFromSchema(schema);
return { schema, content: JSON.stringify({ data: introspection }) };
} catch (e) {
return {
error: `Could not parse file as introspection JSON or GraphQL SDL: ${errorMessage(e)}`,
};
}
}
function errorMessage(e: unknown): string {
return e instanceof Error ? e.message : String(e);
}
+17 -13
View File
@@ -2,9 +2,11 @@ import type { BatchUpsertResult } from "@yaakapp-internal/models";
import { FormattedError, VStack } from "@yaakapp-internal/ui";
import { Button } from "../components/core/Button";
import { ImportDataDialog } from "../components/ImportDataDialog";
import { activeWorkspaceAtom } from "../hooks/useActiveWorkspace";
import { createFastMutation } from "../hooks/useFastMutation";
import { showAlert } from "./alert";
import { showDialog } from "./dialog";
import { jotaiStore } from "./jotai";
import { pluralizeCount } from "./pluralize";
import { router } from "./router";
import { rpc } from "./rpc";
@@ -26,9 +28,12 @@ export const importData = createFastMutation({
title: "Import Data",
size: "sm",
render: ({ hide }) => {
const importAndHide = async (runImport: () => Promise<BatchUpsertResult>) => {
const importAndHide = async (filePath: string) => {
try {
await finishImport(await runImport());
const didImport = await performImport(filePath);
if (!didImport) {
return;
}
resolve();
} catch (err) {
reject(err);
@@ -36,23 +41,20 @@ export const importData = createFastMutation({
hide();
}
};
return (
<ImportDataDialog
importFile={(filePath) =>
importAndHide(() => rpc<BatchUpsertResult>("cmd_import_data", { filePath }))
}
importUrl={(url) =>
importAndHide(() => rpc<BatchUpsertResult>("cmd_import_url", { url }))
}
/>
);
return <ImportDataDialog importData={importAndHide} />;
},
});
});
},
});
async function finishImport(imported: BatchUpsertResult): Promise<void> {
async function performImport(filePath: string): Promise<boolean> {
const activeWorkspace = jotaiStore.get(activeWorkspaceAtom);
const imported = await rpc<BatchUpsertResult>("cmd_import_data", {
filePath,
workspaceId: activeWorkspace?.id,
});
const importedWorkspace = imported.workspaces[0];
showDialog({
@@ -101,4 +103,6 @@ async function finishImport(imported: BatchUpsertResult): Promise<void> {
search: { environment_id: environmentId },
});
}
return true;
}
+1 -2
View File
@@ -68,8 +68,7 @@ export async function getResponseBodySseSummary(
export async function getResponseBodyBytes(
response: HttpResponse,
): Promise<Uint8Array<ArrayBuffer> | null> {
// A response body is stored under the response's own id
return platform.blobs.read(response.id);
return platform.files.readResponseBody(response.id);
}
async function getResponseBodyDecoded(response: HttpResponse): Promise<string | null> {
+1 -1
View File
@@ -1,6 +1,6 @@
import type { RpcPayload } from "@yaakapp-internal/platform";
import { platform } from "@yaakapp-internal/platform";
import type { RpcSchema } from "@yaakapp-internal/rpc-schema";
import type { RpcSchema } from "@yaakapp-internal/tauri-client";
/**
* Every backend command the app can call: the generated wire schema, one field
+2 -3
View File
@@ -1,12 +1,11 @@
import type { HttpRequest } from "@yaakapp-internal/models";
import type { EphemeralHttpResponse } from "@yaakapp-internal/rpc-schema";
import type { HttpRequest, HttpResponse } from "@yaakapp-internal/models";
import { getActiveCookieJar } from "../hooks/useActiveCookieJar";
import { rpc } from "./rpc";
export async function sendEphemeralRequest(
request: HttpRequest,
environmentId: string | null,
): Promise<EphemeralHttpResponse> {
): Promise<HttpResponse> {
// Remove some things that we don't want to associate
const newRequest = { ...request };
return rpc("cmd_send_ephemeral_request", {
-1
View File
@@ -43,6 +43,5 @@ yaak-http = { workspace = true }
yaak-models = { workspace = true }
yaak-plugins = { workspace = true }
yaak-rpc = { workspace = true }
yaak-rpc-schema = { workspace = true }
yaak-sse = { workspace = true }
yaak-templates = { workspace = true }
+9 -8
View File
@@ -247,12 +247,12 @@ async fn response_body(
Query(_q): Query<BodyQuery>,
headers: HeaderMap,
) -> Response {
let location = match app.state.locate_response_body(&id) {
Ok(location) => location,
let response = match app.state.db().get_http_response(&id) {
Ok(response) => response,
Err(_) => return (StatusCode::NOT_FOUND, "No such response").into_response(),
};
let Some(body_path) = location.path else {
let Some(body_path) = response.body_path else {
return (StatusCode::NOT_FOUND, "Response has no body").into_response();
};
@@ -269,11 +269,12 @@ async fn response_body(
}
};
let content_type = if location.content_type.is_empty() {
"application/octet-stream".to_string()
} else {
location.content_type
};
let content_type = response
.headers
.iter()
.find(|h| h.name.eq_ignore_ascii_case("content-type"))
.map(|h| h.value.clone())
.unwrap_or_else(|| "application/octet-stream".to_string());
let range = headers.get(header::RANGE).and_then(|v| v.to_str().ok()).and_then(parse_range);
+372 -166
View File
@@ -7,14 +7,16 @@
//! they are plain data. The command *bodies* are what matter, and they call the
//! same engine functions the desktop calls.
use super::{BridgeCtx, unsupported_command};
use super::{BridgeCtx, UNSUPPORTED_COMMANDS, unsupported_command};
use mime_guess::{Mime, mime};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use yaak::import::{ImportDataParams, import_data as import_data_shared};
use yaak::models_ops::{delete_model, duplicate_model, upsert_model};
use yaak::send::{ResponseBody, SendHttpRequestWithPluginsParams, send_http_request_with_plugins};
use yaak::responses::{is_response_id, response_body_path};
use yaak::send::{SendHttpRequestWithPluginsParams, send_http_request_with_plugins};
use yaak_core::WorkspaceContext;
use yaak_models::models::{
AnyModel, Environment, GraphQlIntrospection, GrpcEvent, HttpRequest, HttpRequestHeader,
@@ -35,11 +37,10 @@ use yaak_plugins::native_template_functions::{
};
use yaak_plugins::plugin_meta::PluginMetadata;
use yaak_rpc::{RpcError, RpcRouter, rpc_handler_async};
use yaak_rpc_schema::*;
use yaak_sse::sse::ServerSentEvent;
use yaak_templates::format_json::format_json;
use yaak_templates::{
RenderErrorBehavior, RenderOptions, TemplateCallback, parse_and_render,
RenderErrorBehavior, RenderOptions, TemplateCallback, Tokens, parse_and_render,
render_json_value_raw,
};
@@ -68,11 +69,51 @@ where
}
}
macro_rules! rpc_commands {
( $( $name:ident ),* $(,)? ) => {
pub fn build_router() -> RpcRouter<BridgeCtx> {
let mut router = RpcRouter::new();
$( router.register(stringify!($name), rpc_handler_async!($name)); )*
for cmd in UNSUPPORTED_COMMANDS {
router.register(
cmd,
Box::new(move |_ctx, _payload| {
let cmd = *cmd;
Box::pin(async move { Err(unsupported_command(cmd)) })
}),
);
}
router
}
};
}
// -- App metadata --
async fn cmd_metadata(ctx: BridgeCtx, _req: CmdMetadataReq) -> Result<AppMetaData> {
#[derive(Debug, Deserialize)]
pub struct EmptyReq {}
/// Deliberately not the desktop's `AppMetaData`: that type lives in a Tauri
/// crate and half its fields are Tauri paths. The serialized shape is the same,
/// which is what the frontend reads.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BridgeMetaData {
is_dev: bool,
version: String,
cli_version: Option<String>,
name: String,
app_data_dir: String,
app_log_dir: String,
vendored_plugin_dir: String,
default_project_dir: String,
feature_updater: bool,
feature_license: bool,
}
async fn cmd_metadata(ctx: BridgeCtx, _req: EmptyReq) -> Result<BridgeMetaData> {
let data_dir = ctx.state.data_dir().to_string_lossy().to_string();
Ok(AppMetaData {
Ok(BridgeMetaData {
is_dev: ctx.state.is_dev,
version: env!("CARGO_PKG_VERSION").to_string(),
cli_version: None,
@@ -97,11 +138,23 @@ async fn cmd_metadata(ctx: BridgeCtx, _req: CmdMetadataReq) -> Result<AppMetaDat
// -- Models --
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelsUpsertReq {
pub model: AnyModel,
}
async fn models_upsert(ctx: BridgeCtx, req: ModelsUpsertReq) -> Result<String> {
let db = ctx.state.db();
upsert_model(&db, ctx.state.blob_manager(), req.model, &ctx.update_source()).map_err(err)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelsDeleteReq {
pub model: AnyModel,
}
/// Deletes run on a blocking thread, as they do on the desktop: a transaction
/// holds a raw sqlite connection, which is neither `Send` nor cheap to hold —
/// dropping a workspace with thousands of requests would otherwise stall the
@@ -116,6 +169,13 @@ async fn models_delete(ctx: BridgeCtx, req: ModelsDeleteReq) -> Result<String> {
.await
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelsDuplicateReq {
pub model_type: String,
pub model_id: String,
}
async fn models_duplicate(ctx: BridgeCtx, req: ModelsDuplicateReq) -> Result<String> {
let source = ctx.update_source();
blocking(move || {
@@ -126,10 +186,16 @@ async fn models_duplicate(ctx: BridgeCtx, req: ModelsDuplicateReq) -> Result<Str
.await
}
async fn models_get_settings(ctx: BridgeCtx, _req: ModelsGetSettingsReq) -> Result<Settings> {
async fn models_get_settings(ctx: BridgeCtx, _req: EmptyReq) -> Result<Settings> {
Ok(ctx.state.db().get_settings())
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelsWorkspaceModelsReq {
pub workspace_id: Option<String>,
}
/// Everything the frontend's model store needs for a workspace, as one JSON
/// string.
///
@@ -203,6 +269,12 @@ async fn models_workspace_models(ctx: BridgeCtx, req: ModelsWorkspaceModelsReq)
serde_json::to_string(&l).map_err(err)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelsWebsocketEventsReq {
pub connection_id: String,
}
async fn models_websocket_events(
ctx: BridgeCtx,
req: ModelsWebsocketEventsReq,
@@ -210,10 +282,22 @@ async fn models_websocket_events(
ctx.state.db().list_websocket_events(&req.connection_id).map_err(err)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelsGrpcEventsReq {
pub connection_id: String,
}
async fn models_grpc_events(ctx: BridgeCtx, req: ModelsGrpcEventsReq) -> Result<Vec<GrpcEvent>> {
ctx.state.db().list_grpc_events(&req.connection_id).map_err(err)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelsGetGraphqlIntrospectionReq {
pub request_id: String,
}
async fn models_get_graphql_introspection(
ctx: BridgeCtx,
req: ModelsGetGraphqlIntrospectionReq,
@@ -221,6 +305,14 @@ async fn models_get_graphql_introspection(
Ok(ctx.state.db().get_graphql_introspection(&req.request_id))
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelsUpsertGraphqlIntrospectionReq {
pub request_id: String,
pub workspace_id: String,
pub content: Option<String>,
}
async fn models_upsert_graphql_introspection(
ctx: BridgeCtx,
req: ModelsUpsertGraphqlIntrospectionReq,
@@ -236,6 +328,12 @@ async fn models_upsert_graphql_introspection(
.map_err(err)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdGetWorkspaceMetaReq {
pub workspace_id: String,
}
async fn cmd_get_workspace_meta(
ctx: BridgeCtx,
req: CmdGetWorkspaceMetaReq,
@@ -247,6 +345,14 @@ async fn cmd_get_workspace_meta(
// -- Sending --
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdSendHttpRequestReq {
pub environment_id: Option<String>,
pub cookie_jar_id: Option<String>,
pub request_id: String,
}
/// Send a saved request.
///
/// Same sequence as the desktop (crates-tauri/.../lib.rs `cmd_send_http_request`):
@@ -338,13 +444,20 @@ async fn send_persisted(
Ok(result.response)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdSendEphemeralRequestReq {
pub request: HttpRequest,
pub environment_id: Option<String>,
pub cookie_jar_id: Option<String>,
}
/// Send without saving. An empty request id keeps the engine from persisting
/// anything, so the body comes back in memory and rides along with the
/// response — there is no row to look up later and no file to serve.
/// anything, so the body comes back in memory instead of on disk.
async fn cmd_send_ephemeral_request(
ctx: BridgeCtx,
req: CmdSendEphemeralRequestReq,
) -> Result<EphemeralHttpResponse> {
) -> Result<HttpResponse> {
let mut request = req.request;
request.id = String::new();
let plugin_manager = ctx.plugins()?;
@@ -370,25 +483,64 @@ async fn cmd_send_ephemeral_request(
.await
.map_err(err)?;
// Blanking the request id above is what makes this send unsaved, so the
// engine always hands the body back. Failing loudly beats returning an
// empty body that reads as "the server sent nothing".
let ResponseBody::Returned(body) = result.response_body else {
return Err(RpcError { message: "Unsaved response did not return a body".to_string() });
};
Ok(EphemeralHttpResponse { response: result.response, body })
Ok(result.response)
}
// -- Reading responses --
/// The frontend hands back an id and never a path, so the only bodies reachable
/// here are ones the engine wrote and the database still knows about.
/// Where a response's body is, and what it is meant to be read as.
struct ResponseBodyLocation {
/// None when the response has no stored body.
path: Option<PathBuf>,
/// The response's declared `Content-Type`, empty when it has none. An
/// ephemeral response has no headers to consult, so its body decodes as
/// UTF-8.
content_type: String,
}
/// Find a response's body from its id alone.
///
/// The tab hands back an id and never a path, so nothing a page says can point
/// this at a file the engine didn't write — the same rule `GET
/// /responses/:id/body` follows. Persisted responses carry the path they were
/// written to; ephemeral ones (GraphQL introspection) never reach the database,
/// but their body still lands at `<response dir>/<id>`, which is how
/// [`yaak::send`] builds the path in the first place.
fn locate_response_body(ctx: &BridgeCtx, response_id: &str) -> Result<ResponseBodyLocation> {
if !is_response_id(response_id) {
return Err(RpcError { message: format!("Invalid response ID {response_id}") });
}
match ctx.state.db().get_http_response(response_id) {
Ok(response) => Ok(ResponseBodyLocation {
path: response.body_path.map(PathBuf::from),
content_type: response
.headers
.iter()
.find(|h| h.name.eq_ignore_ascii_case("content-type"))
.map(|h| h.value.clone())
.unwrap_or_default(),
}),
Err(yaak_models::error::Error::ModelNotFound(_)) => Ok(ResponseBodyLocation {
path: Some(response_body_path(&ctx.state.response_dir(), response_id)),
content_type: String::new(),
}),
Err(e) => Err(err(e)),
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdHttpResponseBodyReq {
pub response_id: String,
pub filter: Option<String>,
}
async fn cmd_http_response_body(
ctx: BridgeCtx,
req: CmdHttpResponseBodyReq,
) -> Result<FilterResponse> {
let location = ctx.state.locate_response_body(&req.response_id).map_err(err)?;
let location = locate_response_body(&ctx, &req.response_id)?;
let Some(body_path) = location.path else {
return Ok(FilterResponse { content: String::new(), error: None });
};
@@ -408,18 +560,6 @@ async fn cmd_http_response_body(
}
}
/// The desktop host uses this to open the file itself. A tab cannot open a
/// path, so the bridge's browser host never calls it — it fetches
/// `/responses/:id/body` instead — but the command answers honestly for any
/// client that does, with the path on the bridge's machine.
async fn cmd_http_response_body_path(
ctx: BridgeCtx,
req: CmdHttpResponseBodyPathReq,
) -> Result<Option<String>> {
let location = ctx.state.locate_response_body(&req.response_id).map_err(err)?;
Ok(location.path.map(|p| p.to_string_lossy().to_string()))
}
/// Decode a response body from disk using the charset its Content-Type
/// declares. Ported from crates-tauri/yaak-app-client/src/encoding.rs.
async fn read_response_body(body_path: impl AsRef<Path>, content_type: &str) -> Option<String> {
@@ -437,6 +577,12 @@ fn parse_charset(content_type: &str) -> Option<String> {
mime.get_param(mime::CHARSET).map(|v| v.to_string())
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdHttpRequestBodyReq {
pub response_id: String,
}
async fn cmd_http_request_body(
ctx: BridgeCtx,
req: CmdHttpRequestBodyReq,
@@ -449,6 +595,12 @@ async fn cmd_http_request_body(
Ok(Some(chunks.into_iter().flat_map(|c| c.data).collect()))
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdGetHttpResponseEventsReq {
pub response_id: String,
}
async fn cmd_get_http_response_events(
ctx: BridgeCtx,
req: CmdGetHttpResponseEventsReq,
@@ -456,14 +608,19 @@ async fn cmd_get_http_response_events(
ctx.state.db().list_http_response_events(&req.response_id).map_err(err)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdGetSseEventsReq {
pub response_id: String,
}
async fn cmd_get_sse_events(
ctx: BridgeCtx,
req: CmdGetSseEventsReq,
) -> Result<Vec<ServerSentEvent>> {
use eventsource_client::{EventParser, SSE};
let Some(body_path) = ctx.state.locate_response_body(&req.response_id).map_err(err)?.path
else {
let Some(body_path) = locate_response_body(&ctx, &req.response_id)?.path else {
return Ok(Vec::new());
};
@@ -485,6 +642,12 @@ async fn cmd_get_sse_events(
Ok(events)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdDeleteAllHttpResponsesReq {
pub request_id: String,
}
async fn cmd_delete_all_http_responses(
ctx: BridgeCtx,
req: CmdDeleteAllHttpResponsesReq,
@@ -496,6 +659,12 @@ async fn cmd_delete_all_http_responses(
Ok(())
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdDeleteSendHistoryReq {
pub workspace_id: String,
}
async fn cmd_delete_send_history(ctx: BridgeCtx, req: CmdDeleteSendHistoryReq) -> Result<()> {
let source = ctx.update_source();
blocking(move || {
@@ -511,10 +680,22 @@ async fn cmd_delete_send_history(ctx: BridgeCtx, req: CmdDeleteSendHistoryReq) -
// -- Formatting and templates --
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdFormatJsonReq {
pub text: String,
}
async fn cmd_format_json(_ctx: BridgeCtx, req: CmdFormatJsonReq) -> Result<String> {
Ok(format_json(&req.text, " "))
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdFormatGraphqlReq {
pub text: String,
}
async fn cmd_format_graphql(_ctx: BridgeCtx, req: CmdFormatGraphqlReq) -> Result<String> {
match pretty_graphql::format_text(&req.text, &Default::default()) {
Ok(formatted) => Ok(formatted),
@@ -522,6 +703,16 @@ async fn cmd_format_graphql(_ctx: BridgeCtx, req: CmdFormatGraphqlReq) -> Result
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdRenderTemplateReq {
pub template: String,
pub workspace_id: String,
pub environment_id: Option<String>,
pub purpose: Option<RenderPurpose>,
pub ignore_error: Option<bool>,
}
async fn cmd_render_template(ctx: BridgeCtx, req: CmdRenderTemplateReq) -> Result<String> {
let environment_chain = ctx
.state
@@ -556,6 +747,12 @@ async fn render_json_value<T: TemplateCallback>(
render_json_value_raw(value, vars, cb, opt).await
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdTemplateTokensToStringReq {
pub tokens: Tokens,
}
async fn cmd_template_tokens_to_string(
_ctx: BridgeCtx,
req: CmdTemplateTokensToStringReq,
@@ -563,6 +760,12 @@ async fn cmd_template_tokens_to_string(
Ok(req.tokens.to_string())
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdDecryptTemplateReq {
pub template: String,
}
async fn cmd_decrypt_template(ctx: BridgeCtx, req: CmdDecryptTemplateReq) -> Result<String> {
decrypt_secure_template_function(
&ctx.state.encryption_manager,
@@ -572,6 +775,12 @@ async fn cmd_decrypt_template(ctx: BridgeCtx, req: CmdDecryptTemplateReq) -> Res
.map_err(err)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdSecureTemplateReq {
pub template: String,
}
async fn cmd_secure_template(ctx: BridgeCtx, req: CmdSecureTemplateReq) -> Result<String> {
encrypt_secure_template_function(
ctx.plugins()?,
@@ -582,13 +791,13 @@ async fn cmd_secure_template(ctx: BridgeCtx, req: CmdSecureTemplateReq) -> Resul
.map_err(err)
}
async fn cmd_default_headers(_ctx: BridgeCtx, _req: CmdDefaultHeadersReq) -> Result<Vec<HttpRequestHeader>> {
async fn cmd_default_headers(_ctx: BridgeCtx, _req: EmptyReq) -> Result<Vec<HttpRequestHeader>> {
Ok(default_headers())
}
// -- Plugins --
async fn cmd_get_themes(ctx: BridgeCtx, _req: CmdGetThemesReq) -> Result<Vec<GetThemesResponse>> {
async fn cmd_get_themes(ctx: BridgeCtx, _req: EmptyReq) -> Result<Vec<GetThemesResponse>> {
// Themes are optional: the TypeScript package ships defaults, and an empty
// list still renders. Don't fail boot when the runtime is down.
let Ok(plugins) = ctx.plugins() else {
@@ -597,13 +806,19 @@ async fn cmd_get_themes(ctx: BridgeCtx, _req: CmdGetThemesReq) -> Result<Vec<Get
plugins.get_themes(&ctx.plugin_context()).await.map_err(err)
}
async fn cmd_plugin_init_errors(ctx: BridgeCtx, _req: CmdPluginInitErrorsReq) -> Result<Vec<(String, String)>> {
async fn cmd_plugin_init_errors(ctx: BridgeCtx, _req: EmptyReq) -> Result<Vec<(String, String)>> {
let Ok(plugins) = ctx.plugins() else {
return Ok(Vec::new());
};
Ok(plugins.take_init_errors().await)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdPluginInfoReq {
pub id: String,
}
async fn cmd_plugin_info(ctx: BridgeCtx, req: CmdPluginInfoReq) -> Result<PluginMetadata> {
let plugin = ctx.state.db().get_plugin(&req.id).map_err(err)?;
let plugins = ctx.plugins()?;
@@ -616,11 +831,24 @@ async fn cmd_plugin_info(ctx: BridgeCtx, req: CmdPluginInfoReq) -> Result<Plugin
async fn cmd_template_function_summaries(
ctx: BridgeCtx,
_req: CmdTemplateFunctionSummariesReq,
_req: EmptyReq,
) -> Result<Vec<GetTemplateFunctionSummaryResponse>> {
ctx.plugins()?.get_template_function_summaries(&ctx.plugin_context()).await.map_err(err)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdTemplateFunctionConfigReq {
pub function_name: String,
pub values: HashMap<String, JsonPrimitive>,
pub model: AnyModel,
/// Sent by the frontend, unused here — same as the desktop, which takes it
/// as `_environment_id`. Template function values are not pre-rendered the
/// way auth values are.
#[allow(dead_code)]
pub environment_id: Option<String>,
}
async fn cmd_template_function_config(
ctx: BridgeCtx,
req: CmdTemplateFunctionConfigReq,
@@ -638,13 +866,22 @@ async fn cmd_template_function_config(
async fn cmd_get_http_authentication_summaries(
ctx: BridgeCtx,
_req: CmdGetHttpAuthenticationSummariesReq,
_req: EmptyReq,
) -> Result<Vec<GetHttpAuthenticationSummaryResponse>> {
let results =
ctx.plugins()?.get_http_authentication_summaries(&ctx.plugin_context()).await.map_err(err)?;
Ok(results.into_iter().map(|(_, a)| a).collect())
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdGetHttpAuthenticationConfigReq {
pub auth_name: String,
pub values: HashMap<String, JsonPrimitive>,
pub model: AnyModel,
pub environment_id: Option<String>,
}
async fn cmd_get_http_authentication_config(
ctx: BridgeCtx,
req: CmdGetHttpAuthenticationConfigReq,
@@ -662,6 +899,16 @@ async fn cmd_get_http_authentication_config(
.map_err(err)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdCallHttpAuthenticationActionReq {
pub auth_name: String,
pub action_index: i32,
pub values: HashMap<String, JsonPrimitive>,
pub model: AnyModel,
pub environment_id: Option<String>,
}
async fn cmd_call_http_authentication_action(
ctx: BridgeCtx,
req: CmdCallHttpAuthenticationActionReq,
@@ -726,11 +973,17 @@ async fn render_auth_values(
async fn cmd_http_request_actions(
ctx: BridgeCtx,
_req: CmdHttpRequestActionsReq,
_req: EmptyReq,
) -> Result<Vec<GetHttpRequestActionsResponse>> {
ctx.plugins()?.get_http_request_actions(&ctx.plugin_context()).await.map_err(err)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdCallHttpRequestActionReq {
pub req: CallHttpRequestActionRequest,
}
async fn cmd_call_http_request_action(
ctx: BridgeCtx,
req: CmdCallHttpRequestActionReq,
@@ -765,11 +1018,17 @@ async fn cmd_call_http_request_action(
async fn cmd_workspace_actions(
ctx: BridgeCtx,
_req: CmdWorkspaceActionsReq,
_req: EmptyReq,
) -> Result<Vec<GetWorkspaceActionsResponse>> {
ctx.plugins()?.get_workspace_actions(&ctx.plugin_context()).await.map_err(err)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdCallWorkspaceActionReq {
pub req: CallWorkspaceActionRequest,
}
async fn cmd_call_workspace_action(ctx: BridgeCtx, req: CmdCallWorkspaceActionReq) -> Result<()> {
use yaak_plugins::events::CallWorkspaceActionArgs;
@@ -783,10 +1042,16 @@ async fn cmd_call_workspace_action(ctx: BridgeCtx, req: CmdCallWorkspaceActionRe
.map_err(err)
}
async fn cmd_folder_actions(ctx: BridgeCtx, _req: CmdFolderActionsReq) -> Result<Vec<GetFolderActionsResponse>> {
async fn cmd_folder_actions(ctx: BridgeCtx, _req: EmptyReq) -> Result<Vec<GetFolderActionsResponse>> {
ctx.plugins()?.get_folder_actions(&ctx.plugin_context()).await.map_err(err)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdCallFolderActionReq {
pub req: CallFolderActionRequest,
}
async fn cmd_call_folder_action(ctx: BridgeCtx, req: CmdCallFolderActionReq) -> Result<()> {
use yaak_plugins::events::CallFolderActionArgs;
@@ -802,6 +1067,13 @@ async fn cmd_call_folder_action(ctx: BridgeCtx, req: CmdCallFolderActionReq) ->
// -- Import --
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdCurlToRequestReq {
pub command: String,
pub workspace_id: String,
}
async fn cmd_curl_to_request(ctx: BridgeCtx, req: CmdCurlToRequestReq) -> Result<HttpRequest> {
let import_result =
ctx.plugins()?.import_data(&ctx.plugin_context(), &req.command).await.map_err(err)?;
@@ -818,6 +1090,12 @@ async fn cmd_curl_to_request(ctx: BridgeCtx, req: CmdCurlToRequestReq) -> Result
Ok(request)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CmdImportDataReq {
pub file_path: String,
}
/// Import from a path on the *bridge's* machine.
///
/// The desktop gets this path from a native file dialog. A tab has no way to
@@ -846,131 +1124,59 @@ async fn cmd_import_data(ctx: BridgeCtx, req: CmdImportDataReq) -> Result<BatchU
.map_err(err)
}
// -- Not on this host --
rpc_commands! {
cmd_metadata,
cmd_default_headers,
cmd_get_themes,
cmd_plugin_init_errors,
cmd_plugin_info,
/// Commands the bridge does not implement. Each still gets an adapter, so the
/// schema stays fully covered and the frontend receives a structured error
/// naming the command and this host rather than a bare "unknown command".
///
/// One list, two uses: `unsupported_commands!` emits both the adapters and the
/// `UNSUPPORTED_COMMANDS` array `implemented_commands` subtracts.
macro_rules! unsupported_commands {
( $( $name:ident ( $req:ty ) ),* $(,)? ) => {
// The stub never produces a value, so it doesn't need to name the
// response type — which keeps git, gRPC and WebSocket crates out of a
// binary that will never call them. `Never` serializes fine.
$( async fn $name(_ctx: BridgeCtx, _req: $req) -> Result<Never> {
Err(unsupported_command(stringify!($name)))
} )*
pub const UNSUPPORTED_COMMANDS: &[&str] = &[ $( stringify!($name), )* ];
};
models_upsert,
models_delete,
models_duplicate,
models_get_settings,
models_workspace_models,
models_websocket_events,
models_grpc_events,
models_get_graphql_introspection,
models_upsert_graphql_introspection,
cmd_get_workspace_meta,
cmd_send_http_request,
cmd_send_ephemeral_request,
cmd_http_response_body,
cmd_http_request_body,
cmd_get_http_response_events,
cmd_get_sse_events,
cmd_delete_all_http_responses,
cmd_delete_send_history,
cmd_format_json,
cmd_format_graphql,
cmd_render_template,
cmd_template_tokens_to_string,
cmd_decrypt_template,
cmd_secure_template,
cmd_template_function_summaries,
cmd_template_function_config,
cmd_get_http_authentication_summaries,
cmd_get_http_authentication_config,
cmd_call_http_authentication_action,
cmd_http_request_actions,
cmd_call_http_request_action,
cmd_workspace_actions,
cmd_call_workspace_action,
cmd_folder_actions,
cmd_call_folder_action,
cmd_curl_to_request,
cmd_import_data,
}
/// A value that cannot exist. The unsupported adapters return `Result<Never>`
/// and always take the `Err` branch, so `rpc_handler_async!` has something
/// serializable to name without a real response type ever being constructed.
#[derive(serde::Serialize)]
enum Never {}
unsupported_commands! {
// Multi-window. A tab is one window; Settings opens through this on the desktop and is therefore unreachable in the browser today.
cmd_new_child_window(CmdNewChildWindowReq),
cmd_new_main_window(CmdNewMainWindowReq),
// gRPC and WebSocket sending.
cmd_grpc_reflect(CmdGrpcReflectReq),
cmd_grpc_go(CmdGrpcGoReq),
cmd_grpc_request_actions(CmdGrpcRequestActionsReq),
cmd_call_grpc_request_action(CmdCallGrpcRequestActionReq),
cmd_delete_all_grpc_connections(CmdDeleteAllGrpcConnectionsReq),
cmd_ws_connect(CmdWsConnectReq),
cmd_ws_send(CmdWsSendReq),
cmd_ws_close(CmdWsCloseReq),
cmd_ws_delete_connections(CmdWsDeleteConnectionsReq),
cmd_websocket_request_actions(CmdWebsocketRequestActionsReq),
cmd_call_websocket_request_action(CmdCallWebsocketRequestActionReq),
// Git-backed workspaces.
cmd_git_checkout(CmdGitCheckoutReq),
cmd_git_branch(CmdGitBranchReq),
cmd_git_delete_branch(CmdGitDeleteBranchReq),
cmd_git_delete_remote_branch(CmdGitDeleteRemoteBranchReq),
cmd_git_merge_branch(CmdGitMergeBranchReq),
cmd_git_rename_branch(CmdGitRenameBranchReq),
cmd_git_status(CmdGitStatusReq),
cmd_git_branch_info(CmdGitBranchInfoReq),
cmd_git_worktree_status(CmdGitWorktreeStatusReq),
cmd_git_log(CmdGitLogReq),
cmd_git_log_for_file(CmdGitLogForFileReq),
cmd_git_file_diff_for_commit(CmdGitFileDiffForCommitReq),
cmd_git_initialize(CmdGitInitializeReq),
cmd_git_clone(CmdGitCloneReq),
cmd_git_commit(CmdGitCommitReq),
cmd_git_fetch_all(CmdGitFetchAllReq),
cmd_git_push(CmdGitPushReq),
cmd_git_pull(CmdGitPullReq),
cmd_git_pull_force_reset(CmdGitPullForceResetReq),
cmd_git_pull_merge(CmdGitPullMergeReq),
cmd_git_add(CmdGitAddReq),
cmd_git_unstage(CmdGitUnstageReq),
cmd_git_reset_changes(CmdGitResetChangesReq),
cmd_git_restore_files(CmdGitRestoreFilesReq),
cmd_git_restore_file_from_commit(CmdGitRestoreFileFromCommitReq),
cmd_git_add_credential(CmdGitAddCredentialReq),
cmd_git_remotes(CmdGitRemotesReq),
cmd_git_add_remote(CmdGitAddRemoteReq),
cmd_git_rm_remote(CmdGitRmRemoteReq),
cmd_git_watch_worktree_status(CmdGitWatchWorktreeStatusReq),
// Filesystem sync.
cmd_sync_calculate(CmdSyncCalculateReq),
cmd_sync_calculate_fs(CmdSyncCalculateFsReq),
cmd_sync_apply(CmdSyncApplyReq),
cmd_sync_watch(CmdSyncWatchReq),
// Workspace encryption.
cmd_enable_encryption(CmdEnableEncryptionReq),
cmd_disable_encryption(CmdDisableEncryptionReq),
cmd_reveal_workspace_key(CmdRevealWorkspaceKeyReq),
cmd_set_workspace_key(CmdSetWorkspaceKeyReq),
// Things that need a local filesystem the tab can point at.
cmd_export_data(CmdExportDataReq),
cmd_save_response(CmdSaveResponseReq),
cmd_save_base64_to_binary(CmdSaveBase64ToBinaryReq),
cmd_plugins_install_from_directory(CmdPluginsInstallFromDirectoryReq),
cmd_import_url(CmdImportUrlReq),
// Desktop application management.
cmd_restart(CmdRestartReq),
cmd_check_for_updates(CmdCheckForUpdatesReq),
cmd_dismiss_notification(CmdDismissNotificationReq),
cmd_send_feedback(CmdSendFeedbackReq),
cmd_plugins_search(CmdPluginsSearchReq),
cmd_plugins_install(CmdPluginsInstallReq),
cmd_plugins_uninstall(CmdPluginsUninstallReq),
cmd_plugins_updates(CmdPluginsUpdatesReq),
cmd_plugins_update_all(CmdPluginsUpdateAllReq),
cmd_reload_plugins(CmdReloadPluginsReq),
}
// -- The router --
/// Every command in the schema, wired to an adapter here.
///
/// The list comes from `yaak_rpc_schema`, so this host cannot silently miss a
/// command the frontend knows about: a schema entry with no adapter below is a
/// compile error, not a runtime "unknown command". Commands the bridge does not
/// support still get an adapter — one that says so — which is what lets the
/// frontend tell a host that will never do git from one that is out of date.
macro_rules! register_commands {
( $( $name:ident ( $req:ty ) -> $res:ty ),* $(,)? ) => {
pub fn build_router() -> RpcRouter<BridgeCtx> {
let mut router = RpcRouter::new();
$( router.register(stringify!($name), rpc_handler_async!($name)); )*
router
}
};
}
yaak_rpc_schema::with_commands!(register_commands);
/// The names of the commands this host actually implements — everything in
/// the schema minus the ones whose adapter is `unsupported`. Reported to the
/// browser so it can fail fast with a clear message.
/// Command names this host implements, for the capability report.
pub fn implemented_commands(router: &RpcRouter<BridgeCtx>) -> Vec<String> {
let unsupported: std::collections::HashSet<&str> =
UNSUPPORTED_COMMANDS.iter().copied().collect();
+91 -7
View File
@@ -1,17 +1,15 @@
//! The bridge's RPC surface.
//!
//! Same envelope, same command names, same request and response types as the
//! desktop — all of that comes from `yaak_rpc_schema` — dispatched through the
//! Same envelope and same command names as the desktop, dispatched through the
//! same `RpcRouter`. Only the adapters differ: the desktop's take a Tauri
//! window and read the workspace off its URL, while these take a `BridgeCtx`
//! carrying the connected tab's reported URL. The bodies underneath call the
//! same engine functions in `yaak`, `yaak-models` and `yaak-plugins`.
//!
//! The router is built from the schema's full command list, so every command
//! the frontend knows has an adapter here — the ones this host doesn't
//! implement return a structured error naming the command and the host, and
//! the frontend surfaces "not supported by the Yaak Bridge" instead of a bare
//! failure. Enough is implemented to boot, edit, send and inspect.
//! This is a subset — enough to boot, edit, send and inspect. Anything not
//! registered here still gets a well-formed answer: `unsupported_command`
//! turns it into an RPC error naming the command and this host, so the frontend
//! surfaces "not supported by the Yaak Bridge" instead of a bare failure.
mod commands;
@@ -56,6 +54,92 @@ pub fn build_router() -> RpcRouter<BridgeCtx> {
commands::build_router()
}
/// Every command the desktop has that the bridge does not implement.
///
/// Registered explicitly rather than left to fall through to "unknown command",
/// so the message says *why* — the frontend can tell a host that will never
/// support git from one that is simply out of date.
pub const UNSUPPORTED_COMMANDS: &[&str] = &[
// Multi-window. A tab is one window; Settings opens through this on the
// desktop and is therefore unreachable in the browser today.
"cmd_new_child_window",
"cmd_new_main_window",
// gRPC and WebSocket sending.
"cmd_grpc_reflect",
"cmd_grpc_go",
"cmd_grpc_request_actions",
"cmd_call_grpc_request_action",
"cmd_delete_all_grpc_connections",
"cmd_ws_connect",
"cmd_ws_send",
"cmd_ws_close",
"cmd_ws_delete_connections",
"cmd_websocket_request_actions",
"cmd_call_websocket_request_action",
// Git-backed workspaces.
"cmd_git_checkout",
"cmd_git_branch",
"cmd_git_delete_branch",
"cmd_git_delete_remote_branch",
"cmd_git_merge_branch",
"cmd_git_rename_branch",
"cmd_git_status",
"cmd_git_branch_info",
"cmd_git_worktree_status",
"cmd_git_log",
"cmd_git_log_for_file",
"cmd_git_file_diff_for_commit",
"cmd_git_initialize",
"cmd_git_clone",
"cmd_git_commit",
"cmd_git_fetch_all",
"cmd_git_push",
"cmd_git_pull",
"cmd_git_pull_force_reset",
"cmd_git_pull_merge",
"cmd_git_add",
"cmd_git_unstage",
"cmd_git_reset_changes",
"cmd_git_restore_files",
"cmd_git_restore_file_from_commit",
"cmd_git_add_credential",
"cmd_git_remotes",
"cmd_git_add_remote",
"cmd_git_rm_remote",
"cmd_git_watch_worktree_status",
// Filesystem sync.
"cmd_sync_calculate",
"cmd_sync_calculate_fs",
"cmd_sync_apply",
"cmd_sync_watch",
// Workspace encryption.
"cmd_enable_encryption",
"cmd_disable_encryption",
"cmd_reveal_workspace_key",
"cmd_set_workspace_key",
// Things that need a local filesystem the tab can point at.
//
// `cmd_http_response_body_path` is how the desktop host turns a response id
// into a file it can open; a tab has nothing to do with the answer and
// fetches `/responses/:id/body` instead.
"cmd_http_response_body_path",
"cmd_export_data",
"cmd_save_response",
"cmd_save_base64_to_binary",
"cmd_plugins_install_from_directory",
// Desktop application management.
"cmd_restart",
"cmd_check_for_updates",
"cmd_dismiss_notification",
"cmd_send_feedback",
"cmd_plugins_search",
"cmd_plugins_install",
"cmd_plugins_uninstall",
"cmd_plugins_updates",
"cmd_plugins_update_all",
"cmd_reload_plugins",
];
pub fn unsupported_command(cmd: &str) -> RpcError {
RpcError {
message: format!("`{cmd}` is not supported on this host (Yaak Bridge)"),
-30
View File
@@ -84,14 +84,6 @@ impl BridgeCapabilities {
}
}
/// Where a response's body is, and what it is meant to be read as.
pub struct ResponseBodyLocation {
/// None when the response has no stored body.
pub path: Option<PathBuf>,
/// The response's declared `Content-Type`, empty when it has none.
pub content_type: String,
}
pub struct BridgeState {
data_dir: PathBuf,
query_manager: QueryManager,
@@ -207,28 +199,6 @@ impl BridgeState {
self.data_dir.join("responses")
}
/// Find a response's body from its id alone.
///
/// The tab hands back an id and never a path, so the only bodies reachable
/// through the bridge are ones the engine wrote and the database still
/// knows about. Every route and command that reads a body goes through
/// here for that reason.
pub fn locate_response_body(
&self,
response_id: &str,
) -> yaak_models::error::Result<ResponseBodyLocation> {
let response = self.db().get_http_response(response_id)?;
Ok(ResponseBodyLocation {
path: response.body_path.map(PathBuf::from),
content_type: response
.headers
.iter()
.find(|h| h.name.eq_ignore_ascii_case("content-type"))
.map(|h| h.value.clone())
.unwrap_or_default(),
})
}
pub fn db(&self) -> ClientDb<'_> {
self.query_manager.connect()
}
-1
View File
@@ -73,7 +73,6 @@ url = "2"
tokio-util = { version = "0.7", features = ["codec"] }
ts-rs = { workspace = true }
yaak-rpc = { workspace = true }
yaak-rpc-schema = { workspace = true }
uuid = "1.12.1"
yaak-api = { workspace = true }
yaak-common = { workspace = true }
@@ -7,12 +7,10 @@ import type { AnyModel, GraphQlIntrospection, GrpcEvent, HttpRequest, HttpReques
import type { PluginMetadata } from "./gen_search";
import type { SyncOp } from "./gen_sync";
import type { BatchUpsertResult } from "./gen_util";
import type { GitWatchResult, WatchResult } from "./index";
import type { Tokens } from "./parser";
import type { ServerSentEvent } from "./sse";
/**
* What the frontend learns about the host it is talking to.
*/
export type AppMetaData = { isDev: boolean, version: string, cliVersion: string | null, name: string, appDataDir: string, appLogDir: string, vendoredPluginDir: string, defaultProjectDir: string, featureUpdater: boolean, featureLicense: boolean, };
export type CmdCallFolderActionReq = { req: CallFolderActionRequest, };
@@ -143,8 +141,6 @@ export type CmdHttpResponseBodyReq = { responseId: string, filter: string | null
export type CmdImportDataReq = { filePath: string, };
export type CmdImportUrlReq = { url: string, };
export type CmdMetadataReq = Record<string, never>;
export type CmdNewChildWindowReq = { url: string, label: string, title: string, innerSize: [number, number], };
@@ -215,21 +211,6 @@ export type CmdWsDeleteConnectionsReq = { requestId: string, };
export type CmdWsSendReq = { connectionId: string, environmentId: string | null, };
/**
* An unsaved response and its body.
*
* The body rides along because nothing stored it: there is no database row to
* look up later and no file for a host to read, so this is the caller's only
* copy.
*/
export type EphemeralHttpResponse = { response: HttpResponse, body: Array<number>, };
/**
* Returned by the two watch commands: the name of the event to emit to stop
* the watcher.
*/
export type GitWatchResult = { unlistenEvent: string, };
export type ModelsDeleteReq = { model: AnyModel, };
export type ModelsDuplicateReq = { modelType: string, modelId: string, };
@@ -248,6 +229,8 @@ export type ModelsWebsocketEventsReq = { connectionId: string, };
export type ModelsWorkspaceModelsReq = { workspaceId: string | null, };
export type RpcSchema = { cmd_metadata: [CmdMetadataReq, AppMetaData], cmd_template_tokens_to_string: [CmdTemplateTokensToStringReq, string], cmd_render_template: [CmdRenderTemplateReq, string], cmd_send_feedback: [CmdSendFeedbackReq, null], cmd_dismiss_notification: [CmdDismissNotificationReq, null], cmd_grpc_reflect: [CmdGrpcReflectReq, Array<ServiceDefinition>], cmd_grpc_go: [CmdGrpcGoReq, string], cmd_restart: [CmdRestartReq, null], cmd_send_ephemeral_request: [CmdSendEphemeralRequestReq, EphemeralHttpResponse], cmd_format_json: [CmdFormatJsonReq, string], cmd_format_graphql: [CmdFormatGraphqlReq, string], cmd_http_response_body: [CmdHttpResponseBodyReq, FilterResponse], cmd_http_response_body_path: [CmdHttpResponseBodyPathReq, string | null], cmd_http_request_body: [CmdHttpRequestBodyReq, Array<number> | null], cmd_get_sse_events: [CmdGetSseEventsReq, Array<ServerSentEvent>], cmd_get_http_response_events: [CmdGetHttpResponseEventsReq, Array<HttpResponseEvent>], cmd_import_data: [CmdImportDataReq, BatchUpsertResult], cmd_import_url: [CmdImportUrlReq, BatchUpsertResult], cmd_http_request_actions: [CmdHttpRequestActionsReq, Array<GetHttpRequestActionsResponse>], cmd_websocket_request_actions: [CmdWebsocketRequestActionsReq, Array<GetWebsocketRequestActionsResponse>], cmd_call_websocket_request_action: [CmdCallWebsocketRequestActionReq, null], cmd_workspace_actions: [CmdWorkspaceActionsReq, Array<GetWorkspaceActionsResponse>], cmd_call_workspace_action: [CmdCallWorkspaceActionReq, null], cmd_folder_actions: [CmdFolderActionsReq, Array<GetFolderActionsResponse>], cmd_call_folder_action: [CmdCallFolderActionReq, null], cmd_grpc_request_actions: [CmdGrpcRequestActionsReq, Array<GetGrpcRequestActionsResponse>], cmd_template_function_summaries: [CmdTemplateFunctionSummariesReq, Array<GetTemplateFunctionSummaryResponse>], cmd_template_function_config: [CmdTemplateFunctionConfigReq, GetTemplateFunctionConfigResponse], cmd_get_http_authentication_summaries: [CmdGetHttpAuthenticationSummariesReq, Array<GetHttpAuthenticationSummaryResponse>], cmd_get_http_authentication_config: [CmdGetHttpAuthenticationConfigReq, GetHttpAuthenticationConfigResponse], cmd_call_http_request_action: [CmdCallHttpRequestActionReq, null], cmd_call_grpc_request_action: [CmdCallGrpcRequestActionReq, null], cmd_call_http_authentication_action: [CmdCallHttpAuthenticationActionReq, null], cmd_curl_to_request: [CmdCurlToRequestReq, HttpRequest], cmd_export_data: [CmdExportDataReq, null], cmd_save_base64_to_binary: [CmdSaveBase64ToBinaryReq, null], cmd_save_response: [CmdSaveResponseReq, null], cmd_send_http_request: [CmdSendHttpRequestReq, HttpResponse], cmd_reload_plugins: [CmdReloadPluginsReq, Array<[string, string]>], cmd_plugin_info: [CmdPluginInfoReq, PluginMetadata], cmd_delete_all_grpc_connections: [CmdDeleteAllGrpcConnectionsReq, null], cmd_delete_send_history: [CmdDeleteSendHistoryReq, null], cmd_delete_all_http_responses: [CmdDeleteAllHttpResponsesReq, null], cmd_get_workspace_meta: [CmdGetWorkspaceMetaReq, WorkspaceMeta], cmd_new_child_window: [CmdNewChildWindowReq, null], cmd_new_main_window: [CmdNewMainWindowReq, null], cmd_check_for_updates: [CmdCheckForUpdatesReq, boolean], cmd_decrypt_template: [CmdDecryptTemplateReq, string], cmd_secure_template: [CmdSecureTemplateReq, string], cmd_get_themes: [CmdGetThemesReq, Array<GetThemesResponse>], cmd_enable_encryption: [CmdEnableEncryptionReq, null], cmd_reveal_workspace_key: [CmdRevealWorkspaceKeyReq, string], cmd_set_workspace_key: [CmdSetWorkspaceKeyReq, null], cmd_disable_encryption: [CmdDisableEncryptionReq, null], cmd_default_headers: [CmdDefaultHeadersReq, Array<HttpRequestHeader>], models_upsert: [ModelsUpsertReq, string], models_delete: [ModelsDeleteReq, string], models_duplicate: [ModelsDuplicateReq, string], models_websocket_events: [ModelsWebsocketEventsReq, Array<WebsocketEvent>], models_grpc_events: [ModelsGrpcEventsReq, Array<GrpcEvent>], models_get_settings: [ModelsGetSettingsReq, Settings], models_get_graphql_introspection: [ModelsGetGraphqlIntrospectionReq, GraphQlIntrospection | null], models_upsert_graphql_introspection: [ModelsUpsertGraphqlIntrospectionReq, GraphQlIntrospection], models_workspace_models: [ModelsWorkspaceModelsReq, string], cmd_git_checkout: [CmdGitCheckoutReq, string], cmd_git_branch: [CmdGitBranchReq, null], cmd_git_delete_branch: [CmdGitDeleteBranchReq, BranchDeleteResult], cmd_git_delete_remote_branch: [CmdGitDeleteRemoteBranchReq, null], cmd_git_merge_branch: [CmdGitMergeBranchReq, null], cmd_git_rename_branch: [CmdGitRenameBranchReq, null], cmd_git_status: [CmdGitStatusReq, GitStatusSummary], cmd_git_branch_info: [CmdGitBranchInfoReq, GitBranchInfo], cmd_git_worktree_status: [CmdGitWorktreeStatusReq, GitWorktreeStatus], cmd_git_log: [CmdGitLogReq, Array<GitCommit>], cmd_git_log_for_file: [CmdGitLogForFileReq, Array<GitCommit>], cmd_git_file_diff_for_commit: [CmdGitFileDiffForCommitReq, GitFileDiff], cmd_git_initialize: [CmdGitInitializeReq, nuLine truncated
export type WatchResult = { unlistenEvent: string, };
/**
* The wire schema, exported to TypeScript. Field name = command name,
* tuple = (request payload, response payload).
*/
export type RpcSchema = { cmd_metadata: [CmdMetadataReq, AppMetaData], cmd_template_tokens_to_string: [CmdTemplateTokensToStringReq, string], cmd_render_template: [CmdRenderTemplateReq, string], cmd_send_feedback: [CmdSendFeedbackReq, null], cmd_dismiss_notification: [CmdDismissNotificationReq, null], cmd_grpc_reflect: [CmdGrpcReflectReq, Array<ServiceDefinition>], cmd_grpc_go: [CmdGrpcGoReq, string], cmd_restart: [CmdRestartReq, null], cmd_send_ephemeral_request: [CmdSendEphemeralRequestReq, HttpResponse], cmd_format_json: [CmdFormatJsonReq, string], cmd_format_graphql: [CmdFormatGraphqlReq, string], cmd_http_response_body: [CmdHttpResponseBodyReq, FilterResponse], cmd_http_response_body_path: [CmdHttpResponseBodyPathReq, string | null], cmd_http_request_body: [CmdHttpRequestBodyReq, Array<number> | null], cmd_get_sse_events: [CmdGetSseEventsReq, Array<ServerSentEvent>], cmd_get_http_response_events: [CmdGetHttpResponseEventsReq, Array<HttpResponseEvent>], cmd_import_data: [CmdImportDataReq, BatchUpsertResult], cmd_http_request_actions: [CmdHttpRequestActionsReq, Array<GetHttpRequestActionsResponse>], cmd_websocket_request_actions: [CmdWebsocketRequestActionsReq, Array<GetWebsocketRequestActionsResponse>], cmd_call_websocket_request_action: [CmdCallWebsocketRequestActionReq, null], cmd_workspace_actions: [CmdWorkspaceActionsReq, Array<GetWorkspaceActionsResponse>], cmd_call_workspace_action: [CmdCallWorkspaceActionReq, null], cmd_folder_actions: [CmdFolderActionsReq, Array<GetFolderActionsResponse>], cmd_call_folder_action: [CmdCallFolderActionReq, null], cmd_grpc_request_actions: [CmdGrpcRequestActionsReq, Array<GetGrpcRequestActionsResponse>], cmd_template_function_summaries: [CmdTemplateFunctionSummariesReq, Array<GetTemplateFunctionSummaryResponse>], cmd_template_function_config: [CmdTemplateFunctionConfigReq, GetTemplateFunctionConfigResponse], cmd_get_http_authentication_summaries: [CmdGetHttpAuthenticationSummariesReq, Array<GetHttpAuthenticationSummaryResponse>], cmd_get_http_authentication_config: [CmdGetHttpAuthenticationConfigReq, GetHttpAuthenticationConfigResponse], cmd_call_http_request_action: [CmdCallHttpRequestActionReq, null], cmd_call_grpc_request_action: [CmdCallGrpcRequestActionReq, null], cmd_call_http_authentication_action: [CmdCallHttpAuthenticationActionReq, null], cmd_curl_to_request: [CmdCurlToRequestReq, HttpRequest], cmd_export_data: [CmdExportDataReq, null], cmd_save_base64_to_binary: [CmdSaveBase64ToBinaryReq, null], cmd_save_response: [CmdSaveResponseReq, null], cmd_send_http_request: [CmdSendHttpRequestReq, HttpResponse], cmd_reload_plugins: [CmdReloadPluginsReq, Array<[string, string]>], cmd_plugin_info: [CmdPluginInfoReq, PluginMetadata], cmd_delete_all_grpc_connections: [CmdDeleteAllGrpcConnectionsReq, null], cmd_delete_send_history: [CmdDeleteSendHistoryReq, null], cmd_delete_all_http_responses: [CmdDeleteAllHttpResponsesReq, null], cmd_get_workspace_meta: [CmdGetWorkspaceMetaReq, WorkspaceMeta], cmd_new_child_window: [CmdNewChildWindowReq, null], cmd_new_main_window: [CmdNewMainWindowReq, null], cmd_check_for_updates: [CmdCheckForUpdatesReq, boolean], cmd_decrypt_template: [CmdDecryptTemplateReq, string], cmd_secure_template: [CmdSecureTemplateReq, string], cmd_get_themes: [CmdGetThemesReq, Array<GetThemesResponse>], cmd_enable_encryption: [CmdEnableEncryptionReq, null], cmd_reveal_workspace_key: [CmdRevealWorkspaceKeyReq, string], cmd_set_workspace_key: [CmdSetWorkspaceKeyReq, null], cmd_disable_encryption: [CmdDisableEncryptionReq, null], cmd_default_headers: [CmdDefaultHeadersReq, Array<HttpRequestHeader>], models_upsert: [ModelsUpsertReq, string], models_delete: [ModelsDeleteReq, string], models_duplicate: [ModelsDuplicateReq, string], models_websocket_events: [ModelsWebsocketEventsReq, Array<WebsocketEvent>], models_grpc_events: [ModelsGrpcEventsReq, Array<GrpcEvent>], models_get_settings: [ModelsGetSettingsReq, Settings], models_get_graphql_introspection: [ModelsGetGraphqlIntrospectionReq, GraphQlIntrospection | null], models_upsert_graphql_introspection: [ModelsUpsertGraphqlIntrospectionReq, GraphQlIntrospection], models_workspace_models: [ModelsWorkspaceModelsReq, string], cmd_git_checkout: [CmdGitCheckoutReq, string], cmd_git_branch: [CmdGitBranchReq, null], cmd_git_delete_branch: [CmdGitDeleteBranchReq, BranchDeleteResult], cmd_git_delete_remote_branch: [CmdGitDeleteRemoteBranchReq, null], cmd_git_merge_branch: [CmdGitMergeBranchReq, null], cmd_git_rename_branch: [CmdGitRenameBranchReq, null], cmd_git_status: [CmdGitStatusReq, GitStatusSummary], cmd_git_branch_info: [CmdGitBranchInfoReq, GitBranchInfo], cmd_git_worktree_status: [CmdGitWorktreeStatusReq, GitWorktreeStatus], cmd_git_log: [CmdGitLogReq, Array<GitCommit>], cmd_git_log_for_file: [CmdGitLogForFileReq, Array<GitCommit>], cmd_git_file_diff_for_commit: [CmdGitFileDiffForCommitReq, GitFileDiff], cmd_git_initialize: [CmdGitInitializeReq, null], cmd_git_clone: [CmdGitCloneReq, CloneResult], cmd_git_commLine truncated
+4
View File
@@ -1,5 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type GitWatchResult = { unlistenEvent: string, };
export type PluginUpdateInfo = { name: string, currentVersion: string, latestVersion: string, };
export type PluginUpdateNotification = { updateCount: number, plugins: Array<PluginUpdateInfo>, };
@@ -10,6 +12,8 @@ export type UpdateResponse = { "type": "ack" } | { "type": "action", action: Upd
export type UpdateResponseAction = "install" | "skip";
export type WatchResult = { unlistenEvent: string, };
export type YaakNotification = { timestamp: string, timeout: number | null, id: string, title: string | null, message: string, color: string | null, action: YaakNotificationAction | null, };
export type YaakNotificationAction = { label: string, url: string, };
File renamed without changes.
+3 -3
View File
@@ -1,4 +1,4 @@
// ts-rs owns bindings/index.ts and rewrites it on export. What remains here
// after the RPC schema moved to @yaakapp-internal/rpc-schema is the
// desktop-only surface: updater and notification types.
// ts-rs owns bindings/index.ts and rewrites it on export, so this hand-written
// entry point is where the generated files come together.
export * from "./bindings/gen_rpc";
export * from "./bindings/index";
@@ -2,6 +2,7 @@ use crate::error::{Error, Result};
use chrono::Utc;
use log::{debug, error, warn};
use notify::Watcher;
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::sync::mpsc;
use std::time::Duration;
@@ -9,11 +10,18 @@ use tauri::{AppHandle, Listener, Runtime};
use tokio::select;
use tokio::sync::watch;
use tokio::time::sleep;
use ts_rs::TS;
use yaak_git::{GitWorktreeStatus, git_path_is_ignored, git_repository_paths, git_worktree_status};
use yaak_rpc_schema::GitWatchResult;
const GIT_STATUS_COALESCE_WINDOW: Duration = Duration::from_millis(250);
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = "index.ts")]
pub(crate) struct GitWatchResult {
unlisten_event: String,
}
pub(crate) async fn watch_git_worktree_status<R, F>(
app_handle: AppHandle<R>,
dir: &Path,
@@ -8,7 +8,7 @@ use std::sync::Arc;
use std::time::Instant;
use tauri::{AppHandle, Manager, Runtime, WebviewWindow};
use tokio::sync::watch::Receiver;
use yaak::send::{ResponseBody, SendHttpRequestWithPluginsParams, send_http_request_with_plugins};
use yaak::send::{SendHttpRequestWithPluginsParams, send_http_request_with_plugins};
use yaak_crypto::manager::EncryptionManager;
use yaak_http::manager::HttpConnectionManager;
use yaak_models::models::{CookieJar, Environment, HttpRequest, HttpResponse, HttpResponseState};
@@ -62,12 +62,6 @@ impl<R: Runtime> ResponseContext<R> {
}
}
/// What a send produced: the response, and where its body went.
pub struct SentHttpRequest {
pub response: HttpResponse,
pub body: ResponseBody,
}
pub async fn send_http_request<R: Runtime>(
window: &WebviewWindow<R>,
unrendered_request: &HttpRequest,
@@ -75,7 +69,7 @@ pub async fn send_http_request<R: Runtime>(
environment: Option<Environment>,
cookie_jar: Option<CookieJar>,
cancelled_rx: &mut Receiver<bool>,
) -> Result<SentHttpRequest> {
) -> Result<HttpResponse> {
send_http_request_with_context(
window,
unrendered_request,
@@ -96,7 +90,7 @@ pub async fn send_http_request_with_context<R: Runtime>(
cookie_jar: Option<CookieJar>,
cancelled_rx: &Receiver<bool>,
plugin_context: &PluginContext,
) -> Result<SentHttpRequest> {
) -> Result<HttpResponse> {
let app_handle = window.app_handle().clone();
let update_source = UpdateSource::from_window_label(window.label());
let mut response_ctx =
@@ -116,7 +110,7 @@ pub async fn send_http_request_with_context<R: Runtime>(
.await;
match result {
Ok(sent) => Ok(sent),
Ok(response) => Ok(response),
Err(e) => {
let error = e.to_string();
let elapsed = start.elapsed().as_millis() as i32;
@@ -129,12 +123,7 @@ pub async fn send_http_request_with_context<R: Runtime>(
}
r.error = Some(error);
});
// The send failed, so whatever body exists is the partial one
// already on disk under the response's id.
Ok(SentHttpRequest {
response: response_ctx.response().clone(),
body: ResponseBody::Stored,
})
Ok(response_ctx.response().clone())
}
}
}
@@ -147,7 +136,7 @@ async fn send_http_request_inner<R: Runtime>(
cancelled_rx: &Receiver<bool>,
plugin_context: &PluginContext,
response_ctx: &mut ResponseContext<R>,
) -> Result<SentHttpRequest> {
) -> Result<HttpResponse> {
let app_handle = window.app_handle().clone();
let plugin_manager = Arc::new((*app_handle.state::<PluginManager>()).clone());
let encryption_manager = Arc::new((*app_handle.state::<EncryptionManager>()).clone());
@@ -176,7 +165,7 @@ async fn send_http_request_inner<R: Runtime>(
.await
.map_err(|e| GenericError(e.to_string()))?;
Ok(SentHttpRequest { response: result.response, body: result.response_body })
Ok(result.response)
}
pub fn resolve_http_request<R: Runtime>(
+2 -82
View File
@@ -5,7 +5,6 @@ use std::fs::read_to_string;
use std::io::ErrorKind;
use tauri::{Manager, Runtime, WebviewWindow};
use yaak::import::{self, ImportDataParams};
use yaak_api::{ApiClientKind, yaak_api_client};
use yaak_core::WorkspaceContext;
use yaak_models::util::BatchUpsertResult;
use yaak_plugins::manager::PluginManager;
@@ -14,25 +13,10 @@ use yaak_tauri_utils::window::WorkspaceWindowTrait;
pub(crate) async fn import_data<R: Runtime>(
window: &WebviewWindow<R>,
file_path: &str,
) -> Result<BatchUpsertResult> {
let contents = read_import_file(file_path)?;
import_contents(window, &contents).await
}
pub(crate) async fn import_url<R: Runtime>(
window: &WebviewWindow<R>,
url: &str,
) -> Result<BatchUpsertResult> {
let contents = fetch_import_url(window, url).await?;
import_contents(window, &contents).await
}
async fn import_contents<R: Runtime>(
window: &WebviewWindow<R>,
contents: &str,
) -> Result<BatchUpsertResult> {
let plugin_manager = window.state::<PluginManager>();
let query_manager = window.db_manager();
let file = read_import_file(file_path)?;
let plugin_context = window.plugin_context();
let workspace_context = WorkspaceContext {
workspace_id: window.workspace_id(),
@@ -46,57 +30,11 @@ async fn import_contents<R: Runtime>(
plugin_manager: &plugin_manager,
plugin_context: &plugin_context,
workspace_context,
contents,
contents: &file,
})
.await?)
}
/// Download an importable document (OpenAPI, Postman, Insomnia, …) so it can be fed to the same
/// pipeline as a file on disk.
///
/// This uses Yaak's own API client, which follows the OS proxy but not the workspace's proxy,
/// client certificate, or certificate-validation settings. Requests are unauthenticated, so
/// specs behind auth must still be downloaded manually and imported as a file.
async fn fetch_import_url<R: Runtime>(window: &WebviewWindow<R>, url: &str) -> Result<String> {
let url = normalize_import_url(url)?;
let app_version = window.app_handle().package_info().version.to_string();
let response = yaak_api_client(ApiClientKind::App, &app_version)?
.get(&url)
// The API client defaults to JSON, but specs are just as often YAML
.header("Accept", "*/*")
.send()
.await
.map_err(|err| Error::GenericError(format!("Failed to fetch {url}: {err}")))?;
let status = response.status();
if !status.is_success() {
return Err(Error::GenericError(format!("Failed to fetch {url}: responded with {status}")));
}
response
.text()
.await
.map_err(|err| Error::GenericError(format!("Failed to read response from {url}: {err}")))
}
fn normalize_import_url(url: &str) -> Result<String> {
let url = url.trim();
if url.is_empty() {
return Err(Error::GenericError("Import URL must not be empty".to_string()));
}
if url.starts_with("http://") || url.starts_with("https://") {
return Ok(url.to_string());
}
match url.split_once("://") {
Some((scheme, _)) => {
Err(Error::GenericError(format!("Import URL must be http or https, but got {scheme}")))
}
None => Ok(format!("https://{url}")),
}
}
fn read_import_file(file_path: &str) -> Result<String> {
read_to_string(file_path).map_err(|err| {
if err.kind() == ErrorKind::InvalidData {
@@ -133,22 +71,4 @@ mod tests {
remove_file(path).expect("remove binary fixture");
}
#[test]
fn normalize_import_url_defaults_to_https() {
assert_eq!(
normalize_import_url(" example.com/openapi.yaml ").unwrap(),
"https://example.com/openapi.yaml"
);
assert_eq!(
normalize_import_url("http://example.com/openapi.yaml").unwrap(),
"http://example.com/openapi.yaml"
);
}
#[test]
fn normalize_import_url_rejects_other_schemes() {
assert!(normalize_import_url("file:///tmp/openapi.yaml").is_err());
assert!(normalize_import_url(" ").is_err());
}
}
+51 -44
View File
@@ -4,7 +4,7 @@ use crate::error::Error::GenericError;
use crate::error::Result;
use crate::grpc::{build_metadata, metadata_to_map, resolve_grpc_request};
use crate::http_request::{resolve_http_request, send_http_request};
use crate::import::{import_data, import_url};
use crate::import::import_data;
use crate::models_ext::{BlobManagerExt, QueryManagerExt};
use crate::notifications::YaakNotifier;
use crate::render::{render_grpc_request, render_json_value, render_template};
@@ -30,7 +30,7 @@ use tokio::sync::Mutex;
use tokio::task::block_in_place;
use tokio::time;
use yaak::export::{self, ExportDataParams};
use yaak::send::ResponseBody;
use yaak::responses::{is_response_id, response_body_path};
use yaak_common::command::new_checked_command;
use yaak_crypto::manager::EncryptionManager;
use yaak_grpc::manager::{GrpcConfig, GrpcHandle};
@@ -56,7 +56,6 @@ use yaak_plugins::events::{
use yaak_plugins::manager::PluginManager;
use yaak_plugins::plugin_meta::{PluginMetadata, get_plugin_meta};
use yaak_plugins::template_callback::PluginTemplateCallback;
use yaak_rpc_schema::{AppMetaData, EphemeralHttpResponse};
use yaak_sse::sse::ServerSentEvent;
use yaak_tauri_utils::window::WorkspaceWindowTrait;
use yaak_templates::format_json::format_json;
@@ -184,6 +183,22 @@ impl<R: Runtime> PluginContextExt<R> for WebviewWindow<R> {
}
}
#[derive(serde::Serialize, ts_rs::TS)]
#[serde(default, rename_all = "camelCase")]
#[ts(export, export_to = "gen_rpc.ts")]
pub struct AppMetaData {
is_dev: bool,
version: String,
cli_version: Option<String>,
name: String,
app_data_dir: String,
app_log_dir: String,
vendored_plugin_dir: String,
default_project_dir: String,
feature_updater: bool,
feature_license: bool,
}
async fn cmd_metadata<R: Runtime>(app_handle: AppHandle<R>) -> YaakResult<AppMetaData> {
let app_data_dir = app_handle.path().app_data_dir()?;
let app_log_dir = app_handle.path().app_log_dir()?;
@@ -967,18 +982,13 @@ async fn cmd_restart<R: Runtime>(app_handle: AppHandle<R>) -> YaakResult<()> {
Ok(())
}
/// Send without saving anything.
///
/// The response never reaches the database, so its body cannot be read back by
/// id later the way a saved response's can. It comes back here instead, which
/// is the only copy the caller gets.
async fn cmd_send_ephemeral_request<R: Runtime>(
mut request: HttpRequest,
environment_id: Option<&str>,
cookie_jar_id: Option<&str>,
window: WebviewWindow<R>,
app_handle: AppHandle<R>,
) -> YaakResult<EphemeralHttpResponse> {
) -> YaakResult<HttpResponse> {
let response = HttpResponse::default();
request.id = "".to_string();
let environment = match environment_id {
@@ -997,18 +1007,7 @@ async fn cmd_send_ephemeral_request<R: Runtime>(
}
});
let sent =
send_http_request(&window, &request, &response, environment, cookie_jar, &mut cancel_rx)
.await?;
// Blanking the request id above is what makes this send unsaved, so the
// engine always hands the body back. Failing loudly beats returning an
// empty body that reads as "the server sent nothing".
let ResponseBody::Returned(body) = sent.body else {
return Err(GenericError("Unsaved response did not return a body".to_string()));
};
Ok(EphemeralHttpResponse { response: sent.response, body })
send_http_request(&window, &request, &response, environment, cookie_jar, &mut cancel_rx).await
}
async fn cmd_format_json(text: &str) -> YaakResult<String> {
@@ -1026,31 +1025,46 @@ async fn cmd_format_graphql(text: &str) -> YaakResult<String> {
struct ResponseBodyLocation {
/// None when the response has no stored body.
path: Option<PathBuf>,
/// The response's declared `Content-Type`, empty when it has none.
/// The response's declared `Content-Type`, empty when it has none. An
/// ephemeral response has no headers to consult, so its body decodes as
/// UTF-8.
content_type: String,
}
/// Find a response's body from its id alone.
///
/// The frontend hands back an id and never a path, so the only bodies reachable
/// here are ones the engine wrote and the database still knows about. A
/// response that was never saved has no entry, and its body came back from the
/// send that made it.
/// The frontend hands back an id and never a path, so nothing a caller says can
/// point this at a file the engine didn't write. Persisted responses carry the
/// path they were written to; ephemeral ones (GraphQL introspection) never
/// reach the database, but their body still lands at `<response dir>/<id>`,
/// which is how [`yaak::send`] builds the path in the first place.
fn locate_response_body<R: Runtime>(
app_handle: &AppHandle<R>,
response_id: &str,
) -> YaakResult<ResponseBodyLocation> {
let response = app_handle.db().get_http_response(response_id)?;
if !is_response_id(response_id) {
return Err(GenericError(format!("Invalid response ID {response_id}")));
}
Ok(ResponseBodyLocation {
path: response.body_path.map(PathBuf::from),
content_type: response
.headers
.iter()
.find(|h| h.name.eq_ignore_ascii_case("content-type"))
.map(|h| h.value.clone())
.unwrap_or_default(),
})
match app_handle.db().get_http_response(response_id) {
Ok(response) => Ok(ResponseBodyLocation {
path: response.body_path.map(PathBuf::from),
content_type: response
.headers
.iter()
.find(|h| h.name.eq_ignore_ascii_case("content-type"))
.map(|h| h.value.clone())
.unwrap_or_default(),
}),
Err(yaak_models::error::Error::ModelNotFound(_)) => {
let response_dir = app_handle.path().app_data_dir()?.join("responses");
Ok(ResponseBodyLocation {
path: Some(response_body_path(&response_dir, response_id)),
content_type: String::new(),
})
}
Err(e) => Err(e.into()),
}
}
async fn cmd_http_response_body<R: Runtime>(
@@ -1149,13 +1163,6 @@ async fn cmd_import_data<R: Runtime>(
import_data(&window, file_path).await
}
async fn cmd_import_url<R: Runtime>(
window: WebviewWindow<R>,
url: &str,
) -> YaakResult<BatchUpsertResult> {
import_url(&window, url).await
}
async fn cmd_http_request_actions<R: Runtime>(
window: WebviewWindow<R>,
plugin_manager: State<'_, PluginManager>,
@@ -1540,7 +1547,7 @@ async fn cmd_send_http_request<R: Runtime>(
)
.await
{
Ok(sent) => sent.response,
Ok(r) => r,
Err(e) => {
let resp = app_handle.db().get_http_response(&response.id)?;
app_handle.db().upsert_http_response(
@@ -314,7 +314,7 @@ async fn handle_host_plugin_request<R: Runtime>(
.await?;
Ok(Some(InternalEventPayload::SendHttpRequestResponse(SendHttpRequestResponse {
http_response: http_response.response,
http_response,
})))
}
HostRequest::OpenWindow(req) => {
File diff suppressed because it is too large. Load diff
+9 -1
View File
@@ -6,10 +6,11 @@ use crate::error::Result;
use crate::models_ext::{BlobManagerExt, QueryManagerExt};
use chrono::Utc;
use log::warn;
use serde::{Deserialize, Serialize};
use std::path::Path;
use tauri::{AppHandle, Listener, Runtime};
use tokio::sync::watch;
use yaak_rpc_schema::WatchResult;
use ts_rs::TS;
use yaak_sync::error::Error::InvalidSyncDirectory;
use yaak_sync::sync::{
FsCandidate, SyncOp, apply_sync_ops, apply_sync_state_ops, compute_sync_ops, get_db_candidates,
@@ -56,6 +57,13 @@ pub(crate) async fn cmd_sync_apply<R: Runtime>(
Ok(())
}
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = "index.ts")]
pub(crate) struct WatchResult {
unlisten_event: String,
}
pub(crate) async fn sync_watch<R, F>(
app_handle: AppHandle<R>,
sync_dir: &Path,
-18
View File
@@ -1,18 +0,0 @@
[package]
name = "yaak-rpc-schema"
version = "0.0.0"
edition = "2024"
authors = ["Gregory Schier"]
publish = false
[dependencies]
serde = { workspace = true, features = ["derive"] }
ts-rs = { workspace = true }
yaak-git = { workspace = true }
yaak-grpc = { workspace = true }
yaak-models = { workspace = true }
yaak-plugins = { workspace = true }
yaak-sse = { workspace = true }
yaak-sync = { workspace = true }
yaak-templates = { workspace = true }
yaak-ws = { workspace = true }
-44
View File
@@ -1,44 +0,0 @@
# yaak-rpc-schema
The wire schema for the app's RPC surface: every command name, its request
payload, and its response type, declared once.
Every host that serves the Yaak UI — the desktop app today, the browser bridge
and anything after it — imports these types and implements the commands against
them. That is what keeps a request's shape from drifting between hosts, and it
is why the TypeScript bindings (`bindings/gen_rpc.ts`, exposed to the frontend
as `@yaakapp-internal/rpc-schema`) are generated from one place.
Nothing here depends on Tauri or on any host. Request structs are plain data,
and so are the few response types declared here rather than in an engine crate.
Command *bodies* live with the host that runs them.
## Adding a command
1. Add its request struct and an entry in `with_commands!` in `src/lib.rs`.
2. Write the adapter in each host — the desktop's live in
`crates-tauri/yaak-app-client/src/rpc_ext.rs`. A host that does not support
the command still has to say so; a missing adapter fails to compile.
3. Regenerate the bindings: `cargo test -p yaak-rpc-schema` writes
`bindings/gen_rpc.ts`, which is committed.
## How hosts consume the list
`with_commands!` takes the name of a `macro_rules!` macro and calls it with the
full `name(Req) -> Res` list. Each host writes a small macro that receives that
list and builds its router:
```rust
macro_rules! register_commands {
( $( $name:ident ( $req:ty ) -> $res:ty ),* $(,)? ) => {
pub fn build_router() -> RpcRouter<MyCtx> {
let mut router = RpcRouter::new();
$( router.register(stringify!($name), rpc_handler_async!($name)); )*
router
}
};
}
yaak_rpc_schema::with_commands!(register_commands);
```
The schema decides *what* commands exist; the host decides *how* each one runs.
-4
View File
@@ -1,4 +0,0 @@
// The RPC wire schema, generated by ts-rs from the Rust declarations in
// src/lib.rs. `RpcSchema` maps every command name to its (request, response)
// pair; the app's `rpc()` helper derives its command union from it.
export * from "./bindings/gen_rpc";
@@ -1,6 +0,0 @@
{
"name": "@yaakapp-internal/rpc-schema",
"version": "1.0.0",
"private": true,
"main": "index.ts"
}
File diff suppressed because it is too large. Load diff
+4 -4
View File
@@ -593,7 +593,7 @@ impl UpsertModelInfo for WorkspaceMeta {
}
}
#[derive(Debug, Clone, Serialize, Deserialize, TS, PartialEq)]
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[ts(export, export_to = "gen_models.ts")]
pub enum CookieDomain {
HostOnly(String),
@@ -602,14 +602,14 @@ pub enum CookieDomain {
Empty,
}
#[derive(Debug, Clone, Serialize, Deserialize, TS, PartialEq)]
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[ts(export, export_to = "gen_models.ts")]
pub enum CookieExpires {
AtUtc(String),
SessionEnd,
}
#[derive(Debug, Clone, Serialize, Deserialize, TS, PartialEq)]
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[ts(export, export_to = "gen_models.ts")]
pub enum CookieSameSite {
Strict,
@@ -617,7 +617,7 @@ pub enum CookieSameSite {
None,
}
#[derive(Debug, Clone, Serialize, TS, PartialEq)]
#[derive(Debug, Clone, Serialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = "gen_models.ts")]
pub struct Cookie {
+1 -1
View File
@@ -1,5 +1,5 @@
import { platform } from "@yaakapp-internal/platform";
import type { WatchResult } from "@yaakapp-internal/rpc-schema";
import type { WatchResult } from "@yaakapp-internal/tauri-client";
import { SyncOp } from "./bindings/gen_sync";
import { WatchEvent } from "./bindings/gen_watch";
-1
View File
@@ -21,4 +21,3 @@ yaak-tls = { workspace = true }
[dev-dependencies]
tempfile = "3"
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
+1
View File
@@ -4,6 +4,7 @@ pub mod import;
pub mod models_ops;
pub mod plugin_events;
pub mod render;
pub mod responses;
pub mod send;
pub use error::Error;
+53
View File
@@ -0,0 +1,53 @@
//! Where response bodies live, from a response id alone.
//!
//! [`send`](crate::send) writes each body to `<response dir>/<response id>`,
//! and every reader has to find it again knowing only the id: commands take an
//! id from the client and never a path, so a path the client chose can never be
//! opened. [`is_response_id`] is the check that makes joining a client-supplied
//! id onto the response directory safe.
use std::path::{Path, PathBuf};
/// The file a response's body is written to, and therefore read back from.
pub fn response_body_path(response_dir: &Path, response_id: &str) -> PathBuf {
response_dir.join(response_id)
}
/// Whether a string is shaped like a response id, and can therefore be joined
/// onto the response directory without escaping it.
///
/// Ids are `rs_<hex>`. Rejecting anything else outright, rather than trying to
/// sanitize it, is what keeps "read the body of response X" from naming a file
/// of the caller's choosing: no separators, no `..`, no absolute paths, no
/// drive letters, no NUL.
pub fn is_response_id(id: &str) -> bool {
!id.is_empty() && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_generated_ids() {
assert!(is_response_id("rs_A1b2C3d4"));
assert!(is_response_id("rs_with-dash"));
}
#[test]
fn rejects_anything_that_could_escape_the_directory() {
for id in [
"",
"..",
"../../etc/passwd",
"rs_1/../../secret",
"/etc/passwd",
r"C:\Windows\System32",
r"rs_1\..\secret",
"rs_1.txt",
"rs_1\0",
] {
assert!(!is_response_id(id), "{id:?} should be rejected");
}
}
}
+214 -588
View File
File diff suppressed because it is too large. Load diff
-1
View File
@@ -58,7 +58,6 @@
"crates-tauri/yaak-fonts",
"crates-tauri/yaak-license",
"crates-tauri/yaak-mac-window",
"crates/common/yaak-rpc-schema",
"crates/yaak-crypto",
"crates/yaak-git",
"crates/yaak-models",
+20 -16
View File
@@ -62,6 +62,16 @@ function detectOsType(): OsType {
return "linux";
}
/**
* The route that serves a response body, keyed by the response id.
*
* The bridge resolves the id against its own database, so this is the only
* thing the page ever has to know about where a body lives.
*/
function responseBodyRoute(responseId: string): string {
return `/responses/${encodeURIComponent(responseId)}/body`;
}
/**
* Answer the Tauri host-plugin commands, which ride outside the RPC envelope.
*
@@ -213,23 +223,19 @@ export function createBridgePlatform(baseUrl: string, token: string | null): Pla
readDir: async () => {
throw unsupported("Browsing the filesystem");
},
// Only ever called with a path this host handed out, and this host has
// no dialog or drag-drop to hand one out with.
readText: async () => {
throw unsupported("Reading a local file");
},
// No filesystem here, so a path is just a string this host echoes back.
// App resources are served by the page's own origin, so the path the
// caller resolved is already a URL a tab can load.
url: (path) => path,
basename: async (path) => path.split(/[/\\]/).pop() ?? path,
resolveResource: async (path) => path,
},
// Bodies live on the bridge's disk and are addressed by response id. The
// server resolves the id through its database, so a page can only ever
// reach a body the engine actually wrote.
blobs: {
async read(id) {
const res = await connection.fetch(`/responses/${encodeURIComponent(id)}/body`);
// The route takes the response id and looks the body up itself, so the
// page never names a file — the same reason the desktop asks the backend
// for the path instead of building one.
async readResponseBody(responseId) {
const res = await connection.fetch(responseBodyRoute(responseId));
if (res.status === 404) return null;
if (!res.ok) {
throw new Error(`Failed to read response body (${res.status})`);
@@ -240,9 +246,7 @@ export function createBridgePlatform(baseUrl: string, token: string | null): Pla
// The `<img src>`/`<video src>` equivalent of Tauri's `convertFileSrc`.
// The token rides in the query because the browser makes these requests
// itself and the page cannot add a header to them.
async url(id) {
return connection.url(`/responses/${encodeURIComponent(id)}/body`);
},
responseBodyUrl: async (responseId) => connection.url(responseBodyRoute(responseId)),
},
rpc: <T,>(cmd: string, payload?: RpcPayload): Promise<T> => {
+7 -5
View File
@@ -20,16 +20,18 @@ declare global {
interface Window {
__TAURI_INTERNALS__?: unknown;
}
// Declared here rather than by depending on Vite's types: this package is
// consumed by a bundler that provides them, and only this one variable.
interface ImportMeta {
readonly env?: Record<string, string | undefined>;
}
}
function bridgeUrl(): string {
// Set when the frontend runs on a Vite dev server and the bridge is on its
// own port. When the bridge serves the built app, they share an origin.
// Vite inlines `import.meta.env` at build time. Read it through a cast so
// this package typechecks on its own without depending on Vite's types, and
// still picks up the real declaration when the app compiles it.
const env = (import.meta as { env?: Record<string, string | undefined> }).env;
const configured = env?.VITE_YAAK_BRIDGE_URL;
const configured = import.meta.env?.VITE_YAAK_BRIDGE_URL;
return (configured ?? window.location.origin).replace(/\/$/, "");
}
-3
View File
@@ -49,9 +49,6 @@ export const platform: Platform = {
get files() {
return host().files;
},
get blobs() {
return host().blobs;
},
rpc: (cmd, payload) => host().rpc(cmd, payload),
rpcStream: (cmd, payload, onMessage) => host().rpcStream(cmd, payload, onMessage),
listen: (event, callback) => host().listen(event, callback),
+11 -15
View File
@@ -5,7 +5,7 @@ import { basename, resolveResource } from "@tauri-apps/api/path";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { clear, readText, writeText } from "@tauri-apps/plugin-clipboard-manager";
import { open, save } from "@tauri-apps/plugin-dialog";
import { readDir, readFile, readTextFile } from "@tauri-apps/plugin-fs";
import { readDir, readFile } from "@tauri-apps/plugin-fs";
import { openUrl, revealItemInDir } from "@tauri-apps/plugin-opener";
import { type as osType } from "@tauri-apps/plugin-os";
import type {
@@ -105,15 +105,14 @@ async function rpc<T>(cmd: string, payload?: RpcPayload): Promise<T> {
}
/**
* Where this host keeps the bytes stored under an id, or null if it has none.
* Where the backend put a response's body, or null if it has none.
*
* The desktop stores them as files the engine wrote, so answering means asking
* the backend. Callers hold ids and nothing else; the path exists for exactly
* as long as it takes to open the file, which is the one thing a desktop host
* can do that a tab cannot.
* The app holds response ids and nothing else; a path exists for exactly as
* long as it takes this host to open the file, which is the one thing a desktop
* host can do that a tab cannot.
*/
function storedBodyPath(id: string): Promise<string | null> {
return rpc<string | null>("cmd_http_response_body_path", { responseId: id });
function responseBodyPath(responseId: string): Promise<string | null> {
return rpc<string | null>("cmd_http_response_body_path", { responseId });
}
export function createTauriPlatform(): Platform {
@@ -137,20 +136,17 @@ export function createTauriPlatform(): Platform {
files: {
readDir: (path) => readDir(path),
readText: (path) => readTextFile(path),
url: (path) => convertFileSrc(path),
basename: (path) => basename(path),
resolveResource: (path) => resolveResource(path),
},
blobs: {
async read(id) {
const path = await storedBodyPath(id);
async readResponseBody(responseId) {
const path = await responseBodyPath(responseId);
return path == null ? null : readFile(path);
},
async url(id) {
const path = await storedBodyPath(id);
async responseBodyUrl(responseId) {
const path = await responseBodyPath(responseId);
return path == null ? null : convertFileSrc(path);
},
},
+13 -30
View File
@@ -137,19 +137,15 @@ export interface PlatformDialog {
* A path here is an opaque handle, not something to parse or construct: the UI
* only ever passes one back to `url` or `readDir`. A host without a filesystem
* can mint handles of its own (a blob id, a URL) and stay compatible.
*
* Response bodies are addressed by response id instead, because they are the
* one thing every host stores somewhere different. The desktop reads the file
* the engine wrote; the bridge fetches it over HTTP. Neither is ever handed a
* location the page chose.
*/
export interface PlatformFiles {
readDir(path: string): Promise<DirEntry[]>;
/**
* The text of a file the user picked, decoded as UTF-8.
*
* Only for paths the host itself handed us — a dialog result or a drag-drop
* payload — never one the page assembled. A host without a filesystem reads
* whatever its own handle points at.
*/
readText(path: string): Promise<string>;
/** A URL the page can load a file from, for `<img>`, `<video>`, and friends. */
url(path: string): string;
@@ -157,31 +153,19 @@ export interface PlatformFiles {
/** Resolve a path bundled with the app itself, rather than one from the backend. */
resolveResource(path: string): Promise<string>;
}
/**
* Content the backend stored, addressed by the id it stored it under.
*
* Where those bytes actually live is the one thing every host answers
* differently — a file the engine wrote, a row in a database, a URL on the
* other end of a socket — so finding them is the host's job and nobody else's.
* The caller passes an id and never a location, which is also what keeps a page
* from naming something the backend never wrote.
*
* What the content *means* is the app's business, not this package's.
*/
export interface PlatformBlobs {
/** The bytes, or null if the host has nothing stored under that id. */
read(id: string): Promise<Uint8Array<ArrayBuffer> | null>;
/** The bytes of a stored response body, or null if the response has none. */
readResponseBody(responseId: string): Promise<Uint8Array<ArrayBuffer> | null>;
/**
* A URL an element can load the content from, for `<img>`, `<video>` and
* friends, or null if the host has nothing stored under that id.
* A URL the media viewers can point an element at, or null if the response
* has no stored body.
*
* Asynchronous because the host may have to ask its backend where the bytes
* are, and it only does that the moment before it reads them.
* Asynchronous because the host may have to ask the backend where the body
* is: only the host is allowed to know that, and only the moment before it
* opens it.
*/
url(id: string): Promise<string | null>;
responseBodyUrl(responseId: string): Promise<string | null>;
}
export interface Platform {
@@ -190,7 +174,6 @@ export interface Platform {
readonly clipboard: PlatformClipboard;
readonly dialog: PlatformDialog;
readonly files: PlatformFiles;
readonly blobs: PlatformBlobs;
/** Call a backend command and await its result. */
rpc<T>(cmd: string, payload?: RpcPayload): Promise<T>;