Building an app
Write an app's schema, rules and views in TypeScript, build it to two WebAssembly components and test it on your machine
An app adds record types, rules and views to Atlas. You write it in
TypeScript with @remotehost/apps, and remotehost-app build turns it into what
the server and Atlas run:
| File | What runs it |
|---|---|
dist/backend/backend.json | the sync service: the types, their rules, the seed |
dist/backend/backend.wasm | the sync service, inside each write's transaction: your validators and afterWrite |
dist/views.json | Atlas: your declared views, drawn by Atlas's own engine with no code of yours |
dist/client.wasm | Atlas, only when you write one: the actions your views declare with app: true |
dist/app.toml | the install manifest |
Every screen is declared. An app's code never draws: Atlas draws its lists,
boards and detail pages from views.json, over the records on the device,
offline too (App protocol). An app of
schema.ts and views.ts alone ships no client component.
Both components are QuickJS programs. They import nothing but the app contract (App protocol): no WASI, so no files and no network. The time and randomness come from the host through the contract.
Start
An app is a folder:
checklist/
schema.ts the backend: types, fields, rules, seed
rules.ts validators and afterWrite (optional)
views.ts declared views: lists, boards, detail pages (optional)
client.ts actions a declaration cannot say (optional)
app.toml the install manifest
test/*.test.tsIts package.json depends on @remotehost/apps, which brings the
remotehost-app command that builds and tests it:
npm install --save-dev @remotehost/appsIt needs Node.js 22.18 or newer and no other toolchain: npm installs what the
build runs with it, as optional dependencies for your platform, so do not
install with --omit=optional. The full example is
packages/apps/examples/checklist.
The schema
import { actor, bool, defineSchema, int, ref, sortKey, text } from "@remotehost/apps";
export default defineSchema({
backend: "checklist",
title: "Checklist",
types: {
list: {
fields: {
number: int().optional(),
identifier: text({ max: 32 }).optional(),
title: text({ max: 280 }),
archived: bool().default(false),
created_by: actor(),
},
number: { field: "number", text: "identifier", format: "CL-{number}" },
author: ["created_by"],
},
item: {
fields: {
list_id: ref("list"),
text: text({ max: 2000 }),
done: bool().default(false),
sort_key: sortKey().optional(),
},
index: [["list_id", "sort_key"]],
},
},
seed: [{ type: "list", name: "inbox", fields: { title: "Inbox" } }],
});A field is required unless .optional() or .default(v). The helpers are
text, longText, int, real, bool, date, time, oneOf, uuid,
ref(to, { onDelete }), sortKey, json, blob and actor. The rules
the server keeps with no code (number, author, writer, immutable,
reserved, principal) are in App protocol.
Rules
Validators run in the write's transaction and only read. A refusal names a stable code, the field at fault and a message:
import { defineRules } from "@remotehost/apps";
import schema from "./schema.ts";
export default defineRules(schema, {
item: {
validate({ next, refuse }) {
if (next && next.text.trim() === "") return refuse("blank_text", "text", "An item needs some text");
},
afterWrite({ next, db }) {
// may write; each write is validated too
},
},
});Views and actions
Every screen is a declared view, in views.ts: what it lists, how it
groups, filters and sorts, its columns, and the actions on its rows. Atlas
draws it with its own engine; no code of yours runs to draw it. A row's
address opens another view, here a list's own items, scoped to that list:
import { defineView, defineViews } from "@remotehost/apps";
import schema from "./schema.ts";
export const listItems = defineView(schema, {
id: "list-items",
title: "Items",
noun: "items",
type: "item",
scope: { list: { eq: ["list_id", "$scope.list"] } },
orderings: [{ id: "manual", label: "Manual", sort: [{ path: "sort_key" }] }],
columns: [
{ key: "done", title: "", style: "plain", value: { if: "done", then: { lit: "[x]" }, else: { lit: "[ ]" } }, action: "toggle", width: 24 },
{ key: "text", title: "Item", value: "text", grow: true },
],
actions: [{ id: "toggle", label: "Done", app: true }],
keys: [{ keys: "x", action: "toggle" }],
});
export default defineViews(schema, [listItems]);What a declaration cannot say is an action in client.ts, declared on the
view with app: true. It gets the targets' ids, never their records, and
reads and writes through db:
import { clientFor, defineClient } from "@remotehost/apps";
import schema from "./schema.ts";
const { action } = clientFor(schema);
export const toggle = action<{ ids?: string[]; id?: string }>("toggle", ({ input, db, refuse }) => {
for (const id of input.ids ?? (input.id ? [input.id] : [])) {
const item = db.item.get(id);
if (!item) return refuse("not_found", "That item is gone");
db.item.update(item.id, { done: !item.done }, { done: item.done });
}
});
export default defineClient({ schema, actions: [toggle] });- An action that asks is a generator.
yield pick(title, choices)asks the person and resumes with the choice's id, ornullif they dismiss it. An action that never asks can be a plain function. - Writes go out once, when the action finishes. A refused action writes nothing.
- Reads must match on resume. If something the action read changed
before the person picked, the resume is refused with
changed_since_pick.
Test and build
npx @remotehost/apps build ./checklist
npx @remotehost/apps test ./checklist
npx @remotehost/apps test ./checklist -t archivenpx @remotehost/apps runs remotehost-app, the command of the
@remotehost/apps your app depends on, so an app builds with the SDK version
it was written for. A package.json script can name it directly:
"build": "remotehost-app build". It was remote app in the remote CLI,
which now only names this command.
remotehost-app test builds once, then runs test/*.test.ts with node --test
against the built components on a fake host. It is an in-memory store
that keeps the declaration's checks and rule settings and the server's
limits on a backend call (time, memory, table elements, reads, random,
nesting), and refuses with the server's codes and reasons. It differs from
the server in three ways:
- It counts a call's guest time as CPU time on its own thread, leaving out the time spent in the host as the server does, so a busy test machine does not time out code the server runs in time.
- A call that never returns hangs the test instead of timing out, since Node cannot stop it; the test runner's own timeout ends it.
- A client's writes apply at once, and
writereturns their refusal. On the real host they are queued and a refusal arrives later, throughon-event.
It keeps no sync, ordering or permissions: the sync service's conformance cases hold the server to the protocol.
A write a validator refused has code invalid, reason validator_refused,
and the validator's own code as appCode. refusal("blank_text") matches
a refusal's code, reason or appCode, and a pattern matches exactly:
refusal({ code: "invalid", reason: "validator_timeout" }).
import { loadApp, refusal } from "@remotehost/apps/testing";
const app = await loadApp(new URL("..", import.meta.url));
const ann = app.person("ann");
assert.throws(() => ann.put("item", { list_id, text: " " }), refusal("blank_text", "text"));
assert.equal(ann.run("toggle", { id }).kind, "done");
assert.equal(app.get("item", id)?.done, true);
assert.equal(app.all("item").filter((i) => i.list_id === list_id && !i.done).length, 0);The fake host draws no views: Atlas draws them, with its own engine. A
test reads the records the host keeps, with app.get(type, id) and
app.all(type), after the writes and actions it runs.
What JavaScript runs
The components run QuickJS, measured with the SDK's language check
(packages/apps/tests/quickjs.test.ts):
- Works: generators, async functions, classes, Unicode and named-group,
lookbehind and sticky regular expressions, BigInt, WeakRef,
findLast,Object.groupBy,Set.prototype.union, errorcause, Proxy,String.prototype.normalize,queueMicrotask, and dates. - The time is the host's:
Date.now(),new Date()andDate()read the contract'snow. In the backend it is the time the write's transaction started, so every validator andafterWritein one write sees the same time. A module's top level runs when the component is built, so read the time inside a function: a read at the top fails the build, saying so. - Missing:
Intl,console,setTimeout,TextEncoderandstructuredClone.toLocaleStringignores its locale. Math.randomis the host's: drawn from the contract'srandom, so it differs in every instance. You don't need it for ids: omitidand the host assigns a UUIDv7.- No awaiting: every call is synchronous, and promise jobs do not run inside one.
- An exception fails the call. A validator that throws anything but a
refusal traps, and the server refuses the write
validator_failed. Return or throwrefuse(...)for a refusal people should read. randomBytes(len)gives the host's random bytes directly, up to 64 KiB a call.
Rust
packages/apps/rust/remotehost-app builds the same two worlds in Rust:
implement backend::Guest or client::Guest and export with
export_backend! or export_client!; its view types write
views.json. backend::now_ms() and
client::now_ms() tell the time, and random_bytes(len) gives randomness;
std::time has no clock on wasm32-unknown-unknown. Build for
wasm32-unknown-unknown and make a component with
wasm-tools component new.
Loading
The build uses componentize-qjs's synchronous runtime (jco's
--backend-qjs-disable-async), so the components use no component-model
async built-ins such as waitable.join and load in wasmtime 36.
Run it in Atlas (Dev)
Nothing about an app is built into Atlas or the sync service. Both read app
packages when they start, the folder remotehost-app build writes:
dist/
app.toml
views.json when the app has a views.ts
client.wasm when the app's client.ts has actions or onEvent
backend/backend.json
backend/history/<n>.json every earlier version of the declaration
backend/backend.wasmOn the repository's local stack (scripts/dev-stack.sh), point both at the same folder
and restart them. Nothing is rebuilt.
-
The sync service serves the backends of the packages
APP_PACKAGESnames,:-separated: each entry a package, or a directory of them. A later entry's package takes the place of an earlier one's with the same app id. The local stack names the checkout's own packages, then those inDEV_STACK_APP_PACKAGES:DEV_STACK_APP_PACKAGES=$HOME/checklist/dist scripts/dev-stack.sh restart remotehost-syncWith
APP_BACKENDS_ALLoff, as in production, only built-in apps' backends are served, so a hello naming yours is refused. -
Your backend's tables, made from its declaration, since no migration in the repository has them. Apply them to the local database as its owner:
cd apps/atlas scripts/cargo.sh run -p remotehost-sync --bin backend-sql -- --package ~/checklist/dist \ | psql "postgres://postgres@127.0.0.1:55440/remotehost"This prints every version of the declaration. After a new version, add
--since <n>to print only the versions aftern. -
Atlas (Dev) loads the folders
atlas app devnames, beside its own packages, and asks the sync service for their backends:atlas app dev ~/checklist/dist # add it, after reading it as a package atlas app dev # list them, or what is wrong with one atlas app dev ~/checklist/dist --removeThe list is the Atlas home's
dev-appsfile, one folder a line. Only Atlas (Dev) reads it, and a dev folder can't say it is built in. Each folder's app joins the rail after the workspace's apps, its declared views drawn in the window. A dev folder that declares a backend Atlas's own packages already declare is refused alone, saying which; Atlas still opens.atlas --dev-appis gone. If you usedatlas --dev-app <src>with your app's source folder, runatlas app dev <src>/distonce instead: name the folder that holdsapp.toml, whichremotehost-app buildwrites todist.Atlas reads which folders to load and their backends as it starts, so quit and reopen Atlas (Dev) after adding or removing a folder or changing its backend. Inside a folder, a new
client.wasmis swapped into the running window and a changedapp.tomlrestarts the client, with no restart of Atlas. Restart the sync service first (step 1), so it serves the backend Atlas asks for. If it does not, the service refuses the request for your backend. Atlas then asks again for its own apps' backends alone, so Issues keeps syncing, and writes to your backend are refused until both are restarted. -
Enable the backend in a workspace:
POST /v1/workspaces/<id>/backends/<backend>/enableon the sync service.
Your validators are compiled when the service starts, and installed for an org the first time someone in it writes to the backend. While no package the service loaded holds the version a write names, the write waits and is tried again, as it does for a lock.