@chia1104/motoko-client
Motoko from the browser: a session's view folded from its events and resumed by cursor, and the calls, over a WebSocket to a Durable Object or HTTP and server-sent events to a Node server.
Motoko from the browser: one client over every transport. It follows sessions, folding each one's
wire events into a session view with @chia1104/motoko-wire's applyEvent, resumes each
from its last cursor when its connection drops, and makes the calls an app needs. The same client,
and the same app code, runs over either transport:
webSocketTransport(socket): a WebSocket to a Durable Object that serves Motoko's socket protocol,@chia1104/motoko-cloudflare'sMotokoCapability, over the Agents SDK'sAgentClient, the socketuseAgentreturns, or any WebSocket.httpTransport({ baseUrl }): HTTP and server-sent events to a server that mountsmotokoHandlerof@chia1104/motoko-node/http, on Node, Bun, Deno or any other Fetch runtime, or to the app's own routes (paths).
It imports nothing but @chia1104/motoko-wire (and React, for /react): no server, Agents SDK, pi
or Node code. React ^19 is an optional peer, for the hook alone. It re-exports the view's types and
the helpers a UI reads it with (wire's view), so a browser app imports from the
client alone.
pnpm add @chia1104/motoko-clientUsage
// Without React, over HTTP: a page beside a Node server that mounts motokoHandler at /motoko.
import { httpTransport, motokoClient } from "@chia1104/motoko-client";
import type { MotokoSessionState } from "@chia1104/motoko-client";
declare function render(state: MotokoSessionState): void;
/** The app's own sign-in: a short-lived token, refreshed as it expires. */
declare function accessToken(): Promise<string>;
const motoko = motokoClient(
httpTransport({
baseUrl: "/motoko",
// Asked again for each request, a follow's reconnects too, so each carries a fresh token.
headers: async () => ({ authorization: `Bearer ${await accessToken()}` }),
}),
);
const { id } = await motoko.createSession();
const unfollow = motoko.follow(id, render);
await motoko.submit(id, { text: "Note that the milk is out.", requestId: crypto.randomUUID() });
// …and once the page is done with the session:
unfollow();Over a socket to a Durable Object, only the transport changes:
motokoClient(webSocketTransport(agent)), with agent the Agents SDK's AgentClient or the socket
useAgent returns (see @chia1104/motoko-cloudflare).
With React, a component takes the client and does not care which transport it has:
// With React: a session's view and its calls, the same over either transport. The app makes its client once.
import { useState } from "react";
import type { MotokoClient } from "@chia1104/motoko-client";
import { useMotokoSession } from "@chia1104/motoko-client/react";
export function Session({ client, sessionId }: { readonly client: MotokoClient; readonly sessionId: string }) {
const { view, status, submit, decide } = useMotokoSession(client, sessionId);
const [draft, setDraft] = useState("");
return (
<section>
{status === "connecting" && <p>Connecting…</p>}
{status === "ended" && <p>This session is gone.</p>}
{view.items.map((item) => {
if (item.kind === "user" || item.kind === "assistant") return <p key={item.messageId}>{item.text}</p>;
if (item.kind !== "tool" || !view.pendingApprovals.includes(item.toolCallId)) return null;
return (
<p key={item.toolCallId}>
{item.label}
<button onClick={() => void decide([{ toolCallId: item.toolCallId, approved: true }])}>Allow</button>
<button onClick={() => void decide([{ toolCallId: item.toolCallId, approved: false }])}>Deny</button>
</p>
);
})}
<form
onSubmit={(event) => {
event.preventDefault();
void submit(draft);
setDraft("");
}}
>
<input value={draft} onChange={(event) => setDraft(event.target.value)} />
</form>
</section>
);
}(examples/, typechecked with the DOM's globals by their own tsconfig.json.)