Calling actors from plain TypeScript
@akterjs/sdk calls actors from TypeScript code that does not use Effect. Calls return Promises, subscriptions take observer callbacks, and any Standard Schema library types the values. Actors stay written in @akterjs/effect, and the SDK speaks the same /rpc protocol as @akterjs/client.
The examples on this page call one Counter actor:
import { Schema } from "effect"
import { Akter } from "@akterjs/effect/contract"
export const User = Akter.caller("user", Schema.Struct({ id: Akter.PrincipalId }))
export const Counting = Schema.TaggedStruct("Counting", { count: Schema.Int })
export const Paused = Schema.TaggedStruct("Paused", { count: Schema.Int })
export class PausedError extends Schema.TaggedError<PausedError, { readonly brand: unique symbol }>()(
"PausedError",
{ count: Schema.Int },
) {}
export const Counter = Akter.make("Counter", {
callers: [User],
commands: {
add: Akter.command({
callers: [User],
errors: [PausedError],
from: [Counting, Paused],
input: Schema.Struct({ by: Schema.Int }),
output: Schema.Int,
to: [Counting, Paused],
}),
pause: Akter.command({
callers: [User],
errors: [],
from: [Counting],
input: Schema.Void,
output: Schema.Void,
to: [Paused],
}),
},
initial: { input: Schema.Struct({ start: Schema.Int }), to: Counting },
key: Schema.String,
parent: Akter.Root,
queries: {
count: Akter.query({
callers: [User],
errors: [],
input: Schema.Void,
output: Schema.Int,
states: [Counting, Paused],
}),
},
states: [Counting, Paused],
tables: [],
})Publish the contracts as JSON
The SDK reads an app’s published contracts, the JSON that recordedContracts builds from the actors. A frontend in the app’s repository imports contracts from the module below. A frontend in another repository imports the JSON file instead.
To write the published contracts to akter.contracts.json, run a script like this one in the app:
import { Effect } from "effect"
import { recordedContracts } from "@akterjs/effect/contract/description"
import { Counter } from "./counter.contract.ts"
export const contracts = await Effect.runPromise(recordedContracts([Counter]))import { writeFileSync } from "node:fs"
import { contracts } from "../src/contracts.ts"
writeFileSync("akter.contracts.json", JSON.stringify(contracts, null, 2))Describe each actor with Standard Schema validators
actor({ name, key, initial, states, commands, queries, channel }) declares the client side of one actor. Each slot takes a Standard Schema validator, so Zod, Valibot, ArkType and Effect Schema all work. Declare a void input with an undefined schema, such as z.undefined() or Schema.Undefined. List every command, query, state and typed error that the published contract holds. createClient refuses a descriptor that drifts from the contract with a ContractMismatchError.
import { z } from "zod"
import { actor } from "@akterjs/sdk"
const count = z.int()
export const CounterActor = actor({
commands: {
add: { errors: { PausedError: z.object({ count }) }, input: z.object({ by: z.int().positive() }), output: count },
pause: { errors: {}, input: z.undefined(), output: z.undefined() },
},
initial: z.object({ start: count }),
key: z.string(),
name: "Counter",
queries: {
count: { errors: {}, input: z.undefined(), output: count },
},
states: {
Counting: z.object({ count }),
Paused: z.object({ count }),
},
})Call commands and queries
createClient({ actors, contracts, url }) returns one function per actor. Each function takes a key and returns a handle with one method per command and query. A handle also has create and ensure when the initial input is not void. Under akter dev, the akter-principal header picks the development caller (Access).
import { createClient, isAkterError } from "@akterjs/sdk"
import { contracts } from "./contracts.ts"
import { CounterActor } from "./counter.sdk.ts"
export const client = createClient({
actors: [CounterActor],
contracts,
headers: () => ({ "akter-principal": '{"kind":"user","principal":{"id":"ada"}}' }),
url: "http://127.0.0.1:4000",
})
export async function addTwice(key: string): Promise<number> {
const counter = client.Counter(key)
await counter.ensure({ start: 0 })
await counter.add({ by: 1 })
try {
return await counter.add({ by: 1 })
} catch (error) {
if (isAkterError(error)) {
console.log(error.failure._tag)
}
return counter.count()
}
}The client validates each key and input before it sends the call, and it validates each reply after the call returns. A failed call rejects with an AkterError. Its failure holds one of these values:
- A typed error that the contract declares, such as
PausedError. - A client failure, such as
CallerNotAllowedError,InvalidInputErrororClientClosedError. - An
UnexpectedErrorwith a message, when the app answers with a failure that neither the contract nor the client declares.
A command whose reply is lost is sent again with the same command id, so the command runs once. To retry a command yourself, pass the same id each time, as in counter.add({ by: 1 }, { commandId }).
Keys are JSON values. Calls with keys that are equal by value return the same handle, so client.Counter(key) is safe to call on every render. client.close() closes every socket. After it, each call rejects with ClientClosedError, and each open subscription reports ClientClosedError to its error callback.
Subscribe to live state and queries
state.subscribe(observer) delivers each committed state as { value, version }. A query’s subscribe delivers each new reply the same way. Both return a function that stops the subscription. matchState(state, cases) branches on the state union, and the typecheck fails when a state has no case.
import { matchState } from "@akterjs/sdk"
import { client } from "./counter-client.ts"
export function watchCounter(key: string, show: (text: string) => void): () => void {
return client.Counter(key).state.subscribe({
error: (failure) => show(failure.message),
next: ({ value }) =>
show(
matchState(value, {
Counting: ({ count }) => `counting at ${count}`,
Paused: ({ count }) => `paused at ${count}`,
}),
),
})
}A subscription that loses its socket reconnects and skips any version it already delivered. A subscription that fails calls error once and stops. An actor with a channel also has channel.connect(presence, observer), which works as described in Channels. UI bindings wrap these subscriptions for React, Solid and Svelte.
Serve the page and the app from one origin
A browser page calls /rpc on the url you pass to createClient. Neither akter dev nor InMemoryRpc answers a CORS preflight request, and the authorization and akter-principal headers always need one. Serve the page and /rpc from the same origin. In development, proxy /rpc from the dev server to the app and pass location.origin as the url.
For example, a Vite dev server forwards calls and live sockets like this:
export default {
server: { proxy: { "/rpc": { target: "http://127.0.0.1:4000", ws: true } } },
}