Functions

Call server code from the client by name, with input and output types inferred from Zod schemas. Every call goes through one POST /api/functions endpoint, and Zod only runs on the server, so it never reaches the client bundle.

+page.svelte
<script lang="ts">
	import { useFunc } from "#lib/functions/index.js";

	const response = await useFunc("userCreate", { email: "[email protected]" });
	// If the call failed: data holds the error message.
	if (response.error) console.error(response.data);
	else console.log(response.data);
</script>

Installation

pnx remote0 add https://plainsv.com/r/functions.json

Files

The utility lives in src/lib/functions. The schemas.ts file defines each function's input and output, handlers holds the server code, server.ts exports the POST handler, and index.ts exports useFunc for the client.

src/routes/api/functions/+server.ts
export { POST } from "#lib/functions/server.js";

Define a schema

Add an entry to functionsSchemas with an in schema, an out schema, and isPublic. The key is the function name used by the client and the handler.

src/lib/functions/schemas.ts
export const functionsSchemas = {
	userCreate: {
		in: z.object({ email: z.email() }),
		out: z.string(),
		isPublic: true,
	},
};

Write a handler

Export a handler with the same name from any file in src/lib/functions/handlers. Every exported function in that folder is registered automatically. Type it with FuncHandler to get typed inputData and the full request event, and return an object with error and data.

src/lib/functions/handlers/demo.ts
import type { FuncHandler } from "../schemas";

/** Create user */
export const userCreate: FuncHandler<"userCreate"> = async ({ event, inputData }) => {
	return { error: false, data: `User with email ${inputData.email} created.` };
};

Calling and validation

useFunc takes the function name and its input, and resolves to a response with error and data. It never throws, and network errors resolve with error: true. The server validates the input against in and a successful output against out, and returns the Zod issues as an error message when either fails. Clear the email below to see a validation error.

+page.svelte
const response = await useFunc("userCreate", { email }, false);

Pass false as the third argument to wait at least 300 milliseconds before resolving, so loading states do not flash on fast responses.

Private functions

Set isPublic: false to only allow calls when event.locals.userData is set, such as after your auth hook signs a user in. Other calls get an error response.

src/lib/functions/schemas.ts
userDeletePrivate: {
	in: z.object({ email: z.email() }),
	out: z.string(),
	isPublic: false,
},

Form data

Use a z.custom schema for FormData input, and pass a FormData object to useFunc. The request is sent as multipart form data instead of JSON.

src/lib/functions/schemas.ts
fileUpload: {
	in: z.custom<FormData>((value) => value instanceof FormData),
	out: z.object({ name: z.string(), size: z.number(), type: z.string() }),
	isPublic: true,
},
+page.svelte
const formData = new FormData();
formData.append("file", file);
const response = await useFunc("fileUpload", formData);

Streaming

Return a Response with the text/event-stream content type to stream. On the client, data becomes an async generator that yields the payload of each data: event, parsed as JSON when it is valid JSON. Stopping the loop early closes the connection.

src/lib/functions/handlers/demo.ts
/** Stream a reply one word at a time */
export const textStream: FuncHandler<"textStream"> = async ({ inputData }) => {
	const words = `You said "${inputData.prompt}".`.split(" ");
	const encoder = new TextEncoder();
	const stream = new ReadableStream({
		async start(controller) {
			for (const word of words) controller.enqueue(encoder.encode(`data: ${JSON.stringify(`${word} `)}\n\n`));
			controller.close();
		},
	});
	return new Response(stream, { headers: { "content-type": "text/event-stream" } });
};
+page.svelte
const response = await useFunc("textStream", { prompt });
if (!response.error) for await (const word of response.data) text += word;

Any other Response returned from a handler is sent as it is, without output validation.

Live streams

Return an async generator as data to stream typed values without building the stream yourself. The server sends each yielded value as a server-sent event, keeps Date values as dates, and sends an error the generator throws as an error event. Type the output with z.custom<AsyncGenerator<T>>(), where T is the type of each value.

Disconnected
src/lib/functions/schemas.ts
liveTicker: {
	in: z.object({ throwError: z.boolean().optional() }),
	out: z.custom<AsyncGenerator<{ count: number; price: number; time: Date }>>(() => true),
	isPublic: true,
},
src/lib/functions/handlers/demo.ts
/** Stream a random price every second, like a live ticker */
export const liveTicker: FuncHandler<"liveTicker"> = async ({ event, inputData }) => {
	async function* ticker() {
		let price = 100;
		for (let count = 1; count <= 60; count++) {
			if (inputData.throwError && count === 3) throw new Error("Ticker failed on purpose.");
			price = Math.round((price + (Math.random() - 0.5) * 2) * 100) / 100;
			yield { count, price, time: new Date() };
			await new Promise((resolve) => setTimeout(resolve, 1000));
		}
	}
	return { error: false, data: ticker() };
};

Read it with useFuncLive, which works like a SvelteKit query.live. It connects when the markup or an effect first reads it and disconnects when the component is destroyed, and components that read the same instance share one connection. current keeps the useFunc response shape: &#123; error: false, data &#125; with the latest value, &#123; error: true, data &#125; with the error message, or undefined before the first event.

+page.svelte
<script lang="ts">
	import { useFuncLive } from "#lib/functions/index.js";

	let throwError = $state(false);
	// Recreate the stream when its input changes
	const ticker = $derived(useFuncLive("liveTicker", { throwError }));

	// Run code for every event or error, removing the callback when the effect reruns
	$effect(() => ticker.onEvent((data) => console.log(data.price)));
	$effect(() => ticker.onError((message) => console.error(message)));
</script>

{#if ticker.current?.error}
	<p>{ticker.current.data}</p>
{:else if ticker.current}
	<p>{ticker.current.data.price} at {ticker.current.data.time.toLocaleTimeString()}</p>
{/if}
<p>{ticker.connected ? "Connected" : "Disconnected"}</p>
<button onclick={() => ticker.reconnect()}>Reconnect</button>
<button onclick={() => ticker.disconnect()}>Disconnect</button>

Use onEvent instead of an effect on current when every value matters, since Svelte batches updates and an effect can skip values that arrive close together. Both callbacks also open the stream when called inside an effect, even when nothing else reads it.

A generator stops at its next yield after the client disconnects. When it waits a long time between values, such as on a database change stream, close the resource from event.request.signal so it stops right away.

src/lib/functions/handlers/demo.ts
const changeStream = db.watchPostById(inputData.id);
// Close the change stream as soon as the client disconnects
event.request.signal.addEventListener("abort", () => changeStream.close());

API

src/lib/functions/index.ts
/** Calls a server function by name and resolves to its typed response */
function useFunc<K extends keyof FuncSchemas>(functionName: K, apiLoad: FuncSchemas[K]["in"], skipSleepTime?: boolean, signal?: AbortSignal): Promise<FuncSchemas[K]["out"]>;

/** Reads a function that returns an async generator as live state */
function useFuncLive<K extends FuncStreamName>(functionName: K, apiLoad: FuncSchemas[K]["in"]): FuncLive<K>;

/** Live stream returned by `useFuncLive` */
class FuncLive<K extends FuncStreamName> {
	/** Latest response, or undefined before the first event */
	get current(): { error: true; data: string } | { error: false; data: FuncStreamItem<K> } | undefined;
	/** Whether the stream is open */
	get connected(): boolean;
	/** Close the current stream and open a new one */
	reconnect(): void;
	/** Close the current stream, keeping the last value */
	disconnect(): void;
	/** Run a callback for every value, and return a function that removes it */
	onEvent(callback: (data: FuncStreamItem<K>) => void): () => void;
	/** Run a callback with the message when the call or stream fails, and return a function that removes it */
	onError(callback: (message: string) => void): () => void;
}
src/lib/functions/schemas.ts
/** Function response type */
type FuncResponse<K extends keyof FuncSchemas> = { error: true; data: string } | { error: false; data: z.infer<(typeof functionsSchemas)[K]["out"]> };

/** Type helper to create function handlers */
type FuncHandler<K extends keyof FuncSchemas> = (props: { event: RequestEvent; inputData: FuncSchemas[K]["in"] }) => FuncSchemas[K]["out"] | Promise<FuncSchemas[K]["out"]> | Response | Promise<Response>;