createClient
Make the client an app uses to call lunas, follow live queries and queue writes, from luna/client.
createClient makes a LunaClient, which connects an app to the lunas of one environment.
import { createClient } from "luna/client";
import type { List } from "../luna/lunas/list.ts";
const client = createClient({ url: "<LUNA_URL>", key: "<LUNA_KEY>" });
const list = client.luna<typeof List>("List", "groceries");
await list.mutate("add", { text: "milk" });
Reference
createClient(options)
Returns a LunaClient. It takes one object of ClientOptions.
urlstring
The environment's URL, the LUNA_URL in .env.local.
stringkey?string
A publishable key. It reaches public luna types only.
stringtoken?string
A secret token, sent as Authorization: Bearer. It reaches private luna types too. Node only, never in an app.
stringheaders?Record<string, string>
Extra request headers. Node only.
Record<string, string>params?() => Record<string, string> | Promise<Record<string, string>>
Query parameters for each new connection, which onBeforeConnect reads as request.query. Asked again on every reconnect.
() => Record<string, string> | Promise<Record<string, string>>keepAliveMs?number
How long a query nobody watches stays live and cached, and how long an unused connection stays open.
number10000settleMs?number
How long a confirmed write stays laid over the queries of other lunas. Queries of the write's own luna get four times as long.
number1000callTimeoutMs?number
How long a call may take, including the wait to connect.
number30000multiplex?boolean
One WebSocket for all of the client's lunas. With false, one each.
booleantruestore?ClientStore
Where query results and queued writes are kept between runs. Use one per account.
ClientStoreoptimistic?Record<string, QueuedOptimistic>
Optimistic updates for queued writes, by name.
Record<string, QueuedOptimistic>LunaClient
The methods an app calls.
luna(type, ...key)?(type: string, ...key: (string | number)[]) => LunaHandle
One luna, by its type and its key values in the order the type declares them. See LunaHandle.
(type: string, ...key: (string | number)[]) => LunaHandleindex(name, partition)?(name: string, partition: string | number) => IndexHandle
One partition of an index, read live. See IndexHandle.
(name: string, partition: string | number) => IndexHandlewrites()?() => readonly QueuedWrite[]
The queued writes that wait or failed, oldest first.
() => readonly QueuedWrite[]subscribeWrites(fn)?(fn: () => void) => () => void
Hears every change to the queue. Returns a function that stops it.
(fn: () => void) => () => voidresumeWrites()?() => void
Sends the queue again after it stopped for a sign-in that ran out.
() => voidretryWrite(id)?(id: string) => void
Puts a failed write back in the queue.
(id: string) => voiddiscardWrite(id)?(id: string) => void
Drops a failed write from the queue and the store.
(id: string) => voidwipe()?() => Promise<void>
Empties the store and the queue. The promises of queued writes reject with Closed.
() => Promise<void>close()?() => void
Closes every connection. The client cannot be used after.
() => voidoptions?ClientOptions
The options the client was made with.
ClientOptionsClientStore
Text kept by key. Each method may return its value or a promise of it.
get(key)(key: string) => string | undefined
The text saved at a key.
(key: string) => string | undefinedset(key, value)(key: string, value: string) => void
Saves text at a key.
(key: string, value: string) => voiddelete(key)(key: string) => void
Removes a key.
(key: string) => voidkeys(prefix)(prefix: string) => string[]
Every key that starts with prefix.
(prefix: string) => string[]webStore(prefix, storage)
Returns a ClientStore over localStorage, or any object shaped like the browser’s Storage. It saves each key as <prefix>:<key>.
prefixstring
Keeps this store's keys apart from others. Give each account its own.
stringstorage?Storage
Where the text goes.
StorageglobalThis.localStorageQueuedWrite
idstring
The write's id. It is also the idempotency key the write is sent with.
stringpathstring
The luna it is for, such as /List/groceries.
stringhandlerstring
The handler it calls.
stringargsRecord<string, unknown>
The handler's arguments.
Record<string, unknown>status"pending" | "failed"
Whether it waits to be sent or failed.
"pending" | "failed"error?{ code: string; message: string }
Why it failed.
{ code: string; message: string }QueuedOptimistic
type QueuedOptimistic = (
local: LocalStore,
write: { luna: LunaHandle; args: Record<string, unknown> },
) => void;
An optimistic update for a queued write, given by name in options.optimistic. A write queued in an earlier run keeps only that name, so the functions are given when the client starts. LocalStore is on the LunaHandle page.
Good to know
mutate,read, live queries and pushes travel over a WebSocket, whileiterateandstreamuse HTTP. Withmultiplex, one socket carries every luna, and each luna still runs its ownonBeforeConnect.- A browser cannot set headers on a WebSocket, so
tokenandheaderswork in Node only. The publishable key goes in the address as?key=. - A dropped connection reconnects on its own. The wait grows with each failed try, from 200 ms up to 15 s.
- A luna that closes the connection itself, with code 1000 or 4000 to 4999, is not reconnected. The next use of that luna opens a new connection, and
paramsis asked again. - A refused connection fails the calls that wait for it with the luna’s own error code. Live queries keep trying after a refusal with status 408, 429, or 500 and above.
enqueuethrowsInvalidwhen the client has nostore, or when the optimistic update it names was not given here.- After
close(), every call throws aConnectionErrorwith codeClosed.
Examples
Call a private luna from your server
A secret token reaches private luna types. Keep it on a server.
import { createClient } from "luna/client";
const client = createClient({
url: "<LUNA_URL>",
token: "<SECRET_TOKEN>",
});
Send your app’s sign-in with each connection
params runs before each connection opens, so a token that was refreshed reaches onBeforeConnect.
import { createClient } from "luna/client";
const client = createClient({
url: "<LUNA_URL>",
key: "<LUNA_KEY>",
params: () => ({ session: localStorage.getItem("session") ?? "" }),
});
Keep results and writes between runs
With a store, saved results show as stale until live ones arrive, and queued writes survive a restart.
import { createClient, webStore } from "luna/client";
type Item = { id: number; text: string };
const client = createClient({
url: "<LUNA_URL>",
key: "<LUNA_KEY>",
store: webStore("account-42"),
optimistic: {
addItem: (local, { luna, args }) =>
local.update(luna.query("all"), (items: Item[]) => [
...items,
{ id: -1, text: String(args.text) },
]),
},
});
client.luna("List", "groceries").enqueue("add", { text: "milk" }, { optimistic: "addItem" });
Show writes that failed
import type { LunaClient } from "luna/client";
export function watchQueue(client: LunaClient) {
return client.subscribeWrites(() => {
for (const w of client.writes()) {
if (w.status === "failed") console.warn(w.handler, w.error?.message);
}
});
}
Call client.retryWrite(id) to send a failed write again, or client.discardWrite(id) to drop it.
Clear an account’s data on sign-out
import type { LunaClient } from "luna/client";
export async function signOut(client: LunaClient) {
await client.wipe();
client.close();
}