@lunora/server is the authoring-side package. It provides defineSchema,
defineTable, the v.* validators, and initLunora. The typed
query / mutation / action builders are emitted by codegen, so you import
them from the generated _generated/server:
// schema + validators from the package:
import { defineSchema, defineTable, v } from "@lunora/server";
// typed builders from codegen:
import { action, mutation, query } from "@/lunora/_generated/server";Codegen also re-exports v from _generated/server with v.id(...) narrowed
to your real table names. Use the package's v in schema.ts (the table names
aren't known there yet) and the generated v in your function files to get
table-name autocomplete. The two are identical at runtime.
defineSchema(tables)
Build the application schema. Returns a Schema<T> object consumed by
codegen and the runtime.
defineTable(shape)
Create a TableBuilder. Fluent methods:
.global({ backend? }): store in D1 (cross-shard) instead of a Durable Object (DO).shardBy(field): partition by the named field.source({ binding, query, tenantBy?, idColumn?, map?, columns?, refresh?, mode? }): materialize this table from an external Postgres/MySQL behind Cloudflare Hyperdrive. A system poll loop reads the (tenant-scoped) slice and lands it in the DO's SQLite, thendefineShapecarries it to clients. Implies.externallyManaged(); under.shardBy(),tenantByis mandatory (the tenant-isolation boundary, enforced by theexternal_source_unscopedadvisor lint).index(name, fields, { unique? }): secondary index.searchIndex(name, { field, filterFields?, language?, staged? }): full-text index overfield(a dot path reads a nested field);filterFields(≤16) are the columns.eq()may narrow by inside the search;languageadds that language's stopwords to the always-on accent folding (de/en/es/fr/it/nl/pt);staged: trueskips the migration-time backfill on a large table;strategy: "native"uses the engine's own full-text index where it has one (Postgrestsvector+ GIN), which is faster on large corpora, but the engine ranks, so ordering no longer matches the other backends.public(): exempt this table from.rls("required")(when secure-by-default is on).softDelete({ field? }):delete()flips a marker column (defaultdeletedAt) instead of removing the row, and list reads hide soft-deleted rows.timestamps({ field? }): adds an epoch-millisecond column (defaultupdatedAt) stamped on insert and restamped on every update (anypatchorreplace, including soft delete andrestore()) unless the write sets it. Creation time is already on every row as_creationTime
Validators (v.*)
v.string();
v.number();
v.boolean();
v.null();
v.bytes();
v.literal("admin");
v.id("users");
v.array(v.string());
v.object({ k: v.number() });
v.union(v.string(), v.number());
v.optional(v.string());A validator throws ValidationError on mismatch. The runtime wraps the error
with an args.<field> path so it points at the field that failed.
query / mutation / action
export const send = mutation.input({ channelId: v.id("channels"), text: v.string() }).mutation(async ({ ctx, args }) => {
/* ... */
});Each returns a RegisteredQuery | RegisteredMutation | RegisteredAction
with a uniform { kind, args, handler } shape consumed by codegen.
ctx shape
QueryCtx, MutationCtx, and ActionCtx share auth, scheduler, and
storage. MutationCtx.db extends QueryCtx.db with mutating methods.
ActionCtx carries a DatabaseWriter too — it does not drop db — but an
action's own writes are not transactional: each autocommits as it runs, and
a later throw rolls nothing back. A mutation dispatched through
ctx.runMutation does get the same transaction a top-level one gets, which is
what makes the "do the transactional part in a mutation, call it from the
action" split safe. See function context for
the full per-kind matrix.
Client-supplied ids
By default ctx.db.insert(table, doc) mints a fresh row id and ignores any
client-chosen _id. To let the caller choose it (which an optimistic client
needs so it can key a row before the server responds), pass a UUID via the
options:
ctx.db.insert("messages", doc, { clientId });clientId is validated for shape (a v1-v8 UUID) and still subject to the
primary-key uniqueness constraint, so a client can't collide with, overwrite, or
forge a peer row. This is the mechanism @lunora/db
uses to reconcile an optimistic row with its persisted server row.
Per-table accessor (ctx.db.<table>)
Each table exposes a typed delegate with the common read/write helpers:
findMany(args)/findFirst(args):argstakeswhere,orderBy,with(relation loading),select(column projection, top-level and per-relation viawith: { rel: { select: [...] } }),cursor/limit,endCursor(a fixed(cursor, endCursor]page forusePaginatedQuery, see Pagination), andincludeDeleted.exists(where?): boolean existence check (reusesfindFirst, no count scan).insert(doc, { skipDuplicates? }):skipDuplicates: trueresolves tonullon a unique conflict instead of throwing.upsert({ target, create, update? })/upsertMany({ target, rows }): insert-or-update keyed by a.unique()column (or tuple); returns{ id, created }.patch/replace/delete(plus the*Manybatch forms).
On a .softDelete() table, delete(id) flips the marker (cascading as a soft
delete), restore(id) clears it, and hardDelete(id) physically removes the row
(real cascade). List reads hide soft-deleted rows; pass
findMany({ includeDeleted: true }) to include them.
Transactions & atomicity
There is no explicit transaction() API: a mutation is a transaction —
for the tables that live in the shard. Every shard-local ctx.db write in a
single mutation commits atomically and rolls back together if the handler
throws, because they share one Durable Object storage transaction. This holds
however the mutation was reached — a top-level RPC, ctx.runMutation from an
action, or a reactor — and a ctx.runMutation from inside a mutation joins the
caller's transaction rather than opening a second one.
That transaction does not reach a .global() table:
those rows live in D1, which has no interactive transactions, so a mutation
that writes both a shard-local row and a global one is writing them
separately. If the handler throws after the global write, the global write
stays. Treat a global write as a step that can fail on its own, and order it
last — or move the pair into a workflow step, whose replay you can make
idempotent.
To run a side effect only after the write commits, schedule it:
ctx.scheduler.runAfter(0, internalFn, args), the deterministic equivalent of
an afterCommit hook (a registered function with serializable args, not an
inline closure). Scheduling from a mutation is part of the same all-or-nothing
unit: the job is enqueued only once the transaction commits, and a rollback
discards it.
Determinism: what actually replays
A query handler can run more than once for the same logical read: a live
subscription re-runs its query whenever a table it reads changes, so
non-deterministic output there (Date.now(), Math.random()) can genuinely
flicker between re-evaluations. Compute it in an action and pass the value in
as an argument, or accept that the field is allowed to differ per re-run.
A mutation handler does not replay under ordinary dispatch. Two
mechanisms cooperate to guarantee this on the DO-backed runtime:
- Idempotency dedup. A client-issued
x-lunora-mutation-idis deduped by(identity, mutationId). A replay of an unacknowledged write returns the cached result without re-running the handler at all. - Optimistic concurrency control (OCC) surfaces as an error, not a retry. A write guarded by optimistic
concurrency that loses the race fails the request with a
409 Conflictresponse back to the caller. The runtime does not catch it and re-invoke the handler internally; the caller decides whether to retry, and a retry is a new dispatch (a fresh idempotency key if the client mints one per attempt), not a replay of the one that failed.
So Date.now() / crypto.randomUUID() inside an ordinary mutation handler
is stable for one logical write: the handler body runs exactly once. This is
the opposite of Convex's model (where OCC failure re-runs the handler), so a
Convex-shaped mental model treats mutation non-determinism as unsafe when it
is not; porting that assumption over errs safe. The one place a DO-shaped
mental model must stay careful: a mutation invoked from inside a workflow
step or a queue consumer can be called again if the surrounding step/
consumer itself replays (Cloudflare Workflows re-executes a step's code on
retry). That is a fresh ctx.runMutation dispatch from the step's
perspective, not a replay this guarantee covers, so non-deterministic values
computed inside such a step should still be treated the way an action value
would be.
defineShape(definition) — partial replication
Declare a shape: a named, partial replication of a table for the
local-first sync engine. A client subscribes by
name + validated args; the DO resolves the predicate server-side and
AND-composes it with the read policies the shape itself declares (use).
Declared in lunora/shapes.ts.
import { defineShape, v } from "@lunora/server";
export const messagesByChannel = defineShape({
table: "messages",
args: { channelId: v.id("channels") }, // optional — omit for a parameterless shape
use: [tenantScoped], // the rls(...) guards whose read policies gate this shape
where: (ctx, { channelId }) => ({ channelId }), // runs on the DO with a trusted ctx
columns: ["text", "authorId", "channelId"], // optional projection; _id/_creationTime always included
});where returns the same WhereInput the row-level security (RLS) DSL uses, so there is no second
predicate implementation. Because it runs with an identity the client can't
forge, a shape is a read-as-permission.
RLS on a shape is opt-in through use, exactly as it is on a procedure: a
shape runs no procedure, so policies declared elsewhere in the project never
reach it. A shape that names no guard replicates on its where alone — under
.rls("required") that is a hard denial for a non-.public() table, and
otherwise codegen refuses to boot the app when the shape's table is governed on
read, naming the shape and the table (use: [] acknowledges a deliberately
ungoverned shape). See
Local-first sync.
defineMutator(definition) — custom mutators
Declare a custom mutator: a server implementation (authoritative, runs in
the shard DO) paired with an optional client twin (optimistic, runs in the
browser). Declared in lunora/mutators.ts.
// Prefer the generated re-export: same runtime, but `ctx` is your project's typed
// `MutationCtx` (schema-checked `ctx.db`) instead of the untyped base context.
import { defineMutator, v } from "./_generated/server";
export const sendMessage = defineMutator({
args: { channelId: v.id("channels"), text: v.string() },
server: (ctx, { channelId, text }) => ctx.db.insert("messages", { channelId, text, authorId: ctx.auth.userId }),
});Codegen emits each mutator as a typed api.mutators.<name> reference, so the
browser-side twin binds to it (serverRef: api.mutators.sendMessage) and infers
its args from these validators.
Add owner: "<column>" to owner-scope the write: the mutator then requires a
verified identity, rejects a client-supplied owner that disagrees with it, and sets
the column to the verified value before server runs, so the impl never repeats
an ownership check by hand. It takes the column name rather than a shape's true
because a mutator may write several tables, so there is no single .ownedBy(field)
to read it from. See
Owner-scoped writes.
The server impl is the linearization point; its writes append to the op-log
and poke back to subscribers. The DO is serialized, so there is no
server-side OCC-retry loop. The client-side optimistic twin and the watermark
ordering are covered in
Local-first sync;
the browser-side defineMutator / bindMutators live in
@lunora/db.
List endpoints
defineListArgs(config) is the shared convention for a paginated list query: it
returns the validator map for .input() plus the translation into
ctx.db.<table>.findMany(...) options, so every list endpoint agrees on how
filtering, sorting, and paging are spelled, and the generated OpenAPI describes
them without special-casing.
import type { Doc } from "./_generated/dataModel";
const listMessages = defineListArgs<Doc<"messages">>()({
filter: { authorId: v.id("users"), status: v.string() },
orderBy: ["_creationTime", "status"],
// defaultLimit: 25, maxLimit: 100, maxInValues: 100, maxOrderBy: 8
});
export const list = c.query
.input(listMessages.args)
.expose({ rest: true })
.query(({ args, ctx }) => ctx.db.messages.findMany(listMessages.toQueryArgs(args)));Callers get where, orderBy, cursor, and limit. where accepts either a
bare value (equality) or the operator object mirroring the ctx.db where DSL
({ gte, lt, in, contains, isNull, … }).
The extra () is what binds the table's document type. With Doc bound, filter
keys, orderBy entries, and each validator's type are checked against the table's
real columns, so a typo, or a column renamed out from under the endpoint, is a
compile error rather than a predicate that silently matches nothing.
TypeScript has no partial type-argument inference, so binding Doc while still
inferring the rest from the config needs the second call.
Three constraints are deliberate:
- Keyset paging, not offset. There is no
page/page_size. Offset paging re-scans from row 0 for every page and shifts rows between pages whenever the data changes (which, under a live query, it always is). - Filterable columns are enumerated.
filteris an allow-list.v.objectdrops undeclared keys, so a caller cannot predicate on a column you didn't publish. Keep the list to indexed columns;@lunora/advisor'sfilter-without-indexlint flags the static cases. This bounds which columns are reachable, not the cost of every operator:containscompiles to a substring position test, andne/notIn/isNull: falseare non-sargable too, so all of them scan regardless of the index. - No
AND/OR/NOTtrees. A flat field⇒predicate map keeps every filter routable to an index. Compose richer logic inside the procedure.
limit is clamped into [1, maxLimit] rather than rejected, and orderBy
fields outside the allow-list are refused by the validator and re-checked in
toQueryArgs. in / notIn arrays are capped at maxInValues (default 100)
to bound request size and the scan the predicate costs, not to stay under the
statement's parameter ceiling, which the where compiler handles by binding a
long list as one JSON parameter. orderBy is capped at maxOrderBy (default 8).
lunora introspect emits list procedures built on this helper. See the
CLI docs.
Caching an exposed REST endpoint
.expose({ rest: true }) publishes a procedure at
/_lunora/rest/<namespace>/<fn>. Add cache to have the runtime answer with
Cache-Control / Cache-Tag / Vary:
export const listPublicPosts = c.query
.input(listPosts.args)
.expose({ rest: true, cache: { scope: "public", maxAge: 60, staleWhileRevalidate: 300, tag: "posts" } })
.query(({ args, ctx }) => ctx.db.posts.findMany(listPosts.toQueryArgs(args)));Caching a procedure-backed endpoint can leak data, because the procedure runs
under ctx.auth and RLS. So scope is enforced, not
trusted: a request carrying Authorization, Cookie,
Cf-Access-Jwt-Assertion, Payment-Signature, or X-Payment is always answered private, even under
scope: "public". A per-caller response therefore never reaches a shared or edge
cache, and the worst a mis-declared scope costs you is a missed cache hit.
That check is a header list, and it cannot be exhaustive: resolveIdentity
receives the whole request, so an app may authenticate on anything. If your
auth reads a header not in that list, declare it:
.expose({ rest: true, cache: { scope: "public", maxAge: 60, credentialHeaders: ["x-api-key"] } })Otherwise those callers read as anonymous and their responses are cached
public. The emitted Vary also covers x-lunora-shard-key and
x-d1-bookmark, which select which rows a request sees. Treat Vary as a
courtesy to well-behaved intermediaries rather than the safety mechanism:
Cloudflare's cache honours it only for Accept-Encoding, so the real protection
is the downgrade above.
Headers are only ever applied to a cacheable exchange: a GET (so query
procedures; a mutation / action is POST-only) that returned 2xx. An error
response is never cached. tag is purgeable through the same
ctx.cache.purge({ tags: [...] }) surface httpRoute(...).cacheTag() uses, and
the emitted OpenAPI documents the headers a caller will observe.
defineDocumentHistory(options) — row-version history
.triggers() already fires on every write with the merged row and the pre-write
row in hand, which is exactly the pair a version history needs. This preset gives
them somewhere to go:
// lunora/history.ts
import { defineDocumentHistory } from "@lunora/server";
export const history = defineDocumentHistory({ retentionMs: 90 * 24 * 60 * 60 * 1000 });
// lunora/schema.ts — attach to each table you want versioned
const threads = defineTable({ ... }).triggers(history.record);
export const schema = defineSchema({ threads }).extend(history.extension);
export const { listForDocument, vacuum } = history.functions;listForDocument({ documentId, before?, limit? }) returns that row's versions
newest first. With before, the first entry back is the last version at or
before that instant — a point-in-time reconstruction in one read. vacuum drops
entries past retentionMs and reports how many, so a cron can decide whether to
run again.
Three things worth knowing before you rely on it:
It records what changed, not who. A trigger's context carries db and
scheduler and no identity, so there is no actor to record and the field does
not exist. An unattributed trail that called itself an audit log would be worse
than none.
Snapshots are redacted, at every depth. Secret-shaped fields
(hashedPassword, apiKey, refreshToken, …) are dropped before the entry is
written — a stored credential outlives the rotation meant to retire it — and the
filter recurses, so a credential inside a v.object(...) column goes too.
Matching is by exact field name, which is the only signal a trigger has, so use
redact for anything spelled differently (api_key, sessionToken).
Reads are internal. An entry is a full row snapshot, including columns the
table's own RLS hides, so listForDocument is an internal query. Wrap it in a
procedure of your own with whatever authorization the surface needs.
A snapshot over maxSnapshotBytes (64 KB default) is dropped and the entry is
marked truncated — that a row changed, and when, is the part a trail cannot
afford to lose. doc and previous are capped independently, so a large
pre-write row does not discard a small post-write one.
One blind spot: insertManyUnsafe skips triggers by design, so seed, migration, and admin-import writes leave no entry. Fine for an undo stack; if you are
using this for compliance, that gap has to be closed elsewhere. Note too that on an .rls("required") schema the merged documentHistory_versions table
needs a policy — deny client access outright, since listForDocument is internal and meant to be wrapped by a procedure of your own.
defineActionCache(options) — memoising an action
The section above caches a response at the HTTP edge. This caches the result of an action inside the app — the model call, the third-party fetch, the embedding — keyed by its arguments, with a TTL:
// lunora/cache.ts
import { defineActionCache } from "@lunora/server";
export const cache = defineActionCache({ ttlMs: 60 * 60 * 1000 });
// lunora/schema.ts — merges in as `actionCache_entries`
export const schema = defineSchema({ ... }).extend(cache.extension);
// Re-export so codegen registers it; schedule it from a cron for bulk cleanup.
export const { purgeExpired } = cache.functions;export const embed = action
.input({ text: v.string() })
.action(async ({ args, ctx }) => cache.wrap(ctx, "embed", args, async () => callEmbeddingModel(args.text)));wrap(ctx, name, args, fn) returns the stored value on a hit and runs fn on a
miss. The key is a SHA-256 of name and the args encoded through the wire codec
with sorted keys — call sites pass whole model requests, which are far too large
to index directly. Because the encoding is structural, { a, b } and { b, a }
are one entry, and bigint / Date / bytes arguments key distinctly instead of
collapsing together.
The cache is global, not per caller: the key holds name and args and no identity. If fn reads ctx.auth (or anything else that varies by caller),
put that value in args, or a second caller with the same arguments gets the first caller's result. A result that differs per caller and cannot be keyed
that way must not be cached.
The following action caches a per-user summary safely, because the verified user id is part of the key:
export const summary = action.input({ docId: v.id("docs") }).action(async ({ args, ctx }) => {
const userId = ctx.auth.userId;
return cache.wrap(ctx, "summary", { docId: args.docId, userId }, async () => summarizeFor(args.docId, userId));
});invalidate(ctx, name, args) drops one entry. invalidateAll(ctx, name) drops
every entry under a name and returns { deleted, complete } — call it again while
complete is false.
Expiry is lazy: a read past the TTL reports a miss and the row is overwritten by
the same call. Each miss also reaps a few expired rows, so an app with steady
traffic stays bounded on its own; purgeExpired is for reclaiming entries whose
names went quiet.
One thing it deliberately does not do: there is no single-flight. Two callers
that miss at the same instant both run fn; the unique index on the key means one
result is stored rather than two rows appearing. Preventing the duplicate work
needs a lock held across an arbitrarily long external call, whose own failure mode
— a crashed holder wedging the key — is worse than a cold start being paid twice.
A result over maxValueBytes (512 KB by default) is returned to the caller but
not stored, so a large answer costs a cache miss rather than a failed action.
wrap reads and writes through the app's own ctx.db, so on an .rls("required") schema the merged actionCache_entries table needs a policy like any
other. Declare one that denies client access outright — entries are keyed by a digest and carry no ownership column, so there is nothing for a row policy to
scope to.
Subpaths
@lunora/server/rls/testing:expectPolicy(policies), an in-process RLS harness that evaluates the same logic therls()middleware runs (no Worker or Durable Object needed).@lunora/server/drizzle: drizzle's SQLite schema-definition surface, used by the generated_generated/drizzle.*files.@lunora/server/data-model/@lunora/server/types: type-only helpers.
API reference
The root entry point's exports that app code calls or configures. Signatures are shortened from the API snapshot; each entry links to the section that explains it in depth where one exists.
Schema and tables
defineSchema
Type: (tables: T, vectorIndexes?, aggregateIndexes?, rankIndexes?) => ExtendableSchema<T>
Builds the application schema from a map of table names to defineTable results.
Details in defineSchema.
defineTable
Type: (inputShape: Shape) => TableBuilder<Shape>
Creates a table from a map of v.* validators. Chain the fluent methods on the
result to add indexes and storage options. Details in defineTable.
TableBuilder
Type: TableBuilder<Shape>
The fluent table configuration returned by defineTable. Each method returns the
builder, so calls chain. The methods are described under defineTable.
Schema
Type: Schema<T>
The schema object consumed by codegen and the runtime. It holds tables,
vectorIndexes, and the optional rlsMode. Apps normally get one from
defineSchema rather than building it by hand.
Validators
v
Type: v (re-exported from @lunora/values)
The validator namespace used in schemas and function arguments, such as v.string()
and v.id("users"). The signatures live on the @lunora/values
page; the usage is in Validators.
Indexes
defineVectorIndex
Type: (options: VectorIndexOptions) => VectorIndexDefinition
Declares a standalone vector index for a source derived from several fields or a
computation. Pass it in the vectorIndexes map of defineSchema.
VectorIndexOptions
Type: { dimensions, embed, metric, source: { table, select }, metadata?, model? }
Options for defineVectorIndex. source names the table and a select function
that picks the value to embed. metric is a VectorMetric, and embed is the
VectorEmbedder the index uses.
defineRankIndex
Type: (name: string, options: RankIndexOptions) => RankIndexDefinition
Declares a standalone rank index. Pass it as the fourth argument to defineSchema,
keyed by index name.
defineAggregateIndex
Type: (name: string, options: AggregateIndexOptions) => AggregateIndexDefinition
Declares a standalone aggregate index. Pass it as the third argument to defineSchema,
keyed by index name.
Function builders
QueryBuilder
Type: QueryBuilder<Context, Args, Output>
The chainable builder for a query. Chain input, output, expose, meta, and
use before the terminal query call. Details in query / mutation / action.
MutationBuilder
Type: MutationBuilder<Context, Args, Output>
The same chain as QueryBuilder, ending in the terminal mutation call. A mutation
handler is one transaction for the shard-local tables it writes. Details in
query / mutation / action.
ActionBuilder
Type: ActionBuilder<Context, Args, Output>
The same chain as QueryBuilder, ending in the terminal action call. Action writes
autocommit one at a time, so read ctx shape before relying on them.
initLunora
Type: { dataModel: <DataModel>() => DataModelInit<DataModel> }
The entry point for a typed data model. initLunora.dataModel<DataModel>() returns
an object whose create() method gives the typed builders.
Shapes and mutators
defineShape
Type: <Args, Context>(definition: ShapeDefinition<Args, Context>) => RegisteredShape<Args, Context>
Declares a named partial replication of a table for the local-first sync engine. Details in defineShape.
ShapeDefinition
Type: { table, args?, use?, where?, columns?, owner?: string | true }
The fields of a shape. table names the table, and where returns the predicate the
shard applies with a trusted context. use lists the rls(...) guards that gate reads,
and columns is an optional projection. owner owner-scopes the shape to the
verified identity: true uses the column declared by the table's .ownedBy(field), and a
string names the owning column directly. A shape needs either where or owner.
defineMutator
Type: (definition: MutatorDefinition) => RegisteredMutator
Declares a custom mutator: an authoritative server implementation, paired with an
optional client twin that runs optimistically in the browser. Details in
defineMutator.
MutatorDefinition
Type: { server, args?, client?, owner? }
server is the authoritative implementation that runs in the shard. client is the
optimistic twin. owner names the column for an owner-scoped write.
Lists
defineListArgs
Type: <TDocument>() => (config: DefineListArgsConfig) => ListArgsSpec
The shared convention for paginated list queries. Call it with the document type, then
with the config. The result provides the validator map for .input() and a
toQueryArgs translation into findMany options. Details in List endpoints.
DefineListArgsConfig
Type: { filter, orderBy, defaultLimit?, maxLimit?, maxInValues?, maxOrderBy? }
Default: defaultLimit 25, maxLimit 100, maxInValues 100, maxOrderBy 8
filter is the allow-list of filterable columns, and orderBy lists the sortable ones.
limit is clamped into [1, maxLimit] rather than rejected.
Caching and history
defineActionCache
Type: (options?: DefineActionCacheOptions) => ActionCacheComponent
Creates a TTL cache for action results, keyed by a digest of the action name and its
arguments. Call cache.wrap(ctx, name, args, fn) inside an action. The cache is
shared by every caller and the key holds no identity, so a result that depends on
ctx.auth must carry the user or tenant id in args. Details in
defineActionCache.
DefineActionCacheOptions
Type: { ttlMs?, maxValueBytes? }
Default: ttlMs 3600000 (one hour), maxValueBytes 524288 (512 KB)
ttlMs sets how long an entry is a hit. A result over maxValueBytes is returned to
the caller but not stored.
defineDocumentHistory
Type: (options?: DefineDocumentHistoryOptions) => DocumentHistoryComponent
Creates a row-version history. Attach history.record to each table with .triggers(...)
and merge history.extension into the schema. Details in
defineDocumentHistory.
DefineDocumentHistoryOptions
Type: { retentionMs?, maxSnapshotBytes?, redact? }
Default: retentionMs 7776000000 (90 days), maxSnapshotBytes 65536 (64 KB)
retentionMs is how long vacuum keeps an entry. redact lists extra field names to
drop from snapshots, on top of the built-in secret-shaped fields.
Access control
rls
Type: (policies, options?) => PolicyMiddleware
Builds the row-level security middleware from a list of policies. Add it to a
procedure with .use(...), or to a shape through its use list.
definePolicy
Type: <Context>(input: DefinePolicyInput<Context>) => Policy<Context>
Declares one row policy. on names the operation, and when is the predicate that
allows it.
defineRole
Type: (name: string, options?) => Role
Declares a named role. Grant it permissions through its options, and register it with
rls(policies, { roles }).
definePermission
Type: (name: string, options?) => Permission
Declares a named permission. A policy checks it with auth.can(permission), and a role
grants it through defineRole.
expectPolicy
Type: (policies, options?) => PolicyAssertion
An in-process harness from @lunora/server/rls/testing. It evaluates policies without a
Worker or Durable Object. Details in Subpaths.
Plugins, env and identity
definePlugin
Type: (key: string, options: DefinePluginOptions<TExtension, TContextIn, TContextOut>) => Plugin<TExtension, TContextIn, TContextOut>
Packages a schema extension and middleware as a reusable plugin under a unique key.
Both option fields are optional. When options.extension is given, the returned plugin
keeps that extension typed under the literal key.
DefinePluginOptions
Type: { extension?, middleware? }
extension is a schema extension that adds tables. middleware runs for the procedures
the plugin is installed on.
defineEnv
Type: <S extends EnvShape>(shape: S) => EnvAccessor<S>
Declares typed environment keys. A missing or invalid key throws LunoraEnvError, with
secret values redacted. The check runs lazily on first access, or eagerly through parse.
defineIdentity
Type: (claims, options?) => IdentityContract
Declares the identity claim contract. claims is a validator map that must include a
required userId string, or the call fails to typecheck.
DefineIdentityOptions
Type: { onInvalid? }
Default: onInvalid "anonymous"
onInvalid (an IdentityRejectMode) sets what the worker does with a request whose
identity fails validation.
HTTP
httpRouter
Type: () => LunoraHttpApp
Creates a Hono app for the HTTP routes the Worker serves.
Register handlers with app.get(path, handler) and similar methods, and make the
app the default export of lunora/http.ts. See
HTTP endpoints.
httpAction
Type: (handler: HttpActionHandler) => LunoraRouteHandler
Wraps a (ctx, request) => Response function as a route handler. It is the raw escape
hatch, mounted with app.all(path, httpAction(fn)).
httpRoute
Type: interface HttpRoute { get; post; put; patch; delete; head; options } where each is (path: string) => HttpRouteBuilder
The entry point for a typed route, with one factory per HTTP verb. Start with
httpRoute.get(path), chain .params(...), .searchParams(...), .body(...), and
.output(...), and finish with .handler(...). The result is a route handler to register on a router.
Live, presence and storage
defineLiveStream
Type: <Topics>(config: LiveStreamConfig<Topics>) => LiveStream<Topics>
Declares a live stream of named topics, delivered over server-sent events. A
subscription is authorized once, at subscribe. Live streams cannot be combined with
.deliveryAuthorization(...).
LiveStreamConfig
Type: { id, topics, onSubscribe?, allowAnonymousControl? }
id names the stream, and topics declares what subscribers can receive. onSubscribe
authorizes a subscription when it opens.
definePresence
Type: (options?: DefinePresenceOptions) => PresenceComponent
Creates the presence component, which tracks connected sessions. A session drops out after its TTL unless it is refreshed.
DefinePresenceOptions
Type: { ttlMs?, maxSessions?, disconnectGraceMs?, tenant? }
Default: ttlMs 30000 (30 seconds), maxSessions 1024, disconnectGraceMs 0
tenant maps the verified identity to the tenant whose rooms the caller can reach, and
it defaults to the identity's orgId claim, or "" when there is none.
disconnectGraceMs defaults to 0, which drops a session the moment its socket closes.
defineStorageRule
Type: <Context>(input: DefineStorageRuleInput<Context>) => StorageRule<Context>
Declares one rule for R2 object access: the bucket, the operation it covers, an optional key prefix, and the decision function.
defineStorageRules
Type: (rules) => ReadonlyArray<StorageRule>
Collects storage rules for the storageRules() middleware. Rules for the same bucket and
operation are combined with OR, and a duplicated rule throws at module load.
Migrations, modules and scheduling
defineMigration
Type: (definition: MigrationDefinition) => RegisteredMigration
Declares an online data migration over the documents of one table. migrate up applies
the up transform to each row.
MigrationDefinition
Type: { id, table, up, down?, covers?, batchSize? }
id is the stable key that per-shard run state is tracked under. up and down are the
forward and reverse row transforms.
defineModule
Type: (config?: ModuleConfig) => ModuleDefinition
Declares the module that a lunora/<folder>/module.ts file stands for, with a
description and the tables it owns.
cronJobs
Type: cronJobs (re-exported from @lunora/scheduler)
Builds the cron jobs declared in lunora/crons.ts. The signatures live on the
@lunora/scheduler page.
Errors
LunoraEnvError
Type: class LunoraEnvError extends LunoraError
Thrown by defineEnv accessors when a key is missing or invalid. Its failures property
lists each failing key, with secret values redacted.
ValidationError
Type: ValidationError (re-exported from @lunora/values)
Thrown when a validator rejects a value. The runtime rewraps it with an args.<field>
path that points at the failing field.
LunoraError
Type: class LunoraError (re-exported from @lunora/errors)
The base class for Lunora's errors. The codes are documented on the
@lunora/errors page.