# Mote: the docs: every page, in reading order Each page stands between marks that say its address as Markdown, its source file and its title. Links between pages are as written in the sources (relative .md paths). # Mote: the docs Mote is a language for apps that run in a browser: one file is the whole app, its pages, back end, data and sign-in, and one Rust binary with no dependencies compiles it. This page is the map of its docs. Start with [card.md](card.md) (the language in brief: most programs can be written from it), then come here to find the page with the whole story. Every component and battery is live, with its source beside it, in the playground at . ## Getting started ```sh rustup target add wasm32-unknown-unknown # once cargo install --path compiler # in a checkout of the repository mote editor vscode # or cursor, neovim, helix, … mote dev app.mote # serve it, reload on save ``` The compiler is Rust; it builds its batteries to wasm, hence the target. [Bun](https://bun.sh) runs the back end of a program that has one (`server fn`, `model`); `mote dev` starts it for you. Nothing else is installed: there is no package to fetch. [cli.md](cli.md) has every command, [editor-plugin.md](editor-plugin.md) what the editor then does. ## What Mote is Mote is a language for writing apps that run in a browser, and the tools that go with it. One `.mote` file is an app: declarations (state, actions, functions) and markup, in one indented syntax. The compiler turns it into one static HTML page, and, when the program has functions that must run on a server, one JavaScript module for Bun. ```mote // docs: whole state n = 0 button `Pressed ${n} times` press={n += 1} ``` ```text mote build app.mote --single writes dist/index.html mote dev app.mote serves it and reloads on save ``` ## How the pieces fit ```text app.mote (+ files it uses, assets/, public/, agents.mote) │ ▼ the compiler (compiler/, Rust, one binary: `mote`) │ lex → parse → check types → emit JavaScript and HTML │ picks the runtime parts, kit components, batteries and icons the program uses ▼ dist/index.html one page: HTML, CSS, one script. Static: any host serves it. dist/server/main.js only if the program has `server fn`s or `model`s: run with Bun dist/… manifest, service worker, icons, assets (an installable, offline app) ``` - **The compiler** (`compiler/src/*.rs`) checks the whole program before it writes anything, and its messages say what to write instead. - **The runtime** (`runtime/`) is what a page runs on: a small reactive core (signals and effects), the DOM helpers, events, storage, widgets. It is written in Mote's own runtime dialect and compiled by the compiler. It is divided into *parts*; a page carries only the parts its program needs. - **Batteries** (`batteries/`) are the heavy pieces of the standard library, written in Rust and compiled to wasm: picture codecs, zip, workbooks, argon2, MP4, code scanning, full-text search, syntax trees, fonts. They run in workers, never on the page's own thread. A build writes each one a program can use as a file beside the page (`assets/zip..wasm`), which the page fetches when it is first called and the browser keeps; a page built `--single` carries them inside. - **The kit** (`kit/`) is about 770 components written in Mote (buttons, dialogs, tables, chat, code blocks). A capitalised tag the page does not declare is looked for there; a page carries only those it uses. - **The back end** (`runtime/server/`) is what `server/main.js` is made of: it serves the page, answers the page's calls, keeps accounts, pushes live values and notifications. It runs on Bun. There is no framework to install, no bundler, no `node_modules`. What ships is what the program uses. ## How to use these docs **To write or change a Mote program** (the usual case): 1. Read [card.md](card.md). It is short and stands alone for the common cases. 2. Read [language.md](language.md) and [markup.md](markup.md) once. They are the two halves of every program. 3. Look up the rest when you need it, through the [how do I…](#how-do-i) table or the [namespaces](#namespaces). 4. Run `mote check file.mote` after every change. The compiler's messages name the fix. Trust it over memory: it knows exactly what exists. 5. Do not guess a name. If a call is not in these pages, it does not exist; `mote check` will say so, with what the namespace does have. Three rules explain most first mistakes: - Only an `action` (or a `{…}` handler) writes state. A `fn` is pure. - A call that can fail must meet `else` or `?` where it is made. - In markup a space ends a value: anything with an operator goes in parentheses. **To work on Mote itself** (the compiler, the runtime, a battery, the kit): read [internals.md](internals.md), then [../runtime/README.md](../runtime/README.md) for the runtime dialect, then [testing.md](testing.md). Every page ends with *In the source*, which names the files and functions behind what it describes. Each topic page is complete for its subject and can be read alone. Each starts with a whole program, then a *Mental model* (how it works underneath), then every form, what is refused, and the pitfalls. ## The pages Grouped as the site's side list groups them; the site reads them in this order. ### Start The language in brief, before anything else. | Page | What it answers | |---|---| | [card.md](card.md) | The language in brief: what to read first. `mote card` prints it. | ### Language What every program is made of. | Page | What it answers | |---|---| | [language.md](language.md) | Declarations, types, `none` and `T?`, `wasm fn` (experimental), logic, built-in calls, a call that can fail, bytes, files and `use`, packages. | | [js.md](js.md) | JavaScript of the program's own, a last resort (what comes first, and what it is for): `extern js` (the typed fns a file exports, on the page, in a worker, on the back end; an element handed to a widget; what ships), `extern script` (another site's script in the head, `integrity=`), and the edge of what the compiler checks. | | [reactivity.md](reactivity.md) | When things run and re-run: state, derive, resources, tasks, timers, `watch`; `newest` (a later run calls an earlier off); what is tracked; workers, and what is moved to them; `fns main` / `fns off` said once for a file or a package. | ### The page What is on the screen, and what it hears. | Page | What it answers | |---|---| | [markup.md](markup.md) | Tags, text, values, styles, colour roles, conditional styles and `group`, binding, `if`/`for`/`match`, `try` / `else err` / `again` (a part of the page that fails shows a fallback), routes, components and slots, named slots, popovers, icons, assets. | | [events.md](events.md) | Every event and what it hands a handler, `it` in a block, dragging (`drag=`, `dropped=`), every drag ending once (`pointercancel`), swiping (`swipe=`), paste, keys and chords, `shortcut` for the whole page, `ref=` and `el.…`. | | [kit.md](kit.md) | How the kit works, the everyday components, the index into [kit/](kit/). | | [kit/*.md](kit/) | Every kit component, by family: [base](kit/base.md), [more](kit/more.md), [chat](kit/chat.md), [ai](kit/ai.md), [code](kit/code.md), [markdown](kit/markdown.md), [flow](kit/flow.md), [editor](kit/editor.md), [richtext](kit/richtext.md), [terminal](kit/terminal.md). | | [widgets.md](widgets.md) | `editor`, `richtext`, `terminal`, `flow`; where every built-in element is documented. | | [agents.md](agents.md) | Pages agents can use: `data-mote`, the `mote-agent` block, `agents.mote`, `llms.txt`. | ### Data What is kept, in the browser and on the back end. | Page | What it answers | |---|---| | [data.md](data.md) | `persist` and `store`, `net`, `db`, `sql`, `fs`, `clipboard`, `crypto`, `zip`, notifications without a back end. | | [tables.md](tables.md) | `csv` and `xlsx`: CSV and Excel workbooks read (typed into a shape, or a large CSV a piece at a time) and written, on a page and on the back end. | | [models.md](models.md) | `model` and `local model`: a schema that is also typed reads and writes; filters, `with`, `atomic`; `put` and `inc`; counting and summing by fields; rules (and a rule that reads a setting), hidden fields, hooks, `live` finds and what a write sends them; a write that shows at once (`pending(row)`, `confirmed`); models chosen at run time; `schema.lock`, `migrate` and changing a schema. | ### Back end The server a program brings with it. | Page | What it answers | |---|---| | [back-end.md](back-end.md) | `server fn`, signing in, `live` values, events, notifications, `proc`, `fs.folder`; who may do what (`rule`, `requires`, `limit`, `--access`), `secret()`, acting as someone; `job fn`, `server at`, `server every`; logs, failure kinds, `on failure`, stacks by `.mote` lines, health and stopping; a call answered once; calls to another Mote back end, `api.json`; snapshots, one database for several apps; running it. | | [delivery.md](delivery.md) | How a build reaches a browser: the same source and compiler give the same bytes (`mote build --check`), `build.txt` and the build's hash (`app.build()`), `policy=strict` (a Content-Security-Policy made from the build, with HSTS, Referrer-Policy, COOP and Permissions-Policy; `connect=`), `update=ask` (`on app.update`, `app.check()`, `app.update()`), and what none of it protects from. | | [calls.md](calls.md) | Calls between browsers: `rtc.join`, a call's peers, mute, camera, screen sharing, messages, `video of=`; `server call` (who may be in a room); STUN and TURN. | ### Media and drawing Pictures, sound, video, canvases, text. | Page | What it answers | |---|---| | [media.md](media.md) | `img` (formats, deep pictures, colour), `paint` (brushes, layers) and `canvas layers=`, `scan`, `camera`, `vid`/`aud`/`reel` (a film's tracks, keys and grades), speech. | | [charts.md](charts.md) | Charts: a component for each kind (line, area, bar, scatter, box plot, heat map, pie, candlestick, Sankey, treemap, sparkline …), `Chart` with marks as children, a million points, zoom and brush, the keyboard, theming. | | [drawing.md](drawing.md) | `surface` (`draw.…`: gradients, layers, a drawing as a picture, typing), `surface gl` (`gl.…`, a picture through a shader), the 3D canvas (`canvas boxes=`, `canvas scene=`). | | [scene.md](scene.md) | `canvas scene=` in full: `three.*` records, materials, pictures on them (`map`, `mapSize`, `grain`, `sides`), lights, the camera. | | [words.md](words.md) | Languages and formats: the app's own strings (`words "de"`, `t("key", {name})` checked against the keys, counts), the language shown (`words.lang`, `words.choose`, ``), `fmt.number/currency/percent/list/plural`, `screen.lang`. | | [text.md](text.md) | `re` and raw strings, `search`, `syntax` (code and Markdown), `font` (font files: layout, outlines), `Highlight`, `CodeBlock`, `Markdown`. | | [pdf.md](pdf.md) | `pdf`: PDF files made from parts (text in standard and embedded fonts, tables, pictures, drawing, headers and footers, links, an outline), read (text with places, pictures, metadata, form fields), changed (forms filled and flattened, merged, pages picked, turned, stamped); showing one. | ### Extensions Packages of ordinary Mote shipped beside the compiler, taken with one `use` line. | Page | What it answers | |---|---| | [../extensions/README.md](../extensions/README.md) | What an extension is, taking one (`[packages]` in `mote.toml`, `use "pkg:…"`), writing one (`wants fn`, a rule, a route, a named slot, settings, tests); each extension's own README: [usage](../extensions/usage/README.md), [usage-forward](../extensions/usage-forward/README.md), [google](../extensions/google/README.md), [oauth](../extensions/oauth/README.md), [jwt](../extensions/jwt/README.md), [totp](../extensions/totp/README.md), [passkey](../extensions/passkey/README.md), [magic](../extensions/magic/README.md), [admin](../extensions/admin/README.md), [stripe](../extensions/stripe/README.md), [paypal](../extensions/paypal/README.md), [paddle](../extensions/paddle/README.md), [polar](../extensions/polar/README.md), [mail](../extensions/mail/README.md), [replicate](../extensions/replicate/README.md), [s3](../extensions/s3/README.md), [aws](../extensions/aws/README.md), [gcloud](../extensions/gcloud/README.md), [azure](../extensions/azure/README.md), [ai](../extensions/ai/README.md), [twilio](../extensions/twilio/README.md), [slack](../extensions/slack/README.md), [discord](../extensions/discord/README.md), [notion](../extensions/notion/README.md), [airtable](../extensions/airtable/README.md), [linear](../extensions/linear/README.md), [github](../extensions/github/README.md), [graphql](../extensions/graphql/README.md), [telegram](../extensions/telegram/README.md), [mcp](../extensions/mcp/README.md), [alert](../extensions/alert/README.md), [sentry](../extensions/sentry/README.md), [captcha](../extensions/captcha/README.md), [postgres](../extensions/postgres/README.md), [redis](../extensions/redis/README.md). | | [analytics.md](analytics.md) | Every event kept and asked: `log` (an append-only durable log, consumers, replay, the capture door, PostHog's shapes), `fact` (an analytics table on SQLite or ClickHouse, rollups), the questions (trends, funnels, retention, paths, stickiness, lifecycle, frequency, people), and the usage extension's product analytics: people, cohorts, flags, experiments, dashboards, the panel. | | [usage.md](usage.md) | What people do in a program, in its own admin page: `usage=on`, what is collected and what never is, cookies and consent, the web's numbers (visitors, visits, bounces, sources, countries, devices, goals, speed), `track`, the usage extension's panel and questions, several apps in one panel, `server on usage`. | | [google.md](google.md) | Continue with Google, an extension: the console's steps, the settings, `GoogleButton`, what is kept, whose account someone from Google is and why, a Workspace domain, `googleMay` (who may come in), shared accounts, running behind a proxy. | | [oauth.md](oauth.md) | Signing in with GitHub, Microsoft (tenants, work addresses), Apple, Discord, GitLab, LinkedIn, Slack, any OpenID provider by its issuer, and a connection for each customer (B2B single sign-on); a provider's tokens sealed and refreshed for its API (`oauthToken`); client credentials and the device code; how to check each against the real provider. | | [second-factor.md](second-factor.md) | Second factors in `auth` (`auth.owed`, `auth.secondPassed`, `requires secondFactor(10)`); codes from an app (TOTP, recovery codes, a QR code writer); passkeys checked on the back end (how many an account, AAGUIDs, attestation asked for and not checked), and `passkey.create` / `passkey.get` in a page, with or without a back end; a key from a passkey (the PRF extension, `passkey.prfSupported`). | | [jwt.md](jwt.md) | A public API's door: API keys (shown once, kept as a hash, scopes, last used, taken back), tokens the back end signs, `/.well-known/jwks.json` and rotation, `requires scope("…")` and `apiCall`. | | [magic.md](magic.md) | Signing in by a link or a code in a mail, over the mail extension. | | [saml.md](saml.md) | SAML and SCIM: not built, why, what a B2B product loses, what OIDC by issuer covers, and the design they would have. | | [services.md](services.md) | Another service without a package: what you would npm install and what to use in Mote, and an extension for a service that is not here, in forty lines. | | [stripe.md](stripe.md) | Payments, billing and marketplaces with Stripe, an extension: Checkout in every mode, the portal, the plans kept at Stripe from the code (`stripeSync`), subscriptions (trials, proration previewed, seats, pause, a downgrade at the period's end), usage on meters, invoices, credit notes, tax, saved cards and charges off-session, payment links, disputes, payouts, Connect; the kinds of failure; idempotency; every event (`Stripe-Signature`, each once, read fresh, caught up after downtime), `StripePlan`, `stripeStanding` and `stripeCan` with a grace; testing a program's hooks; a restricted key's rights; the API version; checking it in test mode in ten minutes. | | [paypal.md](paypal.md) | Payments and subscriptions with PayPal, an extension: orders (approve, capture once, authorize, refund), subscriptions, payouts; the kinds of failure; events checked by PayPal's verify call, each once; checking it against PayPal's sandbox; why there is no one billing facade. | | [paddle.md](paddle.md) | Paddle Billing, a merchant of record, an extension: transactions and checkout links, customers, subscriptions (proration, pause, resume, cancel), refunds as adjustments, the portal; `Paddle-Signature` events, each once; checking it in Paddle's sandbox. | | [polar.md](polar.md) | Polar, a merchant of record for software, an extension: checkouts and checkout links, customers by `external_id`, subscriptions, benefits (`polarCan`), orders, refunds, the portal; Standard Webhooks (`webhook.check`), each once; checking it in Polar's sandbox. | | [mail-library.md](mail-library.md) | The mail extension's library: a message parsed (RFC 5322, MIME, encoded words, RFC 2231, nested parts, legacy character sets) from a reader with each body a piece at a time, in a page, a worker or the back end alike; mbox files a message at a time; addresses, Punycode, the Public Suffix List. | | [mail.md](mail.md) | Mail through Resend or Cloudflare Email Service, an extension: `mailSend` and its fields, batches, a message for later, the suppression list, Resend's events (Svix signatures), bodies from Markdown, checking it against the services. | | [replicate.md](replicate.md) | Running models on Replicate, an extension: a prediction by its version, waited for or streamed; a run kept as a row and followed by a job and the webhook until it ends; files in and out; the kinds of failure. | | [postgres.md](postgres.md) | Postgres, an extension: its wire protocol written out on `tcp.open`, TLS and SCRAM-SHA-256, parameters never in the text, values by type, a pool, transactions and savepoints, LISTEN/NOTIFY, COPY, a cancel; Supabase, Neon, RDS and poolers; checking it against a real server. | | [redis.md](redis.md) | Redis, an extension: RESP2 and RESP3 on `tcp.open`, or Upstash's REST API behind the same calls; strings, hashes, lists, sets, sorted sets, streams, pipelines, MULTI/EXEC, pub/sub; a rate limiter, a lock with a fencing token, cache-aside. | | [s3.md](s3.md) | Files in an S3-compatible bucket (AWS, R2, B2, MinIO), an extension: SigV4 written out and checked against AWS's examples, put, get, head, delete, list, uploads in parts, presigned addresses for a browser; what a model's `file` field would need to be kept in one. | | [aws.md](aws.md) | AWS, an extension: SigV4 for any service, the back end's keys (its own, or a role's on EC2, ECS, EKS), SQS and a consumer, DynamoDB, Lambda, SNS and its signed messages, SES behind `mailSend`, Bedrock behind the ai extension, Secrets Manager, SSM, EventBridge; checking each against AWS. | | [gcloud.md](gcloud.md) | Google Cloud and Google's APIs, an extension: a service account, the metadata server or a person's token; Cloud Storage, Sheets, Drive, Calendar, Gmail behind `mailSend`, FCM and APNs, Pub/Sub, BigQuery, Gemini behind the ai extension, Maps. | | [azure.md](azure.md) | Azure Blob Storage (SharedKey, SAS) and Communication Services Email behind `mailSend`, an extension; what else of Azure would matter. | | [ai.md](ai.md) | Language models, an extension: Anthropic, OpenAI and Gemini behind one surface; streaming into the page or out of a route; tools and answers in the program's own types; batches, files, pictures, speech; costs, budgets, a cache, recorded replies; embeddings and a vector store; `AiChat` of the kit's chat parts. | | [twilio.md](twilio.md) | Text messages and phone codes (Verify) through Twilio, an extension; its status callbacks, signed. | | [slack.md](slack.md) | A Slack app, an extension: messages and threads, reactions, files, people and channels page by page, modals and the home tab, Block Kit as shapes; events, slash commands and interactivity, signed, answered in three seconds, done in jobs; Slack's limits. | | [discord.md](discord.md) | A Discord bot, an extension: messages with embeds, buttons and selects, channels and threads, members and roles, webhooks, slash commands; the Interactions Endpoint checked with Ed25519, deferred work in jobs; buckets and the global limit. | | [notion.md](notion.md) | Notion, an extension: a database's data sources queried with filters and sorts page by page, every property as a plain value, pages made and changed, search, a page's content read as Markdown and written from it; Notion's rate. | | [linear.md](linear.md) | Linear, an extension: issues listed with Linear's filters by cursor, made and changed, comments, teams and states over its GraphQL API; errors and the spent limit as failures; the webhook checked and each delivery done once in a job. | | [github.md](github.md) | GitHub, an extension: repositories, files read and written, issues, pull requests, comments, reviews, checks and statuses, releases, Actions; lists by their Link header; a GitHub App's JWT and installation tokens kept; limits held for every caller of a token; webhooks checked (X-Hub-Signature-256) and done once in a job. | | [graphql.md](graphql.md) | Any GraphQL API, an extension: the query and its variables, data or the errors as failures with a kind, an answer in part, a connection page by page by its cursor; what github and linear are made on. | | [telegram.md](telegram.md) | A Telegram bot, an extension: messages with keyboards, files by id, address or bytes, edits, presses answered, files fetched; updates by a webhook checked by its secret token or by long polling in a job, each done once. | | [airtable.md](airtable.md) | Airtable, an extension: records listed by formula, view and sort page by page, made, changed, upserted and deleted ten a request; the base's five a second and its thirty seconds after a 429; webhooks, their pings checked and each change told once. | | [mcp.md](mcp.md) | The Model Context Protocol, an extension: the program as an MCP server over Streamable HTTP (its typed fns as tools, its rows as resources, prompts, progress as events, sessions, a bearer and the Origin checked), and as a client of other servers whose tools the ai extension's loop can call. | | [alert.md](alert.md) | A line to Slack, Discord or any webhook, an extension; every fault, once in ten minutes. | | [sentry.md](sentry.md) | Faults and reports to Sentry, an extension, fed by `server on failure`. | | [captcha.md](captcha.md) | The server's check of a Turnstile or hCaptcha token, an extension. | | [admin.md](admin.md) | The admin extension: `rule admin`, `AdminPanel` and its pieces (people, every model's rows under its own rules, jobs, health, access, a log), acting as someone, what an admin can and cannot do. | ### Tools Building, checking, testing, and working on Mote itself. | Page | What it answers | |---|---| | [cli.md](cli.md) | `mote build/dev/serve/check/test/migrate/restore/tree/editor/lsp/card/runtime`, flags (`check --access`, `--perf`, `--api`, `--against`), outputs (source maps, `api.json`, `.env.example`, `Dockerfile`), diagnostics' ids and where they end (underlined in a terminal), project folders, `mote.toml`, environment. | | [testing.md](testing.md) | Tests in the program (`test`, `mote test`: the back end, with its own clock, stand-ins, `given env`), `tests/all.sh`, expectations, `tests/real.mjs` and writing a driver, unit tests, `docs/check.sh`. | | [editor-plugin.md](editor-plugin.md) | Your editor in one line (`mote editor vscode`, or Cursor, Windsurf, VSCodium, Neovim, Vim, Helix, Emacs); `mote lsp`, the language server: what is wrong as you type, hover with a declaration's comment, definitions, rename, completion, the outline. | | [internals.md](internals.md) | The compiler's passes and files, how runtime parts are chosen, batteries, adding a namespace end to end. | | [../runtime/README.md](../runtime/README.md) | The runtime dialect: the reference for writing `runtime/*.mote`. | | [../bench/README.md](../bench/README.md) | Measurements of Mote itself: `wasm fn` against JavaScript in Chrome and Bun, a long feed of pictures, reading codes; each with the way to run it again. | ## How do I… | Task | Page | |---|---| | keep a value and show it | [language.md](language.md#state), [markup.md](markup.md#text) | | keep a list, add to it, remove from it | [language.md](language.md#writes), [markup.md](markup.md#control) | | keep something between visits | [language.md](language.md#state) (`persist`), [data.md](data.md) | | compute something from state | [reactivity.md](reactivity.md#derive) | | bind a field to state | [markup.md](markup.md#binding) | | react to a press, a key, a pointer, a dropped file, a paste | [events.md](events.md) | | let the user drag one thing onto another; reorder a list by hand | [events.md](events.md#dragging) | | make a card follow the finger and throw it with a flick; know where it stands mid-transition | [events.md](events.md#swiping) (`swipe=`), [events.md](events.md#the-element-itself) (`el.transform`) | | end a drag however the press ends (a touch taken to scroll, the page hidden) | [events.md](events.md#every-drag-ends) (`pointercancel=`) | | show slides one at a time, set by index, followed by a swipe | [kit/base.md](kit/base.md#carousel) (`Carousel`) | | keep a sheet on the page at a peek (a map's list, a player) | [kit/base.md](kit/base.md#a-drawer-that-stays-on-the-page) (`Drawer modal=false`) | | add a keyboard shortcut; know whether Shift is held | [events.md](events.md#keys) | | hear a shortcut while the keyboard is in a field | [events.md](events.md#keys-typed-in-a-field) | | a shortcut for the whole page, wherever the keyboard is | [events.md](events.md#shortcuts-for-the-whole-page) | | keep every fn of a file or a package on the page, said once | [reactivity.md](reactivity.md#said-once-for-a-file-or-a-package) | | read or set a field's selection; insert at the caret; put a menu at the caret | [events.md](events.md#a-fields-caret-and-selection) | | put a button inside something that is itself pressed | [events.md](events.md#a-press-inside-a-press) | | know whether the page is in front, or the person is away | [markup.md](markup.md#in-front-and-at-it) | | say what a shared link shows (title, description, picture); open the share sheet | [markup.md](markup.md#a-shared-link), [data.md](data.md#share) (`share()`) | | make a link to this page that someone else can open | [markup.md](markup.md#routes) (`route.link`), [back-end.md](back-end.md#what-a-server-fn-can-use) (`route.origin`) | | hand a secret to a page of another site, or be handed one, after `#` | [markup.md](markup.md#the-fragment) (`go("https://…/#…")`, `route.takeFragment()`) | | let another site's page call a route; answer `HEAD` | [back-end.md](back-end.md#other-origins-cors) (`cors=`), [back-end.md](back-end.md#head) | | do something when a value changes | [reactivity.md](reactivity.md#watch) | | style something; follow light and dark | [markup.md](markup.md#styles), [markup.md](markup.md#colour-roles) | | style on hover, or by the window's width | [markup.md](markup.md#conditional-styles) | | print the page or a part of it; fill the screen | [markup.md](markup.md#print-and-the-whole-screen) | | show one thing or another; show a list | [markup.md](markup.md#control) | | have several pages | [markup.md](markup.md#routes) | | make a component; pass children to it | [markup.md](markup.md#components) | | use a ready-made button, dialog, table, menu | [kit.md](kit.md) | | open a dialog, a popover, a tooltip; show a toast | [markup.md](markup.md#popover-and-tip), [kit.md](kit.md), [language.md](language.md#built-in) | | search as the person types, so that only the last answer counts | [reactivity.md](reactivity.md#newest-a-later-run-calls-an-earlier-one-off) (`action … newest`) | | load data when the page opens | [reactivity.md](reactivity.md#resources), [reactivity.md](reactivity.md#tasks) | | fetch from the network | [data.md](data.md#net) | | handle a failure; show "loading" | [language.md](language.md#a-call-that-can-fail), [reactivity.md](reactivity.md#resources) | | run something on a timer | [reactivity.md](reactivity.md#timers) | | keep heavy work off the page's thread | [reactivity.md](reactivity.md#workers) | | run a loop of numbers as WebAssembly (experimental), and see what it gains | [language.md](language.md#wasm-fn) (`wasm fn`), [../bench/README.md](../bench/README.md#wasm-fn-against-javascript) | | call a server; keep a secret off the page | [back-end.md](back-end.md#server-fn) | | run another program (git, a build, a test) | [back-end.md](back-end.md#other-programs) | | call another Mote app's back end, typed, with no secret in the code | [back-end.md](back-end.md#another-back-end) | | describe the back end to other tools (OpenAPI, a TypeScript client) | [back-end.md](back-end.md#describing-the-back-end) | | read and write files of a folder on the server | [back-end.md](back-end.md#folders) | | go on working after a call has answered; work when the back end starts, or on a timer | [back-end.md](back-end.md#work-of-its-own) | | call an API that limits, refuses, or streams its answer | [data.md](data.md#netsend), [data.md](data.md#netstream) | | sign people in | [back-end.md](back-end.md#signing-in) | | let people sign in with Google | [google.md](google.md) | | let people sign in with GitHub, Microsoft, Apple, Slack, their company's Okta | [oauth.md](oauth.md) | | ask for a code from an app, or a passkey | [second-factor.md](second-factor.md) | | keep a key under a passkey (the PRF extension), with or without a back end | [second-factor.md](second-factor.md#a-key-from-a-passkey-the-prf-extension) | | give a public API keys and tokens | [jwt.md](jwt.md) | | let people sign in by a link or a code in a mail | [magic.md](magic.md) | | take payments, sell a subscription, bill by usage, pay sellers, hear Stripe's webhooks | [stripe.md](stripe.md) | | take payments with PayPal, or sell through a merchant of record (Paddle, Polar) | [paypal.md](paypal.md), [paddle.md](paddle.md), [polar.md](polar.md) | | send mail (Resend, Cloudflare), keep a suppression list, write a mail in Markdown | [mail.md](mail.md) | | read a mail message or an mbox, in a page or on the back end; compare addresses, find a domain's organisational domain | [mail-library.md](mail-library.md) | | run a model on Replicate, stream its output, follow a long run across restarts | [replicate.md](replicate.md) | | keep files in S3, R2, B2 or MinIO; let a browser upload straight to a bucket | [s3.md](s3.md) | | read and write a Postgres database (Supabase, Neon, RDS, one of your own) | [postgres.md](postgres.md) | | a cache, a rate limit, a lock, a queue or pub/sub in Redis or Upstash | [redis.md](redis.md) | | talk to a service below HTTP (a TCP or TLS protocol), or one that streams over a WebSocket | [back-end.md](back-end.md#connections-of-its-own) | | talk to a language model, stream its words, let it call my fns; a chat in the page | [ai.md](ai.md) | | use AWS: queues, DynamoDB, Lambda, SES, Bedrock, secrets; run on a role, not keys | [aws.md](aws.md) | | use Google's APIs: Cloud Storage, Sheets, Drive, Calendar, Gmail, push to phones, Pub/Sub, BigQuery, Gemini | [gcloud.md](gcloud.md) | | keep files in Azure Blob Storage; send mail through Azure | [azure.md](azure.md) | | read or write XML | [data.md](data.md#xml) | | send a text message, check a phone number with a code | [twilio.md](twilio.md) | | make a Slack app: post with blocks, hear events, answer slash commands, buttons and modals | [slack.md](slack.md) | | make a Discord bot: slash commands, buttons, embeds, roles | [discord.md](discord.md) | | read and write a Notion database, a page as Markdown | [notion.md](notion.md) | | read and write an Airtable base; be told when it changes | [airtable.md](airtable.md) | | make and follow Linear issues from my program | [linear.md](linear.md) | | open issues, write files, post checks or answer webhooks on GitHub; be a GitHub App | [github.md](github.md) | | ask any GraphQL API (Shopify, Contentful, my own), page by page | [graphql.md](graphql.md) | | make a Telegram bot | [telegram.md](telegram.md) | | let Claude or another MCP client call my fns; use another MCP server's tools | [mcp.md](mcp.md) | | post to Slack or Discord; be told of every fault | [alert.md](alert.md), [sentry.md](sentry.md) | | check a captcha (Turnstile, hCaptcha) on the server | [captcha.md](captcha.md) | | use a service there is no extension for, without `extern js` | [services.md](services.md) | | invite someone: an account with no password, a link that proves their address | [back-end.md](back-end.md#accounts-made-by-the-programs-own-code) | | see how the app is used: active people, top screens, what fails, a measure of my own | [usage.md](usage.md) | | keep every event and ask it: funnels, retention cohorts, paths, new and returning, feature flags, experiments, dashboards; an event log with consumers; ClickHouse | [analytics.md](analytics.md) | | count visitors, pageviews and bounces, where visits come from, the country (a proxy's header, a file of IP ranges, the time zone), browsers and devices, goals, Web Vitals | [usage.md](usage.md#the-webs-numbers) | | have an admin page: accounts, every model's rows, jobs, health, "see what they see" | [admin.md](admin.md) | | take an extension (usage, Google, admin) into a program; write one | [../extensions/README.md](../extensions/README.md#taking-one), [../extensions/README.md](../extensions/README.md#writing-one) | | say who may read the usage numbers | [usage.md](usage.md#who-may-read-it) (`usageMay`) | | see several apps' usage in one panel | [usage.md](usage.md#several-apps-one-panel) (`usageTake(batch, app)`, `app=`) | | read or write a model whose name is only known as the program runs | [models.md](models.md#models-chosen-at-run-time) | | list the accounts; say what the back end is and stands on | [back-end.md](back-end.md#passwords-from-the-programs-own-code), [back-end.md](back-end.md#what-the-back-end-is) | | keep a value current across everyone's pages | [back-end.md](back-end.md#live-values) | | record a voice clip; show how loud the microphone is | [media.md](media.md#recording-a-microphone) | | play a sound; ring; say "press to turn sound on" | [media.md](media.md#sound) | | play, pause and seek an `audio` or a `video` from the page | [media.md](media.md#audio-and-video) | | put a count in the tab's title and on the app's icon | [markup.md](markup.md#values-of-the-whole-page) | | show each upload's progress; cancel one | [models.md](models.md#several-uploads-at-once) | | send a notification | [back-end.md](back-end.md#notifications), [data.md](data.md#notifications-without-a-back-end) | | store records; query them with SQL | [data.md](data.md#db), [data.md](data.md#sql) | | declare what is kept once, and read and write it with no SQL | [models.md](models.md) | | keep records in the browser that a list follows | [models.md](models.md#local-models) | | share records between people; say who may read or change a row | [models.md](models.md#models-on-the-back-end), [models.md](models.md#rules) | | see who may do what, across every rule, `server fn` and route; find a rule written too open | [back-end.md](back-end.md#who-may-do-what) (`mote check --access`) | | say who may call a `server fn` (`requires admin`), with a rule a model's lines share; mark one open on purpose | [back-end.md](back-end.md#rules) | | limit how often something is called; slow down password guessing; know the caller's address behind a proxy | [back-end.md](back-end.md#limits) | | keep a key out of the log, and refuse to start without it | [back-end.md](back-end.md#secrets) (`secret("KEY")`) | | let support see what a user sees (act as them), safely | [back-end.md](back-end.md#acting-as-someone) (`auth.as`) | | check a signature, or a token another service signed (a JWT) | [data.md](data.md#signatures-with-a-key-pair) | | search the rows of a model by the words in them, under its rules | [models.md](models.md#full-text-search) | | show what a person just wrote before the back end has answered; dim it until it has; take it back if it is refused | [models.md](models.md#a-write-shows-at-once) (`pending(row)`, `confirmed`) | | keep what was written while offline and send it when the line is back | [models.md](models.md#a-write-shows-at-once) | | make sending a call twice safe; set how long a call may take | [back-end.md](back-end.md#a-call-is-answered-once) | | test a page on a slow, lossy or dead line | [testing.md](testing.md#testsslowproxymjs) | | do several writes as one | [models.md](models.md#atomic) | | run something whenever a row is added or changed | [models.md](models.md#in-a-server-fn-and-hooks) | | add, rename or remove a field once there is data | [models.md](models.md#changing-a-schema) | | read a file, several, or a folder the user picks; save a file | [data.md](data.md#fs) | | open a phone's camera; take many large files without reading them all | [data.md](data.md#the-camera), [data.md](data.md#files-not-read-yet) | | keep the browser from clearing what is kept; know that a disk is full | [data.md](data.md#storage-that-stays) | | take a page under a phone's notch and home bar | [markup.md](markup.md#the-screens-edges) | | read and write the clipboard | [data.md](data.md#clipboard), [events.md](events.md#the-events) (`paste`) | | make bytes, write numbers into them, read a binary file | [language.md](language.md#bytes) | | read or write a CSV or an Excel workbook; import a spreadsheet into a shape; export one | [tables.md](tables.md) | | zip, gzip, zlib, hash | [data.md](data.md#zip), [data.md](data.md#crypto) | | encrypt in the page before anything leaves it; exchange keys (X25519, ML-KEM-768); sign (Ed25519); derive a key from a password; a proof of work | [data.md](data.md#keys-of-the-pages-own) | | make an invoice or a report as a PDF; read a PDF's text; fill a PDF form; merge or split PDFs | [pdf.md](pdf.md) | | show a picture; ship an asset; use an icon | [markup.md](markup.md#pictures-and-assets), [markup.md](markup.md#icons) | | resize, crop or encode a picture | [media.md](media.md#img) | | open a phone's large photo without running out of memory | [media.md](media.md#a-photo-that-fits) | | read a TIFF, a GIF's frames, a raw file's preview, a photo's Exif | [media.md](media.md#formats), [media.md](media.md#what-a-file-says) | | keep 16 bits; convert between colour spaces | [media.md](media.md#deep-pictures), [media.md](media.md#colour) | | let the user paint; brushes, masks and layers | [media.md](media.md#paint), [media.md](media.md#brushes), [media.md](media.md#layers) | | show a chart (lines, bars, a pie, a heat map, a Sankey diagram …) | [charts.md](charts.md) | | chart a million points; zoom, pan and brush a chart; a sparkline in a table | [charts.md](charts.md#large-data), [charts.md](charts.md#interactions), [charts.md](charts.md#small-charts) | | draw on a canvas (a game, a chart of your own) | [drawing.md](drawing.md#surface-2d) | | fill with a gradient; group shapes; add a shadow | [drawing.md](drawing.md#gradients-and-patterns), [drawing.md](drawing.md#layers) | | save a drawing as a picture | [drawing.md](drawing.md#a-drawing-as-a-picture) | | take typing on a canvas (an editor of your own) | [drawing.md](drawing.md#typing-on-a-surface) | | draw with WebGL; run a picture through a shader | [drawing.md](drawing.md#surface-gl), [drawing.md](drawing.md#a-picture-through-a-shader) | | measure text; lay out a line with a font file; get a glyph's outline | [drawing.md](drawing.md#surface-2d) (`draw.measure`), [text.md](text.md#font) | | show boxes in 3D | [drawing.md](drawing.md#the-3d-canvas-canvas-boxes) | | build a 3D scene of meshes, lights and a camera | [scene.md](scene.md) | | let people talk, see each other and share a screen | [calls.md](calls.md) | | say who may join a call; set up STUN and TURN | [calls.md](calls.md#the-guard-server-call), [calls.md](calls.md#deploying) | | log from the back end; find a failure by its id | [back-end.md](back-end.md#logs), [back-end.md](back-end.md#the-calls-id) | | tell kinds of failure apart; hear every failure in one place | [back-end.md](back-end.md#when-something-fails) | | deploy: health checks, stopping cleanly, caching, a container | [back-end.md](back-end.md#health-and-stopping), [back-end.md](back-end.md#running-it), [cli.md](cli.md#what-a-build-writes-for-whoever-runs-it) | | use the camera; read a QR code or barcode | [media.md](media.md#camera), [media.md](media.md#scan) | | play, cut and export video | [media.md](media.md#vid-aud-and-reel) | | put clips on tracks; keyframe, wipe, grade; meter the sound | [media.md](media.md#a-film-clips-tracks-keys) | | match text with a pattern | [text.md](text.md#patterns) | | search text (a list the page has; for a model's rows, [models.md](models.md#full-text-search)) | [text.md](text.md#search) | | colour code; show Markdown | [text.md](text.md#highlight-codeblock-and-markdown) | | embed a code editor, a terminal, a node canvas | [widgets.md](widgets.md) | | write mail: bold, lists, links, quotes, pictures, as HTML and plain text | [kit/richtext.md](kit/richtext.md) | | measure or scroll an element | [events.md](events.md#the-element-itself) | | split a program over files; use another project's | [language.md](language.md#files-and-use), [language.md](language.md#packages) | | build, serve, check | [cli.md](cli.md) | | set my editor up: errors as I type, hover, go to definition, rename | [editor-plugin.md](editor-plugin.md#setting-an-editor-up) (`mote editor`, `mote lsp`) | | write a declaration's documentation, shown on hover | [editor-plugin.md](editor-plugin.md#comments-that-document) | | see a file's syntax tree; know where a diagnostic ends | [cli.md](cli.md#mote-tree) (`mote tree`, `mote check --json`) | | make an installable, offline app | [cli.md](cli.md#mote-build) | | build the same bytes twice, and check a folder or a site against the source | [delivery.md](delivery.md#the-same-build-every-time) (`mote build --check`, `build.txt`) | | show which build the app is | [delivery.md](delivery.md#buildtxt-and-the-builds-hash) (`app.build()`) | | send the page with a strict Content-Security-Policy and the other security headers | [delivery.md](delivery.md#the-strict-policy) (`policy=strict`, `connect=`) | | keep an installed app on its build until the person agrees to a new one | [delivery.md](delivery.md#updates-that-ask) (`update=ask`) | | make a page agents can use | [agents.md](agents.md) | | test a page | [testing.md](testing.md#writing-a-test) | | test the back end: rules, hooks, `server fn`s, jobs, with the clock set | [testing.md](testing.md#tests-in-the-program) | | do work later, so that it is not lost (mail, a webhook out), or at a time of day | [back-end.md](back-end.md#later-job-fn), [back-end.md](back-end.md#at-a-time-of-day) | | change the rows already there when the schema changes | [models.md](models.md#a-change-to-the-data-itself-migrate) | | show a fallback where part of a page fails (a chart given bad data, a derive that throws), with a way to try again | [markup.md](markup.md#try) (`try` / `else err` / `again`) | | hear every failure of the page in one place; know what kind it was and where it was written | [back-end.md](back-end.md#when-something-fails) (`on failure(f)`: `f.kind`, `f.words`, `f.at`) | | say exactly which words a person sees for each kind of failure (offline, sign in, refused, limited…) | [back-end.md](back-end.md#the-words-of-each-kind) | | see `.mote` lines in a stack, not the built JavaScript | [back-end.md](back-end.md#where-a-fault-was-written) | | add a row or change it if it is there; add one to a count | [models.md](models.md#put-and-inc) (`T.put`, `inc`) | | count rows by a field; sum a field by another | [models.md](models.md#rows-taken-together) (`T.count(f, {by})`, `T.sum`) | | read a setting in a rule (an admins' list in the environment) | [back-end.md](back-end.md#a-rule-that-reads-a-setting) (`setting`, `setting.list`) | | know what a write sends to the pages that follow a list | [models.md](models.md#what-a-write-sends-a-page) | | run something every night, or at 9 on Mondays | [back-end.md](back-end.md#at-a-time-of-day) (`server at`) | | queue work that must not be lost, with retries | [back-end.md](back-end.md#later-job-fn) (`job fn`, `.in`, `.at`, `unique`) | | take backups of the database while it runs; restore one | [back-end.md](back-end.md#snapshots) (`MOTE_BACKUP`, `mote restore`) | | share one database between two apps | [back-end.md](back-end.md#several-apps-one-database) (`MOTE_SQL`), [back-end.md](back-end.md#readonly-a-model-an-app-only-reads) | | check two programs that work together agree (their calls, their models) | [cli.md](cli.md#mote-check) (`--against`) | | send mail | [back-end.md](back-end.md#sending-mail) | | find code that is slow on the back end (a query in a loop) | [cli.md](cli.md#mote-check) (`--perf`) | | say, in a package, a fn the program that takes it must declare | [language.md](language.md#what-a-package-wants-of-its-taker) (`wants fn`) | | test the back end with settings of its own | [testing.md](testing.md#settings-for-one-test) (`given env`) | | understand a compiler message | [cli.md](cli.md#the-ids) | | add a namespace or a call to Mote | [internals.md](internals.md#adding-a-namespace-a-worked-example) | | add a battery | [internals.md](internals.md#batteries) | | add a runtime part | [internals.md](internals.md#adding-a-runtime-part) | | add a tag, an event, a widget, a kit component | [internals.md](internals.md#adding-other-things) | | write runtime code | [../runtime/README.md](../runtime/README.md) | ## Namespaces Every namespace of the standard library, and its page. "Waits" means the call leaves the page: it can fail, must meet `else` or `?`, and cannot go in a derive or a binding. | Namespace | What | Waits | In a `server fn` | Page | |---|---|---|---|---| | `net` | requests over the network; `send` (any status), `stream` (pieces, events) | yes | yes | [data.md](data.md#net) | | `proc` | other programs: `run`, `start` | yes | only there | [back-end.md](back-end.md#other-programs) | | `tcp` | a connection below HTTP: `open` (plain, TLS, STARTTLS, a proxy), `take` (a pool), `pools` | yes | only there | [back-end.md](back-end.md#connections-of-its-own) | | `ws` | a WebSocket the back end opens: `open` | yes | only there | [back-end.md](back-end.md#a-websocket-from-the-back-end) | | `webhook` | another service's webhook: `check` (its signature, over the bytes sent), `once` (each event once) | yes | only there | [back-end.md](back-end.md#webhooks) | | `db` | keys to values, in IndexedDB; `persist`, `persisted`, `room`: whether the site's data stays, and how much fits | yes | no | [data.md](data.md#db) | | `sql` | SQLite | yes | yes | [data.md](data.md#sql) | | `fs` | private files; `open` (a reader, a piece at a time) and `writer`; pick (one, many, a folder) and save; `folder` | yes | yes (not pick, save); `folder` only there | [data.md](data.md#fs), [back-end.md](back-end.md#folders) | | `clipboard` | the system's clipboard: `text`, `image`, `put` | yes | no | [data.md](data.md#clipboard) | | `store` | `localStorage` | no | no | [data.md](data.md#persist-and-store) | | `crypto` | `hash` (SHA-2, SHA-3, BLAKE2b), `hmac`, `hkdf`, `pbkdf2`, `argon2id`, `random`, `randomBytes`, `equal`; a page's own keys: `aes.seal` and `open` (AES-256-GCM), `x25519`, `ed25519`, `mlkem768`, `pow` | yes (`random`, `randomBytes`, `equal`, `crc32`: no) | yes, all of these; `sign`, `verify`, `seal`, `open`, `jwt` only there | [data.md](data.md#crypto), [data.md](data.md#keys-of-the-pages-own) | | `zip` | gzip, deflate, zlib, .zip files; `entries`, `open`, `gunzipStream` for large ones, a piece at a time | yes | yes | [data.md](data.md#zip) | | `tar` | a .tar (a .tgz through `zip.gunzipStream`), an entry at a time: `entries` | yes | yes | [data.md](data.md#archives) | | `csv` | CSV read (typed, or a piece at a time with `open`) and written | yes (`write`: no) | yes | [tables.md](tables.md#csv) | | `xlsx` | Excel workbooks read and written | yes | yes | [tables.md](tables.md#xlsx) | | `files` | a model's files: `upload`, `sending` (the page), `keep`, `bytes`, `path` (the back end); `files.progress` | yes (`progress`, `sending`: no) | `keep`, `bytes`, `path` | [models.md](models.md#files) | | `bytes` | bytes from text, hex, base64; `new`, `of`, `join` | no (`hex`, `base64` can fail) | yes | [language.md](language.md#bytes) | | `img` | picture codecs and edits; `decode` (to `fit`), `info`, `frames`, `depth`, `convert` | yes | yes (Mote's own codecs) | [media.md](media.md#img) | | `paint` | pictures that are drawn on | no | no | [media.md](media.md#paint) | | `scan` | QR codes and barcodes | yes | no | [media.md](media.md#scan) | | `cam` | the camera's frame and error | `shot`: yes | no | [media.md](media.md#camera) | | `vid`, `aud` | video and sound (`vid.progress`, `vid.levels`: no) | yes | no | [media.md](media.md#vid-aud-and-reel) | | `speech`, `mic` | speech in and out, microphones; `mic.record`, `mic.meter` (a recording's `stop`: waits; its `pause`, `resume`, `cancel`: no) | yes | no | [media.md](media.md#speech-and-microphones) | | `sound` | a sound with no element: `play`, `stop`; `sound.ready`, `sound.error` | no | no | [media.md](media.md#sound) | | `rtc` | calls between browsers: `join`, `devices`; a `call`'s own `mute`, `camera`, `share`, `use`, `send`, `stats`, `leave` | yes (`send`, `leave`: no) | no (`server call` is its guard) | [calls.md](calls.md) | | `draw` | the 2D pen of a `surface`; `measure`, `read`, `picture` | no | no | [drawing.md](drawing.md#surface-2d) | | `gl` | the WebGL pen of a `surface gl`; `pen`, `image`, `filter` | no | no | [drawing.md](drawing.md#surface-gl) | | `three` | records for `canvas scene=` | no | no | [scene.md](scene.md) | | `re` | patterns | no | yes | [text.md](text.md#patterns) | | `richtext` | a rich text document as mail: `html` (inline styles), `text`; `from` text, `quote`, `apply` an edit's operations, `pictures` | no | yes (and in an `off fn`) | [kit/richtext.md](kit/richtext.md#mail-of-it) | | `search` | full-text search | yes | yes | [text.md](text.md#search) | | `html` | HTML from elsewhere held to an allow-list (`clean`) or as plain text (`text`); the `htmlframe` element shows it | yes | yes | [text.md](text.md#html) | | `syntax` | text to a tree | yes | yes | [text.md](text.md#syntax) | | `font` | font files: facts, layout, outlines, subsets | yes | yes (not `use`) | [text.md](text.md#font) | | `pdf` | PDF files: `make` from parts (`text`, `table`, `image`, …), `info`, `read`, `words`, `images`, `fields`, `fill`, `flatten`, `merge`, `pages`, `rotate`, `stamp` | yes (the parts: no) | yes | [pdf.md](pdf.md) | | `app` | the app itself: `build` (the build's hash); in a page of an app that says `update=ask`, `check` and `update`; on the back end `info`, `access` | yes | `build`, `info`, `access` | [delivery.md](delivery.md), [back-end.md](back-end.md#what-the-back-end-is) | | `auth` | signing in | yes | `me` | [back-end.md](back-end.md#signing-in) | | `notify`, `push` | notifications: `allowed`, `enable`, `devices`, `inbox`; to some devices, with data | yes | `notify.send`, `notify.devices` | [back-end.md](back-end.md#notifications), [data.md](data.md#notifications-without-a-back-end) | | `el` | an element held through `ref=`; a field's caret and selection | no | no | [events.md](events.md#the-element-itself), [events.md](events.md#a-fields-caret-and-selection) | | `keys` | modifier keys held now | no | no | [events.md](events.md#keys) | | `screen` | window width class, size, scheme; `print`, `fullscreen`, `full`; `visible`, `focused`, `idle(ms)` | no | no | [markup.md](markup.md#conditional-styles), [markup.md](markup.md#in-front-and-at-it) | | `route` | the current address: `path`, `url`, `origin`, `link(path)` | no | no (`origin` only) | [markup.md](markup.md#routes) | | `time` | a moment in a zone and a language: `clock`, `date`, `words`; `parts`, `of`, `add`, `next`, `startOf`, `endOf`; `stamp`, `read`; `zone`, `zones`, `weekStart` | no | yes, the zone said (not `zone`) | [language.md](language.md#time) | A `model` is not a namespace: its name is, with the operations of [models.md](models.md#the-operations) (`Note.find(…)`, `Note.add(…)`); each waits, a `model`'s in a `server fn` too, a `local model`'s only in the page. Built-in calls with no namespace (`uid`, `now`, `log`, `go`, `back`, `toast`, `copy`, `focus`, `scroll`, `fail`, `pending`, `failed`, `failure`, `refresh`, `asset`, `scheme`, `bytes`; and on the back end `env`, `changed`, `emit`, `emitTo`): [language.md](language.md#built-in) and the pages above. ## Checking these docs ```sh docs/check.sh ``` extracts every fenced `mote` block that starts with `// docs: whole` and runs `mote check` on it ([testing.md](testing.md#docschecksh)). ## Adding to these docs > **Where things go** (for whoever adds to these docs, or merges a branch > that added lines to the old one-page card): > > - The card is a summary now. A new call does **not** get a line there > unless most programs will want it. It goes in its **topic page**, under > the heading for its namespace or element, and gets a row in the > [namespace table](#namespaces) above if the namespace is new. > - Where each kind of thing lives: `bytes` → [language.md](language.md#bytes) · > events, keys, dragging → [events.md](events.md) · `watch`, timers, tasks > → [reactivity.md](reactivity.md) · `draw`, `gl`, `surface`, the > 3D canvas → [drawing.md](drawing.md) · `paint`, `img` and picture > formats, `vid`, `aud`, `reel`, `camera`, `scan` → [media.md](media.md) · > files a page names → [markup.md](markup.md#pictures-and-assets) · > `screen`, print, the whole screen → [markup.md](markup.md#conditional-styles) · > `rtc`, a call, `video of=`, `server call` → [calls.md](calls.md) · > storage, the network, the clipboard → [data.md](data.md) · the back end → > [back-end.md](back-end.md) · `model`, its operations, rules and > `schema.lock` → [models.md](models.md) · `re`, `search`, `syntax`, `font` → [text.md](text.md) · `pdf` → [pdf.md](pdf.md) · > a new element the runtime builds → [widgets.md](widgets.md) · a kit > component → [kit.md](kit.md) and its page under `kit/`. > - Every topic page has the same headings: the opening example, *Mental > model*, the subject's sections, *Pitfalls*, *Where a new call goes* > (where it applies), *In the source*. Put a call in its section's table, > add what is refused and any pitfall, and name the source file. > - The 3D canvas's scene API (`three.*`, `canvas scene=`) has its own > page, [scene.md](scene.md), and a brief section in > [drawing.md](drawing.md#the-3d-canvas-canvas-scene). > - An example that can stand alone starts with `// docs: whole` and must > pass [`docs/check.sh`](check.sh). Run it before finishing. > - Do not describe a plan as if it were built. If it is not in the > compiler in this checkout, it is not in these pages. # Mote card The language in brief; everything here compiles today. The whole of it is in `docs/` of the Mote repository and at https://motelang.com: start at docs/README.md (a map, and a "how do I…" index). Each section names its page. Every component, live with its source: https://playground.motelang.com ```mote // docs: whole shape Todo id: string title: string done: bool state todos: Todo[] = [] persist state draft = "" derive left = todos.filter(t => !t.done).length action add if draft.trim() == "" return todos.push({id: uid(), title: draft, done: false}) draft = "" column gap=8 padding=16 row gap=8 input value=draft placeholder="What next?" submit=add button "Add" press=add for t in todos key=t.id row gap=8 align-items=center input type=checkbox checked=t.done text t.title color=(t.done ? "dim" : "fg") button "×" press={todos.remove(t)} text `${left} left` color=dim ``` Three rules: only an `action` or a `{…}` handler writes state (a `fn` is pure) · a call that can fail meets `else` or `?` at once · in markup a space ends a value: anything with an operator goes in parentheses. ## Commands → docs/cli.md ```text mote dev app.mote serve it, reload on save mote check app.mote [--json] what is wrong, and the fix mote test app.mote run its `test` blocks (the back end's rules, hooks, fns, jobs): no browser docs/testing.md mote build app.mote dist/: installable, offline mote build app.mote --single one HTML file (opens from file://) a battery (zip img pdf syntax re sql charts …) is a file, assets/..wasm, fetched at its first call; --single holds them inside mote serve dist serve a built directory mote card this card mote editor vscode set an editor up (cursor neovim helix …; `mote lsp` is its server) docs/editor-plugin.md mote tree app.mote the syntax tree as written, with where each part starts and ends (--json) ``` In a terminal `mote check` shows the line and underlines what is wrong; `--json` says `end_line` `end_col` too. A file is an app: declarations and markup. Blocks are indented with spaces. `// comment`: the lines right above a declaration (a field too) are its documentation, shown on hover. Beside the entry: `public/` ships whole · `assets/` ships what is named · `icon.svg` is the app's icon. ## Declarations → docs/language.md ```text state n = 0 a value the page shows; `persist` keeps it in localStorage state todos: Todo[] = [] persist an empty list or `none` needs its type derive left = todos.filter(t => !t.done).length follows what it reads; cannot be assigned · `derive row: json = got?.row` with a type action add / action set(v: string) statements; may write state `assume` + a block of assignments in an action: done at once, taken back if the action fails after it (a `server fn` says no); `+=` by as much, `=` only if nothing wrote since · model writes need none: they show at once reactivity.md#assume fn total(xs: number[]) = xs.length pure; or `fn f(a: T): R` with a block · `T?` params at the end may be left out (none) wasm fn sum(xs: number[]): number experimental: it and the plain fns it calls as one WebAssembly module (numbers bools shapes lists; same answers as JavaScript, which runs until it is ready) language.md#wasm-fn shape Todo `field: type` lines indented under it component Badge(label: string, tone: string?) declarations and markup indented under it use "./parts.mote" that file's declarations · `use "pkg:name/file.mote"` with mote.toml (the program's, first, from any file) wants fn usageMay(): bool in a package: a fn the program is to declare (H166 at its entry, with the line) · `= expr`: a default it may replace a name is declared once in the whole program (H022 names both places) app "Todos" accent=#0a84ff title and accent · scheme=dark (or light) · lang="de" ( with no words) · toasts="top right" · agents=off edges=cover (under a phone's notch and home bar: padding-bottom="max(16px, env(safe-area-inset-bottom))") render=ahead (the back end sends each page drawn, with its data: back-end.md#a-page-drawn-ahead; with no back end of its own, `mote build` writes `/` and each written-out route drawn, as files) writes=confirmed (a model's writes from the page wait) · timeout=30000 (ms a call may take; unsaid: no limit) policy=strict connect="https://api.x.com wss://relay.x.com" (a Content-Security-Policy made from the build: scripts and styles by hash, no unsafe-inline, no unsafe-eval; and HSTS, Referrer-Policy, COOP, Permissions-Policy) · update=ask (a new build waits: on app.update(u: {build: string, forced: bool}) · app.check() · app.update()) · app.build() the build's hash, the SHA-256 of dist/build.txt · the same source and compiler give the same dist/: mote build app.mote --check dist → docs/delivery.md installed: id="mail" scope="/" share="text links image/* .eml" handles="mailto" opens=".eml" shortcuts="New: #/compose; Inbox: #/inbox" · on app.handed(h: {how, title, text, url, files: picked[]}) app "Shop" "Cabinets drawn by you" a second string is the description · a shared link fills itself in (title, Open Graph, Twitter): share.png (or .jpg, og.png) beside the entry or in public/ is the picture, else the icon (small card) image="cover.png" (or an address; never SVG: H169) · url="https://shop.example" for a page no back end serves; a back end writes whole addresses from Host (MOTE_PROXY: the proxy's; MOTE_URL) markup.md ``` ## Types and logic → docs/language.md ```text string number bool none bytes json · T[] · T? · a shape's name · {x: number} · image sheet video sound font ``` Inferred except parameters, shape fields, and an empty or `none` first value. Structural. `json` fits anything, unchecked. No unions: `T?` is the one "or", and must be settled before `.` or arithmetic: `x?.f` · `x ?? d` · `if x …` · `if x == none return` (or `fail("…")?`, `continue`, `break`: the rest of the block knows it is there). `find() pop() at()` give `T?`. ```text let x = e · x = e, += -= *= /= · if c … else if … else … · `if c stmt else stmt` on one line · match x (arms indented) a block declares a name once (a second `let x`, or one of a parameter: H022; `x = e` changes it); an inner block may hide an outer name for x in xs · for x, i in xs · while c · return e · break · continue · x => e · (a, b) => e · c ? a : b · a ?? b · a?.b & | ^ ~ << >> >>> (32-bit; tighter than == and <, looser than + -: `x & 1 == 0` is `(x & 1) == 0`) · 0xff == and != are strict · none (no null, undefined) · `text ${e}` · r"\d+" raw · [a, ...b] · {k: v, k, ...o} writes: assign state, or change it in place (push pop shift unshift splice sort reverse fill remove(x), t.done = true) built in: uid() now() log(x) toast("Saved") (three show, the rest wait) copy(text) go("/path") back() forward() time.clock(now()) time.date(now()) share() the share sheet with this page (its route's title, description, address) · share({title, text, url, files}) · gives "shared" "cancelled" "copied" "shown": no sheet, the link is copied and a toast says so; never fails data.md focus("id") (the caret stays; focus("id", true) selects) · scroll("id", "end") · close() by id these (and el.focus el.scrollTo el.select) wait for what the action itself just made appear; `drawn()` waits for the page to show what was written (then read el.rect …) · el.from() {id, row, data}: where the event being handled happened (row: its `for` row's key) · el.at(x, y) the same at a point · el.row("list", key) that row's element scroll("msg-42", {inside: "list", block: "center", behavior: "instant"}) brings it into view (start center end nearest) plus JavaScript's own methods, and Math JSON Date Number String Object Array (there is no `new`) words words "en" + lines `hello = "Hello, {name}!"`, `items = {zero: "…", one: "{n} item", other: "{n} items"}` (the first is the source; a later language's missing keys show the first's: H251) · words "de" from "./de.words" · t("hello", {name}) checked against the keys and their {names} (H248) · words.lang words.langs words.choose("de") (kept; follows) · screen.lang fmt fmt.number(n, {lang, digits, exact, compact, grouping}) · fmt.currency(n, "EUR", {sign: "code"}) · fmt.percent(0.25) fmt.list(xs, {type: "or"}) · fmt.plural(n, {one: "{n} file", other: "{n} files"}) · in words.lang unless lang: said → docs/words.md time time.clock(at, {zone: "Asia/Tokyo", lang: "de", hours: 24}) · time.date(at, {zone, lang, style: "long"}) (short medium long full numeric month weekday iso) · time.words(at, {from: tick}) "in 20 minutes", "yesterday" · time.zone() · time.zones() let p = time.parts(at, zone?) {year, month, day, hour, minute, second, weekday, offset} · time.of({...p, day: p.day + 1, hour: 9}, zone?) time.add(at, {days: 1}, zone?) · time.startOf(at, "week", {zone, first: 1}) · time.endOf · time.stamp(at) "2026-11-12T14:22" · time.read(stamp)? · time.weekStart(lang?) · on the back end the zone is said (there is no reader) → docs/language.md#time time.next({hour: 9, minute: 0, weekday?}, zone?, from?): the next moment a clock there reads so, right across a change of the clocks ``` ## A call that can fail → docs/language.md Everything that leaves the page can fail, and none says async or await: the compiler waits for it. ```text x else fallback the fallback on failure; `else err => …` gets the message x? pass the failure on: in a fn, the fn can now fail; in an action, the action stops · `c ? a()? : b()?` pending(a) failed(a) failure(a) of an action or a resource: `button "Save" press=save disabled=pending(save)` pending(row) a model's row with a write the back end has not answered: opacity=(pending(m) ? 0.5 : 1) let xs: Post[] = net.get(url)? json takes the type its `let` gives it fail("out of stock")? a failure made on purpose: failure(action) has the words; only a fault is logged fail("out of stock", {kind: "stock", data: {sku}})? with a kind and data · a failure in text is its words, and also: err.kind err.id err.data err.where err.words (under `else err =>`) · failure(save)?.kind … kind: offline signin refused invalid toobig full (no room on the device) memory (img) limited (429: err.data.retryAfter, seconds) timeout taken (a key or a unique value another row has: err.data {model, fields}; add set put atomic auth.create, SQLite and Postgres, and in the page) fault said, or the program's own · id: the call's, as the back end's log has it x else err => (err.kind == "taken" ? none : err?) err? in the handler: the failure passed on as it came (kind, data; a fault stays a fault); fail(err)? makes a "said" of its words · back-end.md#a-create-that-loses-taken on failure(f) + a block, top level: every failure nothing else heard (an action's nobody reads with failure(a), a resource's with no else, a live value's, an uncaught error); f: Failure {words, kind, id, data, where, at} f.at: where a fault of the page's own code was written ("app.mote:12"), as its back end says (`app … faults=off`) ``` extern js "./glue.js" + lines `fn confetti(count: number): none`: the file's exports, typed; every call waits and can fail, and what comes back is checked against its type · `off` after the file: also in a worker · a `server fn` runs it in Bun · `el: element` hands a ref (the file hears `mote:gone` when it leaves) · extern script "https://…" integrity="…" another site's script in the head · a LAST RESORT (a battery, the kit, an extension, net.* to an HTTP API, proc.run come first); build and check list each as "outside what is checked" · docs/js.md Only actions, fns, handlers, tasks and resources can wait. A binding or a `=>` cannot: use a resource. But `x => upload(x)` (nothing but a call of an action that waits) begins it and gives none: for callbacks (forEach, a handler given to a json value). `wait(p)?` waits for a promise a json value holds: `let t = wait(widget.value()) else ""` (widget: json). ## Markup → docs/markup.md ```text tag text? name=value… children indented. Text is a string, a template, or a name. tags view box row column grid text image link icon, HTML's own (button input h1 ul li …), Components value "string" · 12 · 12px 50% 1fr · #0a84ff · center · t.title · draft.trim() · (any expression) · {a handler} style any CSS property by name; a bare number is px (not on flex opacity z-index line-height font-weight …) roles fg bg dim card line accent danger ok warn follow light and dark; computed: color=(done ? "dim" : "fg") attrs HTML's own: class for id href type placeholder aria-* data-*; a lone word is a boolean: `input autofocus` · `AdminPanel trusted` (a bool prop) bind `input value=draft`, `input type=checkbox checked=t.done` write back when the value is state states hover · active · focus · disabled · checked · phone · tablet · desktop · dark · light · still: a child line of styles button "Save" background=accent hover opacity=0.8 a value may be worked out: hover background=skin.hover mark a parent `group`; then `in hover opacity=1` on a child styles it while the parent is hovered control if c / else if c / else · for t in todos key=t.id · for t, i in xs · match x · let p = e · let xs: string[] = row.data.xs ?? [] long for r in rows key=r.id virtual (measured) · virtual=32 (every row 32px: a million rows) · sticky=r.head (a group's head stays) only the rows in view are drawn, in the nearest box that scrolls (give it a height); across in a `row`; lanes in a grid; the row at the top stays put; a row's own state goes when it is scrolled away (keep it by key); find-in-page sees drawn rows a model's rows: `live xs = T.find(f, {order: "at desc", window: 200}) else []` + `for x in xs key=x?.id virtual=36` (below) scroll("list", {row: key}) · {index: n} · el.inView("list", key) · el.shown("list") {first, last, count} markup.md#long-lists try + what may fail to draw, then `else err` + what stands there instead (err: a Failure; `again` builds it once more): catches a throw while built or updated, a derive's failure, a resource's or live value's with no else; not a handler's routes route "/planet/:id" (id is in scope) · route "*" · link "About" href="/about" · go("/about") (a whole address leaves the page) · route.path a program with `route` blocks, or that reads route.path or calls go/back, routes in the page: there href="/x" is in-app (#/x), but for a whole address, `download`, `target=`, and /file/… route.origin · route.url · route.link("/join/abc") the whole address of a path, for someone else to open route "/pricing" title="Pricing" description="…" image="p.png": the tab follows it; the back end answers /pricing with its own tags (strings written out: H172) · a page no back end serves: the app's (routes are after #) route.query("q") (reactive, or none) · route.setQuery({q: text, page: none}) (no new history entry) app "X" routes=paths: /planet/mars with the History API (back, forward, scroll put back, href="#id" scrolls); the host answers every path with the page (back end, mote dev/serve do; a build writes 404.html) · base="/shop/" below a path · from file:// routes stay after # · root unsaved=(dirty) (or the words): beforeunload, and in-app moves ask with routes=paths (else H355): route.fragment what stands after # (reactive) · route.setFragment("x") ("": none; no new entry) · route.takeFragment() read and taken out of the address and the history before any other script of the page runs, handed over once: for a secret another site hands over with go("https://there.example/#…") markup.md#the-fragment lines=2 (two lines, then an ellipsis) · -webkit-line-clamp=3 (a browser's own property) · on a style a word that names a fn or an action is CSS's word (flex-wrap=wrap) · preload=none decoding=async fetchpriority=low inputmode=numeric enterkeyhint=send · an attribute whose value is none is not written · a popover is its element's next sibling other image "hero.jpg" (assets/) · icon "camera" size=20 · `icon glyph` for a value, its names written `icon("camera")` where they are made (only those ship) · popover and tip under an element · dialog open=flag · row glass net.online: a reactive bool, false with no network (not asked of a page on localhost) or while the line to the back end is down (it reopens itself); a call that finds nobody there fails (`else`, failure(action)) and logs nothing → docs/back-end.md window screen.visible (in front) · screen.focused (has the keyboard) · screen.idle(60000) (nobody at it): reactive bools screen.awake(true)? keeps the screen on (taken again whenever the page is seen) · screen.awake(false)? screen.filesOver (files held over the window; a file let go outside a `drop=` never leaves the page) · pastefiles=attach: a paste that carries files, in a field inside too; the field keeps the words page root density=density zoom=zoom var-brand=brand motion="less" values of the whole page, from state, at the top of any file: a CSS property styles the root · var-brand is --brand, read as color="var(--brand)" (var-accent re-colours a role) · any other name is asked about by a child line in any file: `in root[density=compact] padding=2`, `in root[contrast] …` motion: "less" | "full" | "system"; the system's wish for less motion is honoured unsaid; `still …` lines, screen.still root lang=locale dir=rtl translate=no: HTML's own on the root; is root lang= while said, else words.lang, else app lang= root title=(n > 0 ? `(${n}) Inbox` : "") badge=n · in an action: title("…") ("" is the app's own) · badge(0) clears root description=(page.blurb): what the page says of itself; with render=ahead it and the title are in the head of the page sent close() in a handler or action closes the popover or dialog the reader is in · close("id") that one ``` Components: `Badge label=t.title`; a `T?` prop may be left out; an event's name is a handler (`Go press=save`, inside `button press=press`); a prop the component assigns is written back (`Switch on=dark`); anything that is not a prop goes on its first element (the first inside it, if that one is a `form display=contents`); children go where it writes `slot`. `slot "bar.tools" row=r` is a place any file may draw in: `fill "bar.tools"(row: Row)` + markup, at the top of a file (a component with no name: props from what the slot gives; every fill is drawn, in `use` order). ## Events → docs/events.md ```text press input change submit focus blur key keyup dblclick contextmenu scroll drop paste pastefiles wheel pinch resized contents seen seen={if it.visible more()} seen-margin=600: into view and out of it, {visible, ratio}; the margin counts as in view pointer events hand {x, y, …, id, type, primary}: `id` tells two fingers apart · pinch={zoom = it.scale} hands {scale, x, y, done} pointerdown pointerup pointermove pointercancel pointerenter pointerleave · dropped over (things carried from a `drag=`) pointerdown= with pointermove= keeps the pointer, and each press gets exactly one pointerup or pointercancel (a touch taken to scroll, the page hidden, the element gone): end the drag on both. Say touch-action=none on what a finger drags wheel={x += it.dx} wheels="x": only that way of the wheel ("y": up and down), the other is the page's · screen.keyboard: px of the window under a keyboard swipe={x = it.tx + it.dx} swipes="y": one finger along it, {dx, dy, vx, vy, phase: "start" "move" "end" "cancel", tx, ty, width, height, type}; swipes= "x" (unsaid) "y" "left" "right" "up" "down" or none. Presses inside still work, the page scrolls the other way press: the innermost thing pressed hears it (a button in a `row press=` does not press the row); presses= hears all press=add · press=remove(t.id) · press={n += 1; open = false} an action, a call, or a block input/change hand over the field's value (a checkbox: its bool) · key: the key's name · pointer*: {x, y, …} in a block, `it` is what was handed over: `input={draft = it.trim()}` · `pointerdown={at = it.x}` `change=set` with `action set(on: bool)` · `key=k keys="mod+s tab"` takes those chords for itself typed in a field inside it, `key=` hears only Escape and the chords with a modifier named in keys= (mod+k) shortcut "mod+k" openSearch · shortcut "mod+1" pick(1) · shortcut "escape" {open = false} (or statements indented under it) a line at the top of any file, in a component, under an `if` or a route (live while that is shown): heard wherever the keyboard is, and when it is nowhere; the chords are `keys=`'s ("mod+z mod+shift+z": several). While a field has the caret only Escape is heard, unless the line ends in `fields`: shortcut "mod+s" save fields. An element whose `keys=` names the chord hears it instead. Under a dialog or a popover: heard while that is open, before the page's own line for the chord keys.shift keys.alt keys.ctrl keys.meta keys.mod (⌘ or Ctrl): held now; pointer events say them too `row drag=t.id kind="todo"` is carried; `row dropped=move(t.id) takes="todo"` receives {value, kind, x, y, …}; child lines `dragging …` and `over …` (`over top …`) style them meanwhile state box: element? = none, then `ref=box`: el.width(box) el.scrollTo(box, top) el.focus(box) el.rect(box) {x, y, width, height} el.transform(box) {tx, ty, sx, sy}: its translate and scale now, mid-transition too every el.… also takes an id (another component's field: el.select("composer", 0)) · el.rect(row, list): its place in the list a field's caret: el.selection(box) {start, end, text} · el.select(box, start, end?) · el.replace(box, start, end, words) (as typing: undo, input=, the bound state) · el.caret(box, at?) {x, y, height} in the window ``` ## When things run → docs/reactivity.md ```text resource posts: Post[] = net.get(`/api?tag=${tag}`) else [] loaded in the background, again when the state its call reads changes; `else` is its value until then and on failure. pending(posts) failure(posts) refresh(posts) task statements that run when the page opens; `task load` is also an action: load() every 1000 / after 500 statements on a timer watch active statements that run after a value changes (never at the start); may not write what it watches task, every, after, watch under an `if` or a route start and stop with it ``` A binding re-runs when state it read changes; nothing else re-renders. A fn that loops and uses only its parameters runs in a worker when an action calls it (`main fn` keeps it on the page, `off fn` sends it). `action preview newest` (or `task load newest`): called again while it waits, the earlier run ends at its wait: nothing after it is done, no `else`, no failure; its worker or call is stopped. What it wrote before the wait stays. Said once: `fns main` (or `off`, `auto`) at the top of a file, before its first fn, for the plain fns below it · mote.toml: `fns = "main"` at its top for the project's own files, and `[fns]` + `engine = "main"` for a package. ## A back end → docs/back-end.md ```mote // docs: whole state job = "door" state price = 0 fn priceOf(job: string): number = job == "door" ? 4175 : 0 server fn quote(job: string): number requires anyone if priceOf(job) == 0 fail("no such job")? return priceOf(job) action ask price = quote(job)? button "Quote" press=ask text `${price} ${failure(ask) ?? ""}` ``` `server fn` runs on Bun; the page calls it by name, as a call that waits and can fail. Its parameters need types (they are checked on arrival). It cannot read the page's state (a `derive` written out whole, `derive most = 50`, it can). A fn only it uses is not in the page. `requires` says who may call it (below: `anyone`, `signedIn`, a rule). It has sql, fs, net, proc, tcp, ws, env("KEY"), route.origin (where the caller reached it), crypto.hash, re, search, syntax. `mote build` writes server/main.js: `bun dist/server/main.js --port 4870`. `mote dev` runs both. Also: auth.signUp/signIn/signOut/me/changePassword(old, new) and `requires signedIn` · `server live fn` with `live x = f(a) else []` and `changed("f", a)` · `emit` and `on name(e: {…})` · notify.send(userId, {title, body, url}, {data, only: "desk" | "phone" | [device ids], tag, silent, renotify}?) · in the page notify.enable() notify.disable() notify.devices() [{id, kind, here}] notify.kind() notify.inbox() notify.read(id) · `on notified(n: {title: string, data: {…}})` · `on notify.opened(n: {url: string, data: json, action: string})`: a notification was pressed (action: its button's id, or ""). `on push.received(p: {data: {sealed: string}})` in the service worker, no page open: db, crypto, notify.show, server fns; nothing shown → "Something new". ```text auth.find(email)? {id, email}? · auth.setPassword(userId, password, {keepSessions})? · auth.signInAs(userId)? · auth.signOutAll(userId)? in a `server fn` only, and unchecked: that fn checks who may (a token kept hashed, a role) auth.create(email)? {id, email}: an account with no password (no sign-in by one until `setPassword`) · auth.setEmail(userId, email)? · auth.create()? an account with no address either (email "", `me.email` none in a rule; any number of them) · auth.setEmail(userId, none)? · auth.limit(key)? first in a sign-in fn of the program's own: its tries counted as auth.signIn's are, in the same buckets · auth.verified(userId)? bool: the address was shown to be theirs, which only the program says: auth.setVerified(userId, yes?)? use "pkg:google/google.mote" · GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET · GoogleButton (or press=googleSignIn): Continue with Google, into the same accounts and sessions; by Google's `sub`; `fn googleMay(who: OidcWho): bool` (false or fail) says who may not → docs/google.md use "pkg:passkey/passkey.mote" · press=passkeyAdd press=passkeySignIn · passkeyCheck (a second factor) · passkeyList()? [{id, name, aaguid, backup…}] · the program may say: fn passkeyMax(user: string): number (how many an account) · fn passkeyPrf(): bool · fn passkeyAttestation(): string (checked: packed, tpm, android-key, fido-u2f, apple) · fn passkeyRoots(aaguid: string): string[] (PEM or folders) · fn passkeyMay(about: PasskeyAbout): bool (about.attested, about.attestation {fmt, trust, root, …}, backup) · security keys only: about.attested && !about.backup · use "pkg:passkey/metadata.mote": passkeyMdsLoad(blob, root)? passkeyMdsRoots(aaguid)? (the FIDO Metadata Service's BLOB, checked up to the root the program pins) second-factor.md#passkeys page: passkey.create(options)? {id, clientData, attestation, transports, authenticator, aaguid, attachment, prf {enabled, first?, second?}} · passkey.get(options)? {id, clientData, authenticator, signature, userHandle, attachment, prf {first?, second?}} · passkey.supported() · passkey.prfSupported()? · options are WebAuthn's, binary as base64url or bytes; no `server fn` needed (challenge, rp, user.id default) · extensions: {prf: {eval: {first: salt}}} or {prf: {evalByCredential: {[id]: {first}}}}: prf.first is 32 secret bytes, the same for the same passkey and salt, not enumerable (never sent, logged or kept by accident) second-factor.md#a-key-from-a-passkey-the-prf-extension auth.list({search, after, limit})? {rows: [{id, email, made, sessions}], total, next} · auth.sessions(userId)? {who, sessions, actedAs, actingAs}: likewise models.list()? · models.of(name).find(f, o)? (past the rules) · models.of(name).as(me).set(key, changes)? (under them): a model named as the program runs, rows as json; get one find count has search searchCount add set del · app.info()? {name, build, started, data, snapshots, settings…} · app.access()? all the back end's alone (H160, H161): who may is the `requires` of the fn that says them models.md#models-chosen-at-run-time rule member(channel: id) = exists(Member, {channel: channel, who: me}) a named test, in the language of a model's rules; rule admin = exists(Member, {who: me, role: "admin"}) it may name other rules (never itself) and `signedIn` rule staff = me.email in setting.list("SHOP_ADMINS") `me.email` (lower case) · `setting("KEY")` its text · `setting.list` after `in` (split at commas, trimmed): read once as the back end starts (a change is a restart); never `secret()` (H163) back-end.md#a-rule-that-reads-a-setting model Message … read if member(channel) a model's line names it with its fields: as if written there server fn purge(channel: id): number requires admin && member(channel) `requires` a test of rules, `signedIn`, && || ! ( ), over the fn's own parameters (id string number bool; `o.channel` of a shape): asked after the arguments are checked, before the body, and at every run of a `live` value; one answer a rule and its values in a call · nobody signed in: 401 `signin` (a test that reads `me` asks for a session) · the rule says no: 403 `refused`, "you may not do that" server fn status(): string requires anyone open to the internet, and says so · server route GET "/x/:id"(req) requires member(id) · a `server fn` with no `requires` where people sign in is warned of (H134; `mote check --strict`: an error) · so is a rule that can never pass, or passes for anyone: `kind == "a" && kind == "b"`, `kind in []` (H162) server fn search(q: string): Hit[] requires anyone limit 5 per minute also per second hour day · by me | ip | a parameter (unsaid: who is signed in, else the address) · over it: 429 `limited`, `retry-after` · kept by each process · on a route too auth.signIn signUp changePassword are limited with nothing written: 10 a minute an email, 30 an address (MOTE_AUTH_LIMIT) the address is the socket's; behind a proxy say MOTE_PROXY=1 (how many): then the last of X-Forwarded-For, never a caller's own check(value, Shape)? json held to a shape (a model's row, [T], {f: T}) as it runs: the value typed, or "invalid" with where: "events[3].amount: a number was wanted, and there is \"12\"" · {extra: "keep" | "drop" | "refuse"} schema(Shape) its JSON Schema, written out when compiled ($defs; {strict: true}: all required, no others) net.lookup(host, "TXT")? a name's records of one kind (back end): A AAAA CNAME NS PTR TXT texts, MX {exchange, priority}, SRV {name, port, priority, weight}, CAA {critical, tag, value} · none is [] · {timeout: 5000, servers} · no answer: "offline" · a test: given dns "example.com TXT" answers {records: […]} net.send("GET", url, {to: {path: "in/a.mp4", resume: true}})? the answer written to a file as it arrives (back end): a.written, a.size; resume asks for the rest (Range) · body: {file: "out/x.csv", from, length}: a file or a part, read as sent lock("export", {for: 60000}) + a block: one run at a time of every back end at the database; one that finds it held is "busy" net.pace("api.x.com", {per: 1000, max: 10}) · net.breaker("api.x.com", {after: 5, rest: 30000}) in `server start`: requests wait their turn; after 5 failures running the host is "offline" at once for 30 s · net.health() req.form({file, files})? a form's body at a route (multipart or urlencoded): {fields, files: [{field, name, type, data}]}; a file past `file` bytes, or more than `files` (100), is "toobig"; the whole is held to MOTE_MAX_BODY webhook.check(req, "stripe", secret("WH"))? the body (json), once its signature is the service's: over the bytes sent, in constant time, its moment within {tolerance: 300} s; else "refused" (a 400) · schemes: stripe standard (svix resend clerk …) github shopify slack twilio paddle discord token … or {hmac, over, header, timestamp} webhook.once(event.id) + a block: done the first time that id is seen, the id kept in the block's own turn (a redelivery is answered and skips it) · queue a `job fn` there for the slow part · req.url: the address as the caller wrote it secret("PAY_KEY") a setting the back end does not start without (it names every one missing) and its log never shows (`[secret]`); not returned by a `server fn`, emitted, kept in a row or said in `fail` (H136, one fn deep) env("KEY") is a plain setting: "" if unset, written as it is auth.as(userId, {look: false, minutes: 10})? in a `server fn` whose `requires` says who may (H137): the caller is taken for that person (`me`, rules, rows, pages) in this app, their own session kept · unsaid: only to look (every write refused: models, files, notify.send, passwords) for 30 minutes · auth.actor()? {id, email}? the real person · never while acting: changePassword, setPassword on them, signOutAll, signing in, acting again · auth.asEnd()? ends it (a page may) · page: auth.acting {as, by, look, until}? and a banner of the runtime's own, with End · logged: began, ended, expired, each refusal a call with the session's cookie, and the open line, are taken from the app's own origin (MOTE_ORIGINS adds some): else 403 · the page is in no other site's frame (MOTE_FRAME) · the line: 500 live values a page, 50 messages a second, 1 MB each (MOTE_LIVE_*) MOTE_ACCOUNTS=/srv/accounts on several apps: one set of accounts and sessions, one id a person (`me`), each app its own rows; MOTE_COOKIE_DOMAIN=.example.com if they are on sibling subdomains back-end.md proc.run(["git", "status"], {cwd, env, input, timeout, max})? {code, out, err, cut}; a list, never a shell's line let run = proc.start(["bun", "test"])? run.line() (none at the end) · run.stop() · run.done()? · run.pid let c = tcp.open(host, 5432, {tls, servername, ca, pin, cert, key, verify, timeout, proxy, pool})? c.read(n, ms?)? exactly n · c.readUntil("\r\n")? · c.line()? · c.readSome()? · c.write(data)? · c.startTls({…})? · c.end() half · c.close() · fails refused lookup reset timeout tls closed toobig · TLS checked (chain and name) unless verify: false · closed at the stop · tcp.take(name, {size, idle, wait})? an idle one, or none (room held: tcp.open(…, {pool: name})) · c.give() · c.keep(k, v) c.kept(k) server listen smtp(c) port=env("SMTP_PORT") cert= key= tls? timeout= max= maxIp= refuse= limit 20 per minute by ip + a block: each connection a socket (closed as the block ends) · c.remote c.local {address, port} · c.startTls() as the server · c.line(ms, max) c.readUntil(end, ms, max) c.readSome(ms, max): toobig, the rest let go · c.stopping, reads fail "stopping" back-end.md#accepting-connections-server-listen let w = ws.open("wss://…", {headers, protocols, reconnect: true})? w.send(data)? · w.next(ms)? {text, bytes, binary, reopened} · w.ping()? ms · w.close(4000, "why") · w.state · w.protocol · both in `mote check --access` CONNECTIONS IT MAY OPEN back-end.md#connections-of-its-own let repo = fs.folder(env("REPO"))? repo.path · repo.text(p) bytes write append del list entries exists info move mkdir a path cannot leave its folder (.., absolute, a link out) · fs.append/exists/info/entries/move/mkdir: the data folder MOTE_SQL=file:/srv/shop/shared on several apps: one database for their models (declared once, in a package both `use`), their files and their accounts; a write in one is in the other's `live` lists; `readonly Price, Staff`: this app only reads them · hooks run where the write was made back-end.md#several-apps-one-database MOTE_SQL=postgres://…?sslmode=require on several back ends of one program: models, jobs, answered calls, leases in Postgres; writes one turn at a time of all of them; `live` by LISTEN/NOTIFY · behind a pooler (port 6543, ?pooler=transaction): MOTE_SQL_DIRECT for LISTEN, else polled · accounts, sessions, limit counts, notify's inbox and devices there too · calls' rooms across back ends (MOTE_CALL_BEAT) · no fulltext yet back-end.md#models-in-postgres mote migrate app.mote --to postgres --data data [--dry-run] [--replace] an app's SQLite data into MOTE_SQL's Postgres (back end stopped): schema as the back end makes it, rows in batches a second run goes on from, each table summed on both sides · logs, facts and the push key (vapid.json → mote_vapid) too · files/ to MOTE_FILES's store when set, after the rows back-end.md#moving-an-app-from-sqlite-to-postgres MOTE_FILES=s3://bucket/folder?endpoint=https://.r2.cloudflarestorage.com + MOTE_FILES_KEY_ID, MOTE_FILES_SECRET: a model's files in R2/S3, not on disk; streamed both ways, Range; rules as before · a file no row knows is kept and counted, never swept (MOTE_FILES_SWEEP_UNKNOWN=1 to) · a container's disk: back-end.md#containers-with-an-ephemeral-disk mote check --disk: what the back end keeps on its own disk · MOTE_DISK=ephemeral|kept: said as it starts (unset: under Postgres) · MOTE_VAPID (a secret): the push key; with Postgres it is one row, mote_vapid, for every back end MOTE_BACKUP="backups?every=1h&keep=30": snapshots of every database, the stored files and vapid.json (WAL; several processes), a folder a time; `mote restore ` puts one back (back end stopped) back-end.md#snapshots server start + a block: once, when the back end is up (nobody is signed in) server every 60000 + a block: on a timer, one run at a time · `server every 60000 once`: in one back end of several server at "03:00" + a block: each day at that time (UTC; `zone="Europe/Paris"`), `"mon,thu 18:30"`: those days; once however many back ends; a moment it was down for is made up at start if under an hour late (MOTE_AT_LATE) detach work(id) the call goes on after this one answers, as who called; a failure is logged; lost if the back end stops job fn welcome(who: id) retries=5 timeout=300000 unique as me + a block: work done later, at least once, across restarts. welcome(id) queues it (cannot fail, gives the job's id) · welcome.in(60000, id) · welcome.at(when, id) a job may run more than once: make it safe to · fails: again after 1 s, 4 s, 16 s … then kept as failed queued inside `atomic`: only if the block is kept · only the back end queues one (a page: H142) · jobs.list({name, state})? jobs.cancel(id)? jobs.retry(id)? · MOTE_JOBS=4 at once (0: none here) server on jobFailed(j) + a block: a job given up on; j: {id, name, args, tries, words, kind} back-end.md#later-job-fn server stop + a block: once, when it is asked to stop (SIGTERM): after the calls in flight, before the databases close app "Shop" usage=on · use "pkg:usage/usage.mote" · `fn usageMay(): bool` (it `wants` it) · UsagePanel on an admin route: who is active, what is used, what fails, kept in the app's own database · track("checkout", {plan}): a measure of one's own (nothing with usage off) · usage="signed in" → docs/usage.md web: visitors, visits (30 min gap, midnight), pageviews, bounces (1 screen, < 10 s, no goal), sources, utm_, country, browser, device, speed (LCP CLS INP TTFB), now · UsageOverview UsagePages UsageSources UsageCountries UsageDevices UsageNow UsageGoals UsageVitals `fn usageGoals(): string[] = ["checkout", "/thanks"]` · paths=full (unsaid: /job/:id) · geo=city|off (unsaid: country) · vitals=10|all|off country: MOTE_GEO_HEADER=cf-ipcountry (with MOTE_PROXY) · MOTE_GEO_DB=ranges.csv (start_ip,end_ip,CC) · else the time zone · never the IP no lasting id unless visitors=kept (a year) · DNT/GPC: nothing, page nor back end · bots dropped (USAGE_BOTS=keep; tests: USAGE_AUTOMATION=count) a visitor who signs in or up is joined to the account (one person, one visit) · several apps, one panel: no usage=on on the keeper; usageTake(batch, "planner") · every question `…, app?` and component app="planner" · fn usageGoalsFor(app: string): string[] the page keeps the open line (/live) and sends on it (posts with none; sendBeacon as it goes) · kinds here, gone: who is here now, exact (UsageHere, a row a tab; a line back within 30 s is the same tab) · autocapture=on: click, change (never a value), rage, dead by data-mote name · inside `private`: named private · no positions kept log Events + fields, `keep 7 days` (or `keep 2 GB`), `capture` (POST /capture, MOTE_CAPTURE_KEYS; PostHog's /batch/ too): an append-only durable log; every log and fact has id at name who session app props · Events.append(row)? appendAll(rows)? read(offset)? since(t)? last()? rewind("store", 0)? stats()? · server on Events(batch) as store: a consumer, its own place, at least once · in Postgres with the models (MOTE_SQL=postgres://…): one log for every back end, in order, no gaps fact Event + fields, order app, name, at · partition month · keep 400 days · rollup daily by name, day count, uniq(who): an analytics table, SQLite, Postgres with the models, or ClickHouse (MOTE_ANALYTICS=clickhouse://…) · Event.dialect() · Event.addAll(rows)? trend funnel retention paths stickiness lifecycle frequency people rows ({last: "30 days", every, by: "props.plan", measure: "p95", of, where, steps, within}) alias(visitor, person) forget(who) sql("…?", [v]) · use "pkg:usage/analytics.mote": AnalyticsPanel, flags, experiments → docs/analytics.md use "pkg:admin/admin.mote" · `rule admin = …` · AdminPanel on a route: people (sessions, sign out everywhere, see what they see), every model's rows (search, open, follow references; changed only as the model's rules let that admin), jobs, health, access, a log · AdminPeople AdminData AdminJobs … alone → docs/admin.md server on usage(batch) + a block: the events themselves, every 5 s: {name, kind, at, user?, anon?, session, route?, ms?, ok?, failKind?, props, path?, title?, referrer?, utm?, client?: UsageClient {ua, brands, lang, zone, screen, viewport, dpr, webdriver, country?, region?, city?, geoFrom}} server on failure(f) + a block: every fault the back end had (call, route, live, start, every, detach); f: {where, words, stack, at?, kind, call?, user?, id}; one that fails itself is logged, no more a stack reads by .mote lines: `place (app.mote:12:3)`, the runtime's frames folded (server/main.js.map) log.info("order placed", {order: o.id}) log.warn log.error log.debug · log(x) is log.info · on the back end one line of JSON on stdout: time level msg fields + call, user, id (the call's: sent by the page in x-mote-call, given back in the answer) or block; a line per call (status ok said fault refused invalid, ms) and per route hit · MOTE_LOG=debug|info|warn|error|off · what secret("KEY") gave (6+ characters) is written [secret] a fault tells the page only `name could not be done (id …)`: the rest is in the log under that id (mote dev shows it) GET /healthz 200 while up · GET /readyz 200 once it takes calls, 503 once stopping · SIGTERM: readyz 503, no new connections, calls in flight finish (MOTE_STOP_MS, 10 s), pages are told and come back within MOTE_BYE_MS (1 s), exit 0 a call is answered once: the back end remembers each caller's ids and answers for 10 min (MOTE_ONCE_MS; a page's model write also in the database, with the write) · so the page sends a call that got no answer again, twice (0.3 s, 1.2 s), then fails as offline ("could not reach the server"); a call has no time limit unless `app … timeout=` says one · another client: send `x-mote-call: ` and reuse it to retry net.* from the back end with no `timeout` gives up after 30 s (MOTE_NET_TIMEOUT; `timeout: 0` none; net.stream: until it begins) it serves the built app: hashed assets/ immutable for a year, the rest no-cache, an etag on the page (304), .gz to who takes gzip, Range, nosniff · mote build also writes dist/Dockerfile and dist/.env.example (never served) server fn thumb(picture: bytes, w: number): bytes bytes cross as they are; a call is 16 MB at most (MOTE_MAX_BODY) files.keep(data, name)? files.bytes(f)? files.path(f)? what a model's `file` field keeps → docs/models.md#files files.derive(f, "thumb", bytes)? a picture kept beside a file: `f.url + "/thumb"`, for whoever may read the row · `f.url + "?download=Q3.pdf"` server fn take(k: Kitchen): string requires peer only another back end may call it; to anyone else it is a 404 extern server fn take(k: Kitchen): string at env("SHOP_URL") declared where it is called: no body · timeout=60000 · as me called like any fn of the back end (never by a page); signed with MOTE_PEER_SECRET (same on both; `new,old` to change it); the answer is checked against the type; the other's `fail` words pass through · `at to` with a `to: string` parameter: the caller's address failing: err.kind is the other's own / said · offline · timeout · invalid · fault (err.id: the id both logs have the call under) data styles: Style[] from "./styles.json" a JSON file beside it, read as it is built: the value written out, for the page and the back end; typed if said data.md api Harbor from "./harbor.json" only ["listBoats", "getBoat"] an OpenAPI 3 file kept beside it, read as it is built: a typed fn a listed operation (harborListBoats(options), harborGetBoat(boatId)) and only the shapes they reach, one harborCall (HARBOR_API, retries on a GET, Retry-After, kinds, the file's error words) · lines: base "…" · auth bearer secret("K") (basic, header "x", query "x") · header "x-version" "1" · mote api expand app.mote: the Mote it is made into → docs/services.md#a-service-with-an-openapi-file mote check app.mote --against ../shop/app.mote the models both keep (MOTE_SQL) and each extern, against that program (or, externs only, its dist/server/api.json) dist/server/api.json: calls, externs, models, shapes, events, routes, rules, env, secrets · `mote build --api`: + openapi.json, client.ts mote check app.mote --access [Name] [--json] who may do what: each model operation, call, route and room with its rule and who that admits in words (`[not tested here: role]`), then "Worth a look": a page write past a `server fn`, a secret field read by many, membership alone on a write, a fn with no `requires`; facts, exit 0 back-end.md#who-may-do-what server route POST "/hooks/:token"(req) + a block: an address for another service; no session assumed req.params.token req.query("n") req.header("x-key") req.text()? req.json()? req.bytes()? req.method req.path return {status: 201, json: {ok: true}} or text: / bytes: / headers: {…}; nothing returned is a 204 GET HEAD POST PUT PATCH DELETE OPTIONS · a GET route answers HEAD: its status and headers, no body (req.method == "HEAD") · answers are cache-control: no-store unless the route says · cors="*" | "https://app.example" | [origins] | setting.list("APP_ORIGINS") | {origins, headers, expose, maxAge, credentials} last on the line: allow-origin on every answer, the OPTIONS preflight written; from another origin the cookie is nobody's unless credentials (H356) back-end.md#head body=4096 (after requires/limit, before or after cors=; on a server fn too): the most bytes it may be sent, in place of MOTE_MAX_BODY, more or less; 413 before the route runs (content-length), or as it arrives (H480) · an address no route and no file is: the page, in a program with one; 404 in a back end with no page (no markup) ``` zip and img work in a server fn too: an export packed where the data is (returned as bytes, or served by a route), a thumbnail. A plain fn is the back end's when only server fns call it (or nothing does yet); called by the page, it is the page's too. use "pkg:mail/parse.mote": mailParse(reader)? {headers, from, to, subject, date, parts [{path, type, charset, name, id, start, end, text}], text, html, problems} · mailPiece/mailSave/mailBody(r, part) a body decoded a piece at a time · pkg:mail/mbox.mote mailMboxNext(r)? {start, from, bodyAt, end, data} · pkg:mail/server.mote: smtpServe(c) in a `server listen` block; the program's smtpRecipient(s, to) and smtpMessage(m) (m.path: the body, spooled) say accept/refuse/defer · smtpOpen(m)? reads it · fn smtpSpool() "file" | "sealed" (fn smtpSpoolKey(): json) | "memory" (up to SIZE, else 552) · pkg:mail/auth.mote (back end): mailDkimVerify(r)? mailDkimSign(r, {domain, selector, key})? mailSpf(ip, from, helo)? mailDmarc(r, spf, dkim)? mailArcVerify(r)? · pkg:mail/deliver.mote (back end): mailDeliver(from, to, path)? [{to, status: delivered|deferred|bounced, code, host, tls}] MX, STARTTLS, MTA-STS · mailQueue(from, to, path)? tried again by a job fn; fn mailDelivered(q, results) · mailDsnRead(r)? a bounce read · pkg:mail/address.mote mailAddrValid mailAddrSame mailDomainAscii (Punycode) mailOrgDomain (the Public Suffix List) page, off fn, back end → docs/mail-library.md Mail is net.send to a mail service's API from a `server fn` (a `job fn`, so that it is not lost), its key a secret() → docs/back-end.md#sending-mail A route that changes things must not trust the cookie alone (a GET never changes anything) → docs/back-end.md#routes Never put what a page sent into a command or a path unchecked → docs/back-end.md#what-this-lets-a-program-do ## Models → docs/models.md ```mote // docs: whole model Room name: string unique owner: id = me read anyone add if me != none change, remove if owner == me local model Draft room: string unique text: string = "" live rooms: Room[] = Room.find({}, {order: "name"}) else [] resource drafts: Draft[] = Draft.find({}) else [] action make(name: string) let r = Room.add({name})? Draft.add({room: r.id})? for r in rooms key=r.id text `${r.name} ${drafts.find(d => d.room == r.id)?.text ?? ""}` button "Make" press=make("den") ``` `model T` is kept on the back end, `local model T` in this browser's SQLite; each is a type and a table. Fields: `id: id` (the key, made for you) · `= default`, `= now`, `= me` (who is signed in; never the page's to give) · `T?` · `Other cascade` (a reference, kept as its key) · `unique` `hidden` `key` `was oldName`; lines `unique a, b` · `index a, b` · `check test else "why"`. ```text T.get(key) T.one(f) T.find(f, {order: "at desc", limit, last, after, with: ["from"]}) T.count(f) T.has(f) T.add(row) T.addAll(rows) T.set(key, changes) T.setAll(f, changes) T.del(key or f) each waits: `?` or `else` a filter: {room: id, state: ["a", "b"], note: none, at: after(t), n: between(1, 9), name: startsWith("ab")} {room: id, any: [{thread: none}, {shown: true}]}: one of several filters, with the fields beside them T.take(f, changes, {order: "due"}): the first row f finds, changed, or none; two callers never get the same row T.put(row, {n: inc(1)}): the row there (its key, or a `unique` set it gives, `= me` counted) changed, else `row` added: an add or a change to the rules, hooks and pages; one turn · inc(n) in any change: `n = n + ?` (numbers; H164) · a page's put waits T.count(f, {by: ["kind"]}) [{kind, count}] · T.sum(f, "total" or [fields], {by, order: "total desc", limit}) · T.min T.max: one statement, GROUP BY; 1000 groups unless `limit` (10000); the back end's alone (H165; `T.as(me)` under the rules) migrate "name" + a block: the back end's statements, run once for a database as it starts, after the schema's steps, all or none atomic + a block: its operations are one (on the back end nothing else waits in it: no net, proc, detach; queue a `job fn`) writes take turns (a block is one turn); on the back end a read never waits for one: it sees the last state kept, one moment per read, its own call's writes, and inside `atomic` the block's own rules (model only): read / add / change / remove / write + `anyone` or `if test`; no rule = closed to the page a test: fields, me, values, == != && || !, `x in [..]`, `exists(Other, {field: value})`; `change if a then b` a reference one step on: `exists(Member, {workspace: channel.workspace, who: me})`, `channel.owner == me` `change text, edited if from == me`: only those fields, for the page; several such lines, each its own test a page's find gives 1000 rows unless it says `limit` (10000 at most); a filter's list holds 1000 values at most full-text: line `index text, title fulltext` (string fields, not hidden/private) · T.search(words, f, {order: "rank" | "at desc", limit, after, snippet: {field, around, mark}}) → rows + `rank` `snippet` · T.searchCount(words, f); reads, under the `read` rule words: `a b` both · `"a b"` phrase · `-a` not · `ab*` prefix; nothing else is syntax · r.snippet.split(mark): every second piece a hit in a page, T.add / T.set / T.del of a `model` show at once: the row the page expects (key made here, = now, = me, defaults) goes in its `live` values, the call gives it back and the action goes on; the answer's row takes its place (same key, same node); refused: taken back, and the `else` beside it runs, else failure(action) has it, else `on failure` · what the action did after that line is not undone · offline: kept (pending), sent in order when the line is back; 200 writes, 5 min at most `confirmed T.add(row)?` this one waits · `confirmed`, a line of a model: all its writes wait · `app … writes=confirmed`: all wait by themselves: addAll setAll take, del by filter, a `file` given, a write in a `fn` passed on with `?`, a row the action goes on to use where a `server before` hook may change it, a row the page holds in no `live` value (set, del) `live x = T.find(…) else []` is kept current, no `changed` (a write sends the row, not the list). In a `server fn`: no rules, unless `T.as(me).find(…)` `live xs = T.find(f, {order: "at desc", window: 200})`: T?[] as long as the count, the rows of the windows a `for … virtual` over it draws, none elsewhere; kept by key as rows come and go `resource` over a `local model`'s find follows the page's writes, in every tab hooks: server before / after T.add(m) · T.change(was, now) · T.remove(was); a `before` may change the row or fail `caller.page` in a hook: the page asked for this write (or `T.as(me)` did), not the back end's own code a write: defaults → before hook → types, checks → the rule → references, unique → kept → after hook a model with no rule is the back end's alone (a queue of one's own: `model Task` + `Task.take(…)`; for work later, a `job fn`) a file: `photo: file` in a model · `Photo.add({photo: files.upload(picked)?})?` · `image p.photo.url` · files.progress several at once: let up = files.sending() · files.upload(f, {into: up})? · up.sent (0..1) up.state · up.cancel() served through its row (the `read` rule decides, 404 otherwise); gone with the row; 100 MB (MOTE_MAX_FILE) `who: Member = me private`: whose the row is, given only to that person's page (none to others; a filter on it finds only one's own). `hidden` fields never reach the page: not by the model's operations, not in the rows a `server fn` returns schema.lock (keep it): safe changes are applied when the back end starts / the page opens; a removed field needs `dropped field` or `mote migrate --drop T.field`; a rename is `was` ``` ## The standard library → docs/README.md#namespaces ```text net net.get(url) net.post(url, body) net.put net.del net.text net.bytes JSON in, json out data.md net.send("POST", url, {headers, body, timeout})? any status: {status, ok, url, location, headers, text, json, bytes} redirect: "follow" | "manual" | "error" · max: bytes · back end: public: true refuses addresses that are not public at every step (a person's URL, fetched safely) · allow: ["wiki.corp"] · net.lookup(host)? · net.public(address) let s = net.stream("POST", url, {…})? s.status · s.chunk()? · s.event()? {event, data, id} · s.rest()? · s.stop() db db.get(k) db.set(k, v) db.del(k) db.keys() db.all() IndexedDB data.md db.persist()? asks the browser to keep the site's data · db.persisted()? · db.room()? {used, left} · a full disk: err.kind == "full" sql sql.open("shop") sql.run(d, "select … where n > ?", [5]) sql.batch SQLite data.md fs fs.text(p) fs.bytes(p) fs.write(p, data) fs.list(dir) fs.pick("image/*") fs.pickMany fs.save(data, name) data.md fs.pick("image/*", {camera: "back"}) a phone's camera · fs.pickMany("image/*", {read: false})? picked[]: {name, size, type} unread, fs.bytes(f)? when wanted fs.append fs.exists fs.info fs.entries fs.move fs.mkdir · fs.open(path or picked)? a reader: r.read(n) readUntil(end) line() find(end) seek(at) readAt(at, n) r.at r.size close() · fs.writer(path, {append})? w.write(data)? w.close()? (an off fn: in place) · fs.writer(path, {seal: key})? / fs.open(file, {seal: key})? sealed: AES-256-GCM in 64 KiB chunks, key 32 bytes or crypto.aes.key clip clipboard.text() clipboard.image() clipboard.put(text or picture) · `paste=` hears a paste data.md store store.get(k) store.set(k, v) store.remove(k) localStorage data.md crypto crypto.hash(data, "sha512"?) crypto.random(n) crypto.argon2id(password, salt) data.md crypto.argon2id(pw, salt, {memory, time, parallelism, length, bytes: true})? bytes · crypto.randomBytes(n) bytes a page's own keys (raw bytes; page, `off fn` and `server fn` alike): data.md#keys-of-the-pages-own crypto.aes.seal(key32, nonce12, data, {aad})? ciphertext then tag (AES-256-GCM; a nonce never twice) · crypto.aes.open(…)? crypto.aes.key(raw)? a key nothing reads back (db.set keeps it) · crypto.x25519.keyPair(seed?)? {private, public} · crypto.x25519.shared(private, public)? · crypto.ed25519.keyPair(seed?)? · .sign(private, data)? · .verify(public, data, sig)? crypto.mlkem768.keyPair(seed?)? {decaps, encaps, seed} · .encaps(encapsKey)? {ciphertext, shared} · .decaps(decapsKey, ct)? crypto.pow(prefix, {bits: 18})? 16 bytes that give prefix + them a SHA-256 of 18 zero bits · crypto.hash(d, "sha3-256") ("sha3-512" "shake128" "shake256" {length} "blake2b" {length, key}) · an old browser: kind "unsupported" (x25519, ed25519) crypto.hash(data, "md5") (a protocol's, never security) · crypto.pbkdf2(pw, salt, {iterations, length})? bytes · crypto.hkdf(key, {salt, info, length})? · crypto.hkdf(key, {info, as: "aes"})? an AES key never bytes · as: "hkdf" · crypto.hkdf.key(raw)? material nothing reads back · key bytes into persist/store/db/log/toast/fail/text/server fn: H460 · crypto.reveal(x) x, meant to be seen (a recovery key shown once) · back end: crypto.seal(secret("KEY"), data, {aad})? (AES-256-GCM) · crypto.open(…)? · crypto.encrypt(publicKey, data, {alg: "RSA-OAEP-256"})? · crypto.decrypt(privateKey, data, {alg})? crypto.hmac(key, data, "sha256"?)?.hex() · crypto.equal(a, b) (a secret is never compared with ==) · crypto.crc32(data) back end: crypto.sign(privateKey, data, {alg})? bytes · crypto.verify(publicKey, data, signature, {alg})? bool · alg "RS256" "ES256" "EdDSA", a key PEM or JWK · crypto.jwt.verify(token, jwks, {aud, iss, leeway})? its payload, checked (signature, exp, nbf, aud, iss; never alg none or HS*) · crypto.jwt.read(token)? {header, payload, …}: unchecked crypto.cert(pem or der)? read whole: {subject, issuer, tbs, signature, sigAlg, ca, pathLen, keyUsage, altNames, aaguid, …} · crypto.cert.chain(leaf, intermediates, roots, {at})? {root, rootSubject, path}: signatures, dates, CAs (no revocation) zip zip.gzip(data) zip.gunzip(b) zip.pack([{name, data}]) zip.unpack(b) data.md zip.entries(f)? (zip64 too) · zip.open(f, name)? a reader, inflated as read · zip.gunzipStream(r)? · tar.entries(r)? t.next()? csv csv.read(data)? string[][] · csv.records(data, Row, {delimiter, header, decimal, dates})? Row[] · csv.open(file, Row)? r.next()? (rows, none at the end) · csv.write(rows, {delimiter, bom}) text tables.md xlsx xlsx.sheets(b)? xlsx.rows(b, {sheet})? xlsx.records(b, Row)? xlsx.read(b)? (kinds, formulas, merges) · xlsx.write([{name, rows, columns: [{key, title, format: "currency"}], filter: true}])? bytes tables.md bytes bytes("text") bytes.new(n) bytes.of([72, 105]) bytes.join([a, b]) bytes.hex(s) bytes.base64(s) b[i] b[i] = v b.slice() b.set(other, at) b.read(at, "u32") b.write(at, "u32", v) b.text() b.hex() b.url() language.md b.text("windows-1251")? any WHATWG label ("unsupported": none such; the CJK sets by a battery, alike everywhere) bytes.find(b, "\r\n", from?) (-1: nowhere) · let w = bytes.buffer(): w.add(data) w.byte(n) w.put("i32be", n) w.length w.bytes() img img.decode(b) img.decode(b, {fit: 2560}) img.info(b) img.png(p) img.jpeg(p, 85) img.tiff img.resize img.fit img.crop img.blur … media.md paint paint.new(w, h) paint.line paint.shape paint.text paint.image, shown by `canvas layers=stack` media.md scan scan.read(picture) codes as {format, text}[] · `camera on=live scan=found` · cam.shot() media.md vid vid.open(b) vid.frame vid.export(clips) · aud.open(b) · `reel clips=clips at=time playing=on` media.md draw `surface draw=chart` with fn chart(g: pen, size: {width: number, height: number, time: number}) draw.clear draw.rect draw.circle draw.line draw.path draw.text draw.image draw.measure("words", {size}) draw.picture(w, h, chart) an `image` · `surface gl`, gl.draw · gl.filter(picture, fs) drawing.md 3D `canvas boxes=list view="iso"` boxes in space · `canvas scene=world camera=eye` with three.* drawing.md, scene.md three.box sphere cylinder plane · three.extrude([[x, y], …], height, {holes}) an outline pushed up scene.md a picture on a material: three.material({color, map: address | bytes | picture, mapSize: [w, h] of the scene per copy (unsaid: one copy a face), mapOffset: [u, v], mapTurn: 90, tint: true}) · three.mesh(geometry, material, {grain: "x" | "y" | "z" (the picture's up; z), sides: material (a box's four thin faces, an extrusion's sides), faces: "x"}) · the same words on a box of boxes= · input hears {phase: "materials", loaded, of, failed, ready} and, past 128 pictures, {phase: "limit"} scene.md#pictures-on-materials-map url url.encode(text) url.decode(text)? · url.parse(text)? {scheme, host, port, path, query, hash} · url.build({host, path, query: {q: "oak door"}}) · url.query("a=1&b=x+y") a record · url.form({…}); page and back end language.md#addresses re re.test(text, r"\d+") re.find(…)?.named?.year re.all re.at re.replace(text, p, "$1" or m => …) re.split re.check re.escape text.md flags last: "i" "m" "s" "u" "y"; \p{L} \p{sc=Greek} \u{1F600} imply "u"; linear time: no \1, (?=, (?<= search search.index([{id, text}] or [{id, fields: {subject, body}}]) a segment · search.find(segs or s, "oak door \"a phrase\" pre* subject:x", {limit, prefix, all, weights: {subject: 3}, removed}) [{id, score, matches: [{field, words}]}] · search.merge([a, b], {removed}) search.open([a, b]) a searcher (loaded once) · search.add(s, seg) remove(s, ids) close(s) count · search.marks(text, q) [{from, to}] text.md#search html html.clean(text, {images: "block"|"proxy"|"allow", proxy: "/img?u={url}", cid, styles})? {html, images, links, removed, trackers} · html.text(text)? text.md htmlframe html=letter images="block" link=open cleaned=seen: cleaned, in a frame where nothing runs (policy=strict too) syntax syntax.parse(text, "js") syntax.tokens syntax.lines; "markdown" is a document, ready to draw text.md a language of your own: let g = syntax.grammar(rules)? · syntax.parse(text, g)? is its whole tree · or `grammar Calc from "./calc.grammar"`, checked at the build font font.open(bytes) font.layout(f, "words", {size}) font.outline font.use(f, "Name") text.md pdf pdf.make([pdf.heading("Invoice"), pdf.text("…"), pdf.table(rows), pdf.image(b)], {title, footer}) pdf.md pdf.read(b) (each page's text) pdf.words pdf.info pdf.fields pdf.fill(b, {Name: "Ada"}) pdf.merge([a, b]) pdf.stamp screen screen.phone screen.dark screen.width · scheme("dark" | "light" | "auto") · screen.print() markup.md notify notify.ask() notify.show("Title", "A line", {actions: [{id, title}], data, url, tag}?) · notify.allowed() "granted" "denied" "default" · push.subscribe(key) data.md speech speech.listen() speech.say(text) · mic.list() media.md mic state rec: recording? = none · rec = mic.record({levels: true})? · rec.level rec.time rec.state (reactive) rec.pause() rec.resume() rec.cancel() · rec.stop()? {bytes, type, length, peaks} · mic.meter()? {level, stop()} player `audio src=url playing=on at=time rate=1 volume=1 duration=length ended=done` (video too; preload="none") playing and at are written back to state (every frame while it plays); a new `at` seeks; duration is only written sound sound.play("ping" | bytes | url, {volume, loop, id}) {played, why: "" | "gesture" | "unsupported"} · sound.stop(id?) tones: ping pop ring error join leave · sound.ready (false until the page was pressed) · sound.error media.md rtc state call: call? = none · call = rtc.join(room, {audio: true, video: true, name, levels: true})? calls.md call.peers call.me: {id, user, name, audio, video, screen, level, speaking, state, verified, error, fingerprints} · `video of=p` (`screen`) rtc.join(room, {verify: key})?: each connection proved with a key the back end lacks · {relay: true}: only through TURN call.ring(accounts, {url}) call.rings: {user, state: ringing answered declined missed offline, at} · rtc.rings() rtc.decline(id) with notify: rung on their devices too, Answer and Decline · on rtc.answer(r: {id, room, from, name}) joins call.mute(on)? call.camera(on)? call.share(on)? call.use({mic})? call.send(data) call.leave() · rtc.devices()? `server call(room: string): bool` says who may join (none declared: nobody) · `on rtc.message(m: {from, data})` models in Postgres: members on different back ends share rooms and rings calls.md#more-than-one-process ``` Most of these leave the page, so they wait and can fail: `else` or `?`. Not store, paint, draw, three, re, screen, `bytes("text")` and crypto.random. ## The kit → docs/kit.md Components that come with Mote; a page carries only those it uses, and they follow the colour roles. ```text Button "Save" press=save variant="outline" size="sm" · Badge · Card title="…" · Label · Separator Input value=name · Textarea value=bio · Checkbox "I agree" checked=ok · Switch on=wifi · Slider value=n Switch value=row.on change=set (also Checkbox, Toggle): driven, shows `value`, tells `change`, writes nothing back Select value=fruit options=["Apple", "Pear"] · Radio · Tabs value=tab options=[…] · Combobox · Pagination Carousel api=car with CarouselContent, CarouselItem: car.index read and set, follows the finger, kept through resizes and slides that come and go Drawer open=open snapPoints=["64px", 0.86] modal=false: a sheet that stays on the page at its peek (modal unsaid: over it) Dialog open=asking title="…" · Sheet open=menu · Alert · Progress value=40 · Avatar · Skeleton · Spinner Menu with MenuItem "Rename" press=rename, and Popover: written under the element that opens them LineChart data=rows x="day" y="visitors" scale="time" zoom · BarChart … config=[{key, label}] stacked · PieChart value= name= donut Chart data=rows x="day" + children Line y="a" · Bar y="b" axis="right" · Rule y=100 label="target" · Band lower= upper= ScatterChart HeatMap BoxPlot CandlestickChart SankeyChart TreemapChart GanttChart Sparkline … a million points; range= picked= group= charts.md Highlight text=code lang="ts" · CodeBlock code=… · Markdown text=answer streaming=busy editor value=source lang="ts" · terminal output=out input=typed · flow edges=edges (docs/widgets.md) richtext value=doc edit=ops picture=file · richtext.html(doc) richtext.text(doc) .from .quote .apply kit/richtext.md several at once: richtext log=entries send=post (sealed units a server numbers; H500) · richtext.copy(doc) .edit(copy, ops) .take(copy, entries) .snapshot(copy) .transform(mine, theirs); page, worker, back end ``` ## For agents and tests → docs/agents.md, docs/testing.md ```text test "a muted person cannot post" + a block, in any file: the back end's own tests, run by `mote test app.mote [words] [--json]` as "ada@example.com" · as none who the lines that follow are run as (an account is made); each test: a fresh back end and database let c = Channel.add({name: "x"})? a model's operation and a `server fn` go through the rules and `requires`, as a page's would trusted + a block its lines are the back end's own code, past the rules: to arrange, and to look expect Message.count({}) == 1 expect · expect (a + b) == c · expect post(…) fails · fails "words" · fails kind "signin" clock "2026-03-01T09:00" · clock +1 day the back end's one clock; moved on, `server every` and `server at` blocks run in order run jobs · queued(welcome) jobs that are due are run · those waiting given net "https://mail.example/*" answers {status: 200, json: {…}} · sent(net) sent(notify) sent(emit) sent(proc) given env "KEEP_DAYS" is "30" · given secret "PAY_KEY" is "sk-test" that test's back end starts with it (H167) test "a note is added" page a test of the page too: its back end listens, and `page` is a browser at it (Chrome on the machine) page.type("New note", "Milk") · page.press("Add") · tap hover key check pick hold swipe drag pinch scroll real input; back when the page is at rest page.see("Milk") · expect page.has("Milk") · page.read() · page.changed() · page.path() · page.title() · page.errors() page.open("/about") · go reload back · size(390, 844, {touch: true}) · scheme("dark") · shot("p.png") · page.eval(js) as "ada@…" signs the browser in too · clock +5 seconds moves the page's timers with the back end's · `page` elsewhere: H336 nothing leaves the process: a request nothing was said of fails the test ``` Every control carries `data-mote`: the action its press runs (`[data-mote="add"]`) or the state a field writes (`[data-mote="draft"]`). A built app has agent.json and llms.txt; `agents.mote` adds your notes. In the page, `mote`: `await mote.read()` the page as lines of text (`#4 button Add`), `mote.press(4 | "add" | {name, text})`, `type` `check` `pick` `key` `hold` `swipe` `drag` `scroll` `go` `see`: each comes back with the page at rest and `{settled, changed}`; `mote.clock.hold()` / `.advance(ms)` the page's timers in hand. `mote drive --out f.mjs`: the same with real input, for tests (no sleeps). agents.md ## Refused, with the fix in the message ```text className onClick htmlFor style=… class · press · for · the property itself null undefined none xs.sort() in a binding or derive toSorted(), or sort in an action text Hello text "Hello" text a ?? b text (a ?? b): a space ends a value xs.contains(x) s.len() xs.append(x) includes · .length · push any boolean String json · bool · string ``` # The language Declarations, types, logic, calls that can fail, files and packages. Markup is in [markup.md](markup.md); when things run and re-run is in [reactivity.md](reactivity.md). Back to the [map](README.md). ```mote // docs: whole shape Todo id: string title: string done: bool state todos: Todo[] = [] persist state draft = "" derive left = todos.filter(t => !t.done).length action add if draft.trim() == "" return todos.push({id: uid(), title: draft, done: false}) draft = "" action remove(id: string) todos = todos.filter(t => t.id != id) column gap=8 padding=16 row gap=8 input value=draft placeholder="What next?" submit=add button "Add" press=add for t in todos key=t.id row gap=8 align-items=center input type=checkbox checked=t.done text t.title color=(t.done ? "dim" : "fg") button "×" press=remove(t.id) text `${left} left` color=dim ``` ## Mental model A file is an app. It holds declarations (what the page knows and can do) and markup (what it shows), in any order; the compiler reads all declarations first, so a name may be used above the line that declares it. The compiler turns the file into one HTML page: 1. `lex.rs` cuts the text into tokens. Indentation is the block structure: a deeper line opens a block, a shallower one closes it. Spaces only; a tab in indentation is refused. A line end inside `( )`, `[ ]` or `{ }` is just a space. 2. `parse.rs` (`Parser::body`) reads each top-level line. A line that starts with a declaration word and a name (`state n`, `fn f`, `shape T`, …) is a declaration. Anything else is markup. 3. `types.rs` (`check`) checks every expression. Types are inferred, so most programs write few of them. 4. `emit.rs` writes the logic as JavaScript; `view.rs` writes the markup. State becomes a signal; what reads it re-runs when it changes ([reactivity.md](reactivity.md)). Three rules shape everything else: - **Only an `action` (or a `{…}` handler, a `task`, a timer) writes state.** A `fn` is pure. A binding in markup and a `derive` only read. - **A call that can fail must be settled where it is made**, with `else` or `?`. Nothing fails silently and nothing is thrown past you. - **Nothing says `async` or `await`.** A call that leaves the page (the network, a file, a worker, the back end) is waited for by the compiler. Only an action, a fn, a handler, a task or a resource can wait. ## Declarations | Line | What it declares | |---|---| | `state n = 0` | A value the page shows and actions change. | | `state todos: Todo[] = [] persist` | The same, kept in `localStorage` under its name between visits. | | `derive left = todos.filter(t => !t.done).length` | A value worked out from state; it follows what it reads. | | `action add` / `action set(v: string)` | Statements that may write state. | | `fn total(xs: number[]) = xs.length` | A pure function, in one line. | | `fn f(a: T): R` + an indented block | A pure function with a body. `: R` is optional. | | `shape Todo` + indented `field: type` lines | A named record type. | | `component Badge(label: string, tone: string?)` | A piece of markup with its own declarations ([markup.md](markup.md#components)). | | `resource posts: Post[] = net.get(url) else []` | A value loaded in the background ([reactivity.md](reactivity.md#resources)). | | `task` / `task load` | Statements that run when the page opens ([reactivity.md](reactivity.md#tasks)). | | `every 1000` / `after 500` | Statements on a timer ([reactivity.md](reactivity.md#timers)). | | `watch active` | Statements that run after a value changes ([reactivity.md](reactivity.md#watch)). | | `fill "bar.tools"(row: Row)` + markup | What this file draws wherever any file wrote `slot "bar.tools" row=r` ([markup.md](markup.md#components)). | | `use "./parts.mote"` | Another file's declarations ([below](#files-and-use)). | | `app "Todos" accent=#0a84ff` | The page's title and settings ([below](#app)). | | `server fn`, `server live fn`, `live`, `on name(…)` | The back end ([back-end.md](back-end.md)). | | `model Note`, `local model Note` + its fields and rules | A schema that is also typed reads and writes ([models.md](models.md)). | | `off fn`, `main fn` | Where a fn runs ([reactivity.md](reactivity.md#workers)). | | `fns main`, `fns off`, `fns auto` | The same, said once for the plain fns of a file, before its first ([reactivity.md](reactivity.md#said-once-for-a-file-or-a-package)). | | `shortcut "mod+k" find` | A chord the whole page hears ([events.md](events.md#shortcuts-for-the-whole-page)). | A name is declared once in a program, whichever of its files declares it (`use` makes them one program). A second one is refused (`H022`), at the later of the two, with where the other is: ```text extras.mote:12:1: error[H022]: `clockOf` is declared twice: a fn here, and a fn at lib.mote:31 ``` `state`, `derive`, `resource`, `live`, `fn` and `action` share their names (an action cannot be called what a state is); `shape` and `model` share theirs; components have their own, so a model and a component (yours or the kit's `Command`) may be called the same. A component's own declarations are its own: two components may each have a `fn label`. ### state ```mote // docs: whole state n = 0 state name: string? = none state tags: string[] = [] state theme = "light" persist text `${n} ${name ?? "nobody"} ${tags.length} ${theme}` ``` The first value gives the type. An empty list or `none` says too little, so those two need the type written (`H061` otherwise). `persist` keeps the value as JSON in `localStorage` under the state's own name; the first value is used only when nothing was kept (`runtime/page/dom.mote`, parts `PG` and `PW`). A state's first value may read other state and call fns, but it may not wait or write. ### Addresses `url` takes an address apart and puts one together, in the page and on the back end alike. | Call | Gives | |---|---| | `url.encode(text)` | The text percent-encoded, to stand in a path or a query: `"a b&c"` is `"a%20b%26c"` (JavaScript's `encodeURIComponent`). | | `url.decode(text)` | The other way. It can fail (text that is not percent-encoded: a lone `%`), so it meets `else` or `?`. | | `url.query(text)` | A query or a form-encoded body (`"text=hello+there%21&channel=%23general"`, with or without a leading `?`) as a record of texts, `json`: `{text: "hello there!", channel: "#general"}`. A `+` is a space, as a form sends it. Of a name given twice, the last. | | `url.form({q: "oak door", page: 2})` | The other way: `"q=oak+door&page=2"`. A field that is `none` is left out. | | `url.parse(text)` | `{scheme, host, port, path, query, hash}`: `"https"`, `"example.com"`, the port as a number (0 when the address names none: the scheme's own), the path as the address writes it (still percent-encoded), the query as `url.query` gives it, and what follows `#`. It can fail (not an address). | | `url.build({host, scheme?, port?, path?, query?, hash?})` | An address from its parts: `scheme` unsaid is `"https"`, `path` `"/"`; `query` is a record as `url.form` takes it. The path is written as addresses are (a space is `%20`). | ```mote // docs: whole state address = "https://example.com:8443/find?q=oak+door&page=2#top" fn told(a: string): string let u = url.parse(a)? return `${u.host} port ${u.port}, looking for "${u.query.q}"` fn next(a: string): string let u = url.parse(a) else none if u == none return a return url.build({...u, query: {...u.query, page: Number(u.query.page ?? 1) + 1}}) column gap=8 padding=16 input value=address text (told(address) else "not an address") text next(address) text `/tag/${url.encode("c++ & more")}` ``` Source: `runtime/shared/patterns.mote` (part `UR`). ### derive A `derive` is an expression. It runs once, then again whenever state it read changes. It cannot be assigned (`H031`), cannot write state (`H030`) and cannot wait (`H082`). `derive first: string? = xs.at(0)` says its type, as a `let` may: the value is checked against it, and it is that type to whatever reads it (a `json` the back end gave, made a `json[]`: `derive rows: json[] = got.rows ?? []`). ```mote // docs: whole server fn quick(): number requires anyone return 1 server fn slow(): number requires anyone return 2 state got: json = {rows: ["a", "b"]} state n = 0 derive rows: json[] = got.rows ?? [] derive first: string? = rows.at(0) component Pill(label: string, loud: bool?) text label font-weight=(loud == true ? 700 : 400) action pick(fast: bool) n = fast ? quick()? : slow()? column gap=8 Pill loud label=`${first ?? "none"} of ${rows.length}` button "Pick" press=pick(true) text `${n}` ``` (`Pill loud`: a lone word straight after a component's name is a `bool` prop of that name, true, where the component has one: [kit.md](kit.md#pitfalls).) ### action An action's body is statements. Parameters need types. An action is called from a handler (`press=add`, `press=remove(t.id)`) or from another action. An action that waits keeps `pending(name)` and `failure(name)` for the page ([below](#a-call-that-can-fail)). `action find(q: string) newest`: called again while it waits, the earlier run is called off ([reactivity.md](reactivity.md#newest-a-later-run-calls-an-earlier-one-off)). ### fn A fn is pure: it reads its parameters, other fns, and (unless it is to run in a worker or on the back end) state. Writing state in a fn is refused (`H030`: "make it an `action`"). Parameters need types (`H060`). The return type is inferred; write it (`fn f(a: T): R`) when you want it checked. A fn that loops or recurses and uses only its parameters and other such fns runs in a worker when an action, handler, task or resource calls it. That is decided by the compiler; `main fn` and `off fn` override it, and `fns main` at the top of a file (or `fns = "main"` in `mote.toml`) says it for all of them ([reactivity.md](reactivity.md#workers)). ### wasm fn **Experimental.** Ahead of JavaScript on counters, indexes and small records, level or behind elsewhere ([the measurements](../bench/README.md)). `wasm fn` compiles a fn, and every plain fn it calls, to one WebAssembly module: ```mote // docs: whole shape Pt x: number y: number fn far(p: Pt): number = Math.sqrt(p.x * p.x + p.y * p.y) wasm fn farthest(ps: Pt[]): number let most = 0 for p in ps most = Math.max(most, far(p)) return most text `${farthest([{x: 3, y: 4}, {x: 6, y: 8}])}` ``` - It gives the same answers as the same fn without the word, which is still compiled to JavaScript too: that runs until the module is ready (a moment after the page opens), in its place wherever there is no WebAssembly, and everywhere when the back end is started with `MOTE_WASM=off`. - What can go: numbers, bools, shapes whose fields can go, lists of those; `let`, writes, `if`, `while`, `for … in`, `return`, `break`, `continue`; arithmetic and comparisons, `Math.*`, `.length`, `xs[i]`, `xs.push(v)` on a line of its own, a shape or a list written out where its type is known, and calls of other plain fns. Anything else is refused (`H220`), and it must say what it gives (`H221`). - It reads only what it is handed, and what it is handed is a copy: a write to a parameter, or to part of one, is refused. Build what changes inside it and return it. - A number that is only ever whole (a counter, a length, an index) is kept as a whole number, and a `number` parameter used as one is taken to be one. When that turns out wrong for a call (it was handed 2.5, a sum went past what a number holds exactly, an index was outside its list), the call is run again as JavaScript: the answer is the same either way, only slower. `int` in a type says a whole number outright. - Calls between the fns of the group cost nothing extra; each call from outside copies its arguments in and its answer out, so a `wasm fn` should be the fn with the loop in it, not a small fn called in a loop. A parameter at the end that may be none (`T?`) may be left out of a call, and is none: so a fn, a `server fn` among them, can take one more thing later without every call changing. Those before it are given, in order (`H064` says how many it takes). ```mote // docs: whole fn greet(name: string, title: string?): string = title == none ? `Hello, ${name}` : `Hello, ${title} ${name}` server fn visits(days: number, app: string?): number requires anyone return days * (app == "planner" ? 2 : 1) text greet("Ada") text greet("Ada", "Dr") ``` ### shape ```mote // docs: whole shape Point x: number y: number shape Line from: Point to: Point label: string? state l: Line = {from: {x: 0, y: 0}, to: {x: 3, y: 4}} fn length(l: Line) = Math.sqrt((l.to.x - l.from.x) * (l.to.x - l.from.x) + (l.to.y - l.from.y) * (l.to.y - l.from.y)) text `${length(l)} ${l.label ?? ""}` ``` A shape is a name for a record type. Shapes may refer to each other and to themselves. A field typed `T?` (or `json`, which may be `none`) may be left out of a literal. #### A shape as a JSON Schema `schema(Line)` is the shape's fields as a JSON Schema (and `schema([Line])`, `schema({total: number})`, any type [`check`](data.md#check) takes), and `schema(length)` a fn's parameters as one (an object of their names), worked out when the program is compiled and written into it as a literal: what a model's tool takes, or the shape its answer is to have ([ai.md](ai.md#tools-and-answers-from-the-programs-own-types)), or what another service is told to send. ```mote // docs: whole // A point on the page. shape Spot // Across, in pixels. x: number y: number label: string? server fn spotSchema(): string requires anyone = JSON.stringify(schema(Spot)) text "schema" ``` Every object is `additionalProperties: false`; a field is in `required` unless it is `T?` or `json`; `T?` is `anyOf: [T, null]`; `T[]` an array; `json` is `{}` (anything); bytes a base64 `string`; a shape inside is written out where it stands, but for a shape that holds itself, written once under `$defs` and named by `$ref`. `{strict: true}` puts every field in `required` (a `T?` may still be null), as model services' strict modes ask. The comment right above the shape, a field or the fn is its `description`. What is not a type is `H318`; a fn's type has no schema (`H313`). `check(value, T)` holds a value to the same type as the program runs. ### app `app "Name"` sets the page's title. Its settings: | Setting | Effect | |---|---| | `accent=#0a84ff` | The accent colour: the `accent` role, the theme colour, the made icon's ground, form controls. | | `scheme=dark` or `scheme=light` | Fixes the colour scheme whatever the system says. | | `lang="de"` | The language the page is written in: ``, which screen readers, translators, hyphenation and a field's spell checking follow. A language tag: `"pt-BR"`, `"zh-Hant"`. Unsaid: `"en"`. One that changes while the page runs is `root lang=…` ([markup.md](markup.md#values-of-the-whole-page)). A tag of another shape is refused (`H231`). | | `toasts="top"` | Where the notes of `toast(…)` stand: an edge (`top`, `bottom`) and a side (`left`, `center`, `right`), as `"top right"` or `"bottom left"`; an edge alone is its centre. Unsaid: `"bottom right"`. | | `edges=cover` | The page goes to the screen's edges, under a phone's notch and home bar ([markup.md](markup.md#the-screens-edges)). | | `agents=off` | Leaves out everything written for agents ([agents.md](agents.md)). | | `writes=confirmed` | Every write of a model from the page waits for the back end before it shows ([models.md](models.md#a-write-shows-at-once)). Unsaid: they show at once. | | `timeout=30000` | How long a call to the back end may take, in ms, before it counts as unanswered ([back-end.md](back-end.md#a-call-is-answered-once)). Unsaid, or `timeout=0`: no limit. | | `policy=strict` | The page is sent with a Content-Security-Policy made from its own build, and the headers that go with it; `connect="…"`, `images="…"`, `media="…"`, `frames="…"` list the other origins it may reach ([delivery.md](delivery.md#the-strict-policy)). | | `update=ask` | An installed app keeps its build until the page says `app.update()` ([delivery.md](delivery.md#updates-that-ask)). Unsaid, or `update=auto`: a new build takes over by itself. | Any other setting is refused (`H047`). Without `app`, the title is the entry file's name (or its folder's, for `app.mote` and `index.mote`), capitalised. ## Types ```text string number bool none bytes json image sheet video sound font database element pen picked T[] T? a shape's name {x: number, y: number} ``` - **Inferred** everywhere except parameters, shape fields, and an empty or `none` first value. - **Structural.** A literal fits a shape when its fields do. A misspelt or missing field is named in the message. - **`json`** fits anything and is not checked. It is what `net.get`, `JSON.parse` and `db.get` give. Give it a type where it lands: `let xs: Post[] = net.get(url)?`. - **No unions.** `T?` ("T or none") is the one "or". - `int` is accepted as another word for `number`. A function type (`() => none`, `(a: T) => R`) may be written on a component's prop; it is read and not checked. - `image` is `{width, height, data: bytes}` (with `depth`, `space` and `profile` if it has them); `sheet`, `video`, `sound`, `database` are small records with an `id` ([media.md](media.md), [data.md](data.md)); `font` is a font file that has been read, with its facts ([text.md](text.md#font)); `element` is what `ref=` fills ([events.md](events.md#the-element-itself)); `pen` is what a `surface` draws with ([drawing.md](drawing.md)). ### none and T? `none` is the one nothing. There is no `null` and no `undefined`. A `T?` must be settled before `.`, an index, or arithmetic (`H062`, `H065`): ```mote // docs: whole shape User name: string age: number state users: User[] = [{name: "Ada", age: 36}] state picked: User? = none fn label(u: User?): string if u == none return "nobody" return `${u.name}, ${u.age}` action pick(name: string) picked = users.find(u => u.name == name) column text label(picked) text (picked?.name ?? "no one yet") if picked text `${picked.age + 1} next year` button "Ada" press=pick("Ada") ``` Ways to settle it: `x?.f` (gives `none` if `x` is), `x ?? d`, `if x …`, `if x != none …`, `if x == none return` (the rest of the block knows it is there; so it does after `fail("…")?`, `continue` and `break`, on the `if`'s line or as the last line under it), and `&&`, `||`, `c ? a : b` on such tests. The narrowing holds for a plain name, not for a field chain: bind the value with `let` first. `find()`, `findLast()`, `pop()`, `shift()` and `at()` give `T?`. `xs[i]` gives `T` (the checker does not know the length). ### What is refused | You write | Message | |---|---| | `n == "1"` (different types) | `H066`: always false | | `s - 1`, `s * 2` on a non-number | `H065`: convert it with `Number(…)` | | `` `${xs}` ``, `text user` (a list or record as text) | `H069`: use `for`, `.join(", ")`, or show a field | | `text someBytes` | `H069`: show it as `.hex()`, `.base64()` or `.text()` | | `image p` where `p` is an `image` (pixels) | `H069`: show it as a file, `img.png(p)?.url("image/png")`, or draw it ([media.md](media.md#mental-model)) | | `xs.length()` | `H063`: `length` is a value | | `any`, `boolean`, `String`, `null` as a type | `H073`, with the right word (`json`, `bool`, `string`, `none`) | ## Logic ```mote // docs: whole state xs = [3, 1, 2] state name = "" state n = 0 fn size(n: number): string match n 0 return "none" 1, 2 return "few" else return "many" action work let first = xs.at(0) if first == none return xs.push(first + 1) for x in xs if x == 1 continue if x > 100 break n += x let i = 0 while i < 3 i += 1 if n > 10 name = "big" else name = "small" let copy = [...xs, 9] let rec = {n, name, ...{extra: true}} log(copy, rec, i > 1 ? "a" : "b") text `${size(xs.length)} ${name}` button "work" press=work ``` - `let x = e` · `let x: T = e` · `x = e`, `+=`, `-=`, `*=`, `/=` A `let` is seen from its line to the end of its block. A block declares a name once: a second `let` of it, or a `let` of one of the fn's parameters or of the loop's own name, is refused (`H022`; write `x = e` to change it). An inner block (under an `if`, a `for`, a `while`) may declare a name an outer one has, or a `state`'s: the outer one is back after the block. Its own value may not read the one it hides (`let n = n + 1`: `H022`). In markup the block is the `if`, `for`, route or component a `let` is in, whatever element it is written under. - `if c` + block, `else if c`, `else` · `if c stmt` on one line, and `if c stmt else stmt` (the `else` may also go on the next line). On one line an `else` is always the `if`'s, never the fallback of a call that can fail (`if p save(p) else p` is refused, `H081`, and says so): put such a call, with its own `else`, on a line of its own under the `if`. - `for x in xs` · `for x, i in xs` (`i` counts the turns from 0, as in markup) · `while c` · `return e` · `break` · `continue` - `atomic` + a block: the model operations in it are one ([models.md](models.md#atomic)) - `x => e` · `(a, b) => e` (a lambda is one expression) - `c ? a : b` · `a ?? b` · `a?.b` · `!a` · `-a` - `+ - * / %` · `< <= > >=` · `==` and `!=` are strict · `&&` `||` - `& | ^ ~ << >> >>>` on numbers, as 32-bit integers (JavaScript's). They bind tighter than a comparison and looser than arithmetic, `<< >> >>>` tightest, then `&`, `^`, `|`: `x & 1 == 0` is `(x & 1) == 0` (not JavaScript's reading), `c >>> 1 ^ poly` is `(c >>> 1) ^ poly`, `1 << n + 1` is `1 << (n + 1)`. `>>> 0` makes a result unsigned. In markup, as any operator, they go in parentheses: `text (flags & 4)`. - `` `text ${e}` `` (may span lines) · `"text"` or `'text'` with `\n \t \r \\ \"` - `r"\d+"`: a raw string, nothing in it is an escape, a backtick and a quote `'` included; it ends at the next `"` ([text.md](text.md#patterns)) - `[a, ...b]` · `{k: v, k, ...o}` · `true` `false` `none` - Numbers: `12`, `1.5`, `2e3`, `0xff`. Colours are values too: `#0a84ff`, `#fff`. - `// a comment` to the end of the line. The `//` lines directly above a declaration (or a shape's or model's field) are its documentation: an editor shows them where the name is hovered ([editor-plugin.md](editor-plugin.md#comments-that-document)). ### match ```text match x arms indented: values (comma-separated), or else 0 return "none" an arm is one statement, or a block under it 1, 2 return "few" else return "many" ``` `match` compares with `==`, top to bottom. It is the same in markup, with markup under each arm ([markup.md](markup.md#control)). ### Writes State is written by assigning it, or by changing it in place: `push`, `pop`, `shift`, `unshift`, `splice`, `sort`, `reverse`, `fill`, `remove(x)`, and `t.done = true`. Writes are allowed only in an action, a `{…}` handler, a task or a timer. The compiler traces each write back to the state the value came from and tells that state's readers (`emit.rs`, `Gen::write` and `Gen::srcs`). So this works, though `t` is a local: ```mote action finish(id: string) let t = todos.find(t => t.id == id) if t t.done = true // tells `todos` ``` `xs.remove(x)` takes the first `x` out of a list. `xs.sort()` in a binding or a derive is refused, because it changes the list: write `toSorted()` (likewise `toReversed()`), or sort in an action. ### Built in | Call | Gives | |---|---| | `uid()` | A new unique id (a UUID string). | | `now()` | The moment, in milliseconds. | | `log(x, …)` | Writes to the console. | | `time.clock(now())` | `"2:22 PM"`, as the reader's own place writes it. In a zone, a language, 12 or 24 hours: [time](#time). | | `time.date(now())` | `"Thu, Nov 12"`, likewise. | | `url.encode(text)` `url.decode(text)?` `url.parse(text)?` `url.build({…})` `url.query(text)` `url.form({…})` | Addresses ([below](#addresses)). | | `store.get(k)` `store.set(k, v)` `store.remove(k)` | `localStorage`, values as JSON. `store.get` gives `none` when there is nothing. | | `go("/path")` `back()` `forward()` `route.path` | Addresses ([markup.md](markup.md#routes)). | | `route.url` `route.origin` `route.link("/path")` | The page's whole address, its origin, and the whole address of one of its paths ([markup.md](markup.md#routes)). | | `route.fragment` `route.setFragment(text)` `route.takeFragment()` | What stands after `#` where routes are paths: read, changed, or read and taken out of the address ([markup.md](markup.md#the-fragment)). | | `net.online` | Whether the page can reach out: the browser's word (not for a page served from this machine), and the line to the back end ([back-end.md](back-end.md#is-there-a-line-netonline)). Reactive. | | `screen.visible` `screen.focused` `screen.idle(ms)` | Whether the page is in front, has the keyboard, and has been left alone ([markup.md](markup.md#in-front-and-at-it)). | | `toast("Saved", "A second line", "error")` | A note in the corner for four seconds; the last two are optional. Which corner: `app … toasts="top"` ([app](#app)). Three notes show at most; more wait their turn (and hurry the oldest along). A note stays while the pointer is on it, and only a note's own box takes presses: what is beside and between the notes can still be pressed. | | `title("(3) Inbox")` `badge(3)` | The page's title, and a number on the app's icon; `title("")` and `badge(0)` put back and take away. Kept current from state by `root title=… badge=…` ([markup.md](markup.md#values-of-the-whole-page)). | | `share()` `share({title, text, url, files})` | Opens the share sheet with the page (its title, description and address), or copies the link and says so where there is none. Gives `"shared"`, `"cancelled"`, `"copied"` or `"shown"`; never fails ([data.md](data.md#share)). | | `copy(text)` | Puts text on the clipboard. It never waits or fails; reading the clipboard, or putting a picture on it, is `clipboard.…` ([data.md](data.md#clipboard)). | | `close()` `close("id")` | Closes the popover or dialog the reader is in; the one with that id ([markup.md](markup.md#popover-and-tip)). | | `focus("id")` | Puts the keyboard in the element with that id (wherever it was drawn: another component's field too); a field's caret is where it was, as with `el.focus`. `focus("id", true)` also selects a field's words, ready to be typed over. | | `scroll("id", where)` | Scrolls that element: `"start"`, `"end"`, `"next"`, `"prev"` (a screenful), or the id of something inside it to bring into view. A third `{behavior: "instant"}` does it at once. | | `scroll(target, {inside, block, behavior})` | Brings an element (an id, or a `ref=`'s) into view: `block` `"start"` `"center"` `"end"` `"nearest"`, `behavior` `"smooth"` `"instant"`, `inside` the one scroller to move ([events.md](events.md#the-element-itself)). | | `fail("why")?` | Ends the fn or action with that failure ([below](#a-call-that-can-fail)). | | `s.isEmpty()` `xs.isEmpty()` | Whether a string or a list is empty. | JavaScript's own methods on strings, lists and numbers are there under their own names (`trim`, `split`, `map`, `filter`, `find`, `reduce`, `toFixed`, …), and so are `Math`, `JSON`, `Date`, `Number`, `String`, `Object`, `Array`, `Boolean`, `parseInt`, `parseFloat`, `isNaN`, `structuredClone`, `performance`. There is no `new`: use `Date.now()` or `now()`, not `new Date()`. `Map` and `Set` are named but cannot be made without `new`; use a record or a list. The checker knows the common methods' types and suggests the right name for a habit from another language (`contains` → `includes`, `len` → `.length`, `append` → `push`). The namespaces (`net`, `db`, `sql`, `fs`, `img`, `re`, …) are listed in the [map](README.md#namespaces). ### time A moment is a number: milliseconds, as `now()` gives. `time` writes one down, and does sums on one, in a zone and a language. None of it waits or fails, so all of it may stand in a binding. ```mote // docs: whole state zone = "Asia/Tokyo" state at = now() fn tomorrowAtNine(from: number, z: string): number let p = time.parts(from, z) return time.of({...p, day: p.day + 1, hour: 9, minute: 0, second: 0}, z) column gap=4 text `${time.clock(at, {zone, hours: 24})} there, ${time.clock(at)} here (${time.zone()})` text time.date(at, {zone, lang: "de", style: "full"}) text `the reminder is ${time.words(tomorrowAtNine(at, zone), {from: at})}` select value=zone for z in time.zones() option z value=z ``` | Call | Gives | |---|---| | `time.clock(at, {zone, lang, hours, seconds}?)` | `"2:22 PM"`. `hours: 12` or `24` (unsaid: as the language has it); `seconds: true` adds them. | | `time.date(at, {zone, lang, style, year}?)` | `"Thu, Nov 12"`. `style`: `"short"` Nov 12 · `"medium"` (unsaid) · `"long"` November 12, 2026 · `"full"` Thursday, November 12, 2026 · `"numeric"` 11/12/2026 · `"month"` November 2026 · `"weekday"` Thursday · `"iso"` 2026-11-12 (the same in every language). `year: true` adds the year to the short ones. | | `time.words(at, {from, zone, lang, style}?)` | How far `at` is from `from` (unsaid: now): `"now"`, `"in 20 minutes"`, `"3 hours ago"`, `"yesterday"`, `"tomorrow"`, `"in 3 days"`, `"last week"`, `"2 months ago"`. Within an hour, by the minute; on the same day (or under six hours), by the hour; past that by the calendar in `zone`. `style`: `"long"` (unsaid), `"short"`, `"narrow"`. | | `time.parts(at, zone?)` | `{year, month, day, hour, minute, second, weekday, offset}`: the calendar and the clock there. `month` is 1 to 12, `weekday` 0 (Sunday) to 6, `offset` the minutes the zone is ahead of UTC at that moment (Berlin in summer: 120). | | `time.sleep(ms)` | Waits that long and does nothing else: the pause of a poll that asks again (`replicateWait` in [replicate.md](replicate.md)). The one call of `time` that waits, so it is a statement, in a fn or an action. In a test (`mote test`) it does not wait. | | `time.of({year, month, day, hour?, minute?, second?}, zone?)` | The moment that reads so there. A number past its end carries on (day 32 is the 1st or 2nd of the next month; hour 25 is one o'clock the day after), so `{...p, day: p.day + 1, hour: 9, minute: 0}` is tomorrow at nine whatever the clocks do in the night. | | `time.add(at, {years, months, weeks, days, hours, minutes, seconds}, zone?)` | `at` moved on (or back, with negatives). Years to days go by the calendar there: the clock reads the same afterwards, also across a change of the clocks, and the 31st plus a month is that month's last day. Hours and less are exact. | | `time.next({hour, minute?, weekday?}, zone?, from?)` | The first moment after `from` (unsaid: now) at which a clock there reads that hour and minute; with `weekday` (0 Sunday to 6), on that day of the week. For work that is due at a time of day ([back-end.md](back-end.md#at-a-time-of-day)). Once a day whatever the clocks do: a time they skip that day is met an hour later (02:30 on the night they go forward is 03:30), and one they repeat is its first time only. | | `time.startOf(at, unit, {zone, lang, first}?)` `time.endOf(…)` | The first moment, and the last millisecond, of the `"minute"`, `"hour"`, `"day"`, `"week"`, `"month"` or `"year"` that `at` is in. A week starts on `first` (0 Sunday to 6), else where `lang` starts its weeks. | | `time.stamp(at, zone?)` | `"2026-11-12T14:22"`: what an `input type="datetime-local"` holds. `.slice(0, 10)` is what `type="date"` holds. | | `time.read(stamp, zone?)` | The moment such a stamp (or a date alone, `"2026-11-12"`: its first moment) names there: a `number?`, `none` for anything else. | | `time.zone()` | This device's zone: `"Europe/Berlin"`. The page's alone (`H092` on the back end). | | `time.zones()` | Every zone there is, `"UTC"` first: about 400 names, as `Intl` lists them. | | `time.weekStart(lang?)` | The day a week starts on there: 0 (Sunday) to 6. `"en-US"` 0, `"de"` 1, `"ar-EG"` 6. | - A **zone** is an IANA name (`"America/New_York"`, `"UTC"`); a **language** is a tag (`"de"`, `"en-GB"`, `"ja"`). Left out, each is the reader's own. One nobody knows counts as left out: nothing here throws, so a binding may be given a zone a person typed. `time.zones().includes(z)` says whether a zone is known. - **An hour the clocks skip** (02:30 on the night they go forward) is read by `time.of` as the hour after (03:30); **an hour they repeat**, as its first time. - **On the back end there is no reader.** In a `server fn`, what depends on a zone must be given one (`H064`: `time.clock(at, {zone: m.zone})`), and `time.zone()` is refused: keep each person's `time.zone()` in their row, written by their page. A language left out there is English. (A plain `fn` that both sides call is checked as the page's; where it runs on the back end without a zone, the zone is UTC.) - `now()` is not followed: a page that shows "in 20 minutes" keeps a state it sets `every 30000` and passes it as `from`. Built on the host's `Intl` (`runtime/shared/time.mote`, part `TI`), so the words are the browser's (or Bun's) own. Recorded in `tests/expect/real_zone_lang_page.txt` and `tests/expect/real_server_net.txt`. ## A call that can fail Every call that leaves the page can fail: the network, storage, a battery, a back-end call. Its type is written `T!` in messages. It must meet one of these at once, or it is refused (`H081`): ```text x else fallback the fallback on failure x else err => … the handler gets the failure's message (a string) x? pass the failure on x else err => (… ? y : err?) settle some failures, pass the others on as they came ``` ```mote // docs: whole shape Post id: number title: string state report = "" fn count(url: string): number let xs: Post[] = net.get(url)? return xs.length action tally let a = count("posts.json") else -1 let b = count("nope.json") else err => err.length let c = count("more.json")? report = `${a} ${b} ${c}` column button "Tally" press=tally disabled=pending(tally) text report if failed(tally) text `It failed: ${failure(tally) ?? ""}` color=danger ``` A `?` right before the `:` of a `c ? a : b` is the first branch's own: `n = c ? one()? : two()?` passes either call's failure on. What `?` does depends on where it is: - **In a fn**, `?` makes the fn one that can fail: its callers must settle it in turn (`count` above). - **In an action**, a task or a `{…}` handler, the action stops there. An action keeps the failure: `failure(action)` is its message (a `string?`), `failed(action)` whether there is one, `pending(action)` whether a run is in flight. So calling an action cannot fail. A fault (nobody answered, the back end broke, something threw) is also logged to the console; a failure the program made on purpose is not (below). - **In a binding or a derive** there is nowhere for it to go: `?` is refused there. Use `else`. A `?` may be followed at once by more: `Note.add(row)?.id` (the `?`, then `.id`), `count()? == 0`, `find()? ?? []`. After a test on one line it ends the test: `if Room.has({name})? return`. (A `?` begins `c ? a : b` only when the `:` follows.) `pending`, `failed` and `failure` take the name of an action or a resource (`H083` otherwise). They are reactive: `button "Save" disabled=pending(save)`. `pending` also takes a row of a model: `pending(m)` is true while a write of that row, which the page has already shown, has not been answered by the back end ([models.md](models.md#a-write-shows-at-once)). `fail("out of stock")?` makes a failure on purpose. It works in a fn or an action, in the page and on the back end; the caller's `else` or `failure(action)` gets the words. Such a failure is an answer, not a fault: an action it stops (whether or not the action waits) keeps the words for `failure(action)` and writes nothing to the console. The same goes for what a `server fn` said with `fail`, a model's `check … else "why"` and a rule's refusal. So a person's mistake can be said with `fail` and shown from `failure(action)`. A failure is its words wherever it is put in text, and also says what kind it is: under `else err => …`, `err.kind` (`"offline"`, `"signin"`, `"refused"`, `"invalid"`, `"toobig"`, `"full"`, `"memory"`, `"taken"`, `"fault"`, `"said"`, or the program's own word), `err.id`, `err.data`, `err.where` and `err.words`; of an action or a resource, `failure(save)?.kind` and the rest. `fail("out of stock", {kind: "stock", data: {sku}})?` gives one its kind and data. **`err?`**, in the handler, passes the failure on as it came (its kind, data and id; a fault stays a fault): `Note.add(row) else err => (err.kind == "taken" ? none : err?)` settles one kind and lets the rest go to the caller, where `fail(err)?` would make a new failure, of the kind `"said"`, from its words. `err?` stands only in such a handler (`H080` elsewhere, as for any `?` after a value that cannot fail). `on failure(f)`, at the top level, hears every failure nothing else did. All of it, with the back end's side, is in [back-end.md](back-end.md#when-something-fails). `log.info("msg", {fields})`, `log.warn`, `log.error` and `log.debug` are the console's in a page and [the log's](back-end.md#logs) on the back end. The words, shown: ```mote // docs: whole state when = "" state booked = 0 action schedule if when.trim() == "" fail("Say when.")? booked += 1 column gap=8 padding=16 input value=when placeholder="When?" button "Schedule" press=schedule if failed(schedule) text (failure(schedule) ?? "") color=danger text `${booked} scheduled` color=dim ``` `let xs: Post[] = net.get(url)?`: a `json` result takes the type its `let` gives it. The type is trusted, not checked at run time. Only actions, fns, handlers, tasks and resources can wait. A binding or a `=>` cannot (`H082`): use a resource, or a `for` loop in an action instead of `map` with a waiting call. **A `=>` may start an action that waits.** A `=>` that is nothing but a call of an action (`x => upload(x)`, `e => pasted(e)`) begins the action and gives none at once; the action goes on by itself, with its own `pending(upload)` and `failure(upload)`. That is what a callback wants: a timer, `xs.forEach`, a handler given to something a `json` value holds. ```text action upload(f: File) // waits f.url = files.upload(f.data)? action sendAll picked.forEach(f => upload(f)) // all begun, side by side; the next line does not wait for them widget.on("change", e => changed(e)) // `widget: json`, what a fn of an `extern js` file gave ``` To have them one after another, and to go on only when they are done, call the action in a `for` loop: there a call waits. A `=>` that starts an action is for where state may change (an action, a handler, a task, a `watch`): in a binding or a `fn` it is refused (`H030`). **`wait(p)`** waits for a promise that a `json` value holds, and gives what it comes to, as `json` (what is not a promise is itself). A promise that is refused is a failure, so it meets `?` or `else` like any call that can fail: ```text action finish(widget: json) // what a fn of an `extern js` file gave (js.md) let text = wait(widget.value()) else "" // a promise it gives, or "" if it is refused let done: json = wait(widget.ready)? // what is not a promise is itself ``` Mote's own calls never need it: they wait by themselves (`clipboard.text()`, `net.get(url)`). How it works underneath: a waiting action compiles to `AC(action, async () => {…})` (`runtime/page/actions.mote`, part `AC`), which counts runs in flight in a signal, catches what is thrown, and puts the message in another signal. `x else y` is a `try`/`catch` around the call. ## bytes ```mote // docs: whole state b: bytes = bytes("hi") state shot: bytes? = none action go let h = bytes.hex("6869")? let g = bytes.base64("aGk=") else bytes("") log(b.text(), b.hex(), b.base64(), b.length, b[0], b.slice(0, 1), h, g) if shot image shot.url() link "Get it" href=b.url("text/csv") button "go" press=go ``` **Making them** | Call | Gives | |---|---| | `bytes("text")` | The text's UTF-8. | | `bytes.new(n)` | `n` zeros. | | `bytes.of([72, 105])` | Bytes from a list of numbers. | | `bytes.join([a, b, c])` | Them end to end, as new bytes. | | `bytes.hex(s)` · `bytes.base64(s)` · `bytes.base64url(s)` · `bytes.base32(s)` | Text read back into bytes. Each can fail. base64url is RFC 4648's section 5 (`-` and `_`, no padding needed); base32 its section 6 (A to Z and 2 to 7, as a TOTP secret is written: case, spaces and padding are let be). | | `bytes.find(b, what, from?)` | Where a run of bytes (or a text's UTF-8) first stands in `b`, from `from` on: a number, -1 where it does not. | | `bytes.buffer()` | Bytes that grow as they are added to, for a message built piece by piece: `w.add(data)` (bytes, or text as UTF-8), `w.byte(n)`, `w.put("i32be", n)` (a number of a kind `b.write` takes), `w.length`, `w.bytes()` (a copy of all of it), `w.clear()`. Each but the last two gives the buffer back, so they chain: `bytes.buffer().add("Q").put("i32be", 9).bytes()`. | **Reading them** | Form | Gives | |---|---| | `b.length` · `b[i]` | How many · one byte, a number 0 to 255. | | `b.slice(from, to)` | A copy of a part; `b.slice()` of it all. | | `b.text()` `b.hex()` `b.base64()` `b.base64url()` `b.base32()` | Them as text (base64url with no padding, base32 with it). | | `b.text("windows-1251")?` | Them as text in a character set, by any of its WHATWG labels (`latin1`, `iso-8859-2`, `koi8-r`, `cp1252`, `shift_jis`, …). It can fail, `"unsupported"`: a label that names no set, or a set not read where it runs. UTF-8 and UTF-16 everywhere; the 28 single-byte sets by tables of the standard's own, and the multi-byte ones (Shift_JIS, EUC-JP, ISO-2022-JP, GBK, gb18030 with its four-byte ranges, Big5 with Hong Kong's extensions, EUC-KR) by the charsets battery, the standard's own decoders and index files: the same text in a page, a worker and the back end, malformed bytes too (U+FFFD where the standard says, which a browser's own decoder does not always: [The legacy multi-byte sets](#the-legacy-multi-byte-sets)). `runtime/shared/charsets.mote` and `batteries/charsets`, made by `node tools/charset-tables.mjs` from the WHATWG Encoding Standard's files at a pinned commit. | | `b.read(at, "u32")` | A number of several bytes, starting at `at`. | | `a.dot(b)` | Two vectors of 32-bit floats (laid end to end, as `write(at, "f32", v)` lays them; of one length) multiplied number by number and added up: the cosine of two of length 1, all at once and fast. A vector store's search ([ai.md](ai.md#retrieval)). | | `b.url()` | An address for them, for `image` and `link`: `image shot.url()`, `link "Get it" href=file.url("text/csv")`. | **Writing into them**, as a list is written into: | Form | Does | |---|---| | `b[i] = v` | One byte. It keeps the low eight bits of `v`. | | `b.set(other, at)` | Lays bytes, or a list of numbers, in from `at`. They must fit. | | `b.fill(v, from?, to?)` | That byte throughout, or over a part. | | `b.write(at, "u32", v)` | A number of several bytes. | ```mote // docs: whole state said = "" fn packed(parts: bytes[]): bytes let head = bytes.new(8) head.set(bytes("MOTE"), 0) head.write(4, "u16", 1) head.write(6, "u16be", parts.length) let all = [head] for p in parts let n = bytes.new(4) n.write(0, "u32", p.length) all.push(n) all.push(p) return bytes.join(all) action build let file = packed([bytes("one"), bytes.of([1, 2, 3])]) let b = file.slice(0, 8) b[0] = 104 b.fill(0, 4) said = `${file.length} bytes, version ${file.read(4, "u16")}, ${file.read(6, "u16be")} parts, ${b.hex()}` button "Build" press=build text said ``` - **The kinds** `read` and `write` know: `i8` `u16` `i16` `u32` `i32` `f32` `f64`, little-endian; `u16be`, `u32be` and the like for big-endian. A single unsigned byte is `b[i]`. Another word is refused (`H064`). - **Who may write.** Writing into bytes is a write like any other: into state, only in an action. A `fn` writes only into bytes it made itself (`bytes.new`, `b.slice()`), never into a parameter (`H030`): take a copy with `.slice()`, write into that and return it. - **A slice is a copy.** Writing into it leaves what it was cut from alone. - Bytes made in a worker fn come back moved, not copied; bytes the page made itself may be written into and still be moved to a worker ([reactivity.md](reactivity.md#what-is-copied-and-what-is-moved)). - A page cannot show bytes: pick a form (`.hex()`, `.text()`, `.url()`). - The address `b.url()` gives is given up when the bytes are (`runtime/page/batteries.mote`, part `BU`). - All of it works in a worker fn and in a `server fn` too. Bytes are a `Uint8Array` underneath (`runtime/shared/bytes.mote`: parts `BY`, `BYJ`, `BYN`). Compressing them is `zip` ([data.md](data.md#zip)). ### The legacy multi-byte sets `b.text(label)` reads the seven multi-byte encodings of the WHATWG Encoding Standard (Shift_JIS, EUC-JP, ISO-2022-JP, GBK, gb18030, Big5, EUC-KR, by any of their labels: `sjis`, `ms932`, `gb2312`, `big5-hkscs`, `ks_c_5601-1987`, …) with the **charsets battery** (`batteries/charsets`): the standard's own decoders, step for step, over tables made from its index files at a pinned commit, with its error handling (a malformed sequence is U+FFFD where the standard says one, and a byte the standard reads again is read again). It is the same wasm in a page, in a worker and in a `server fn`, so a text reads the same everywhere, byte for byte, whatever the host's own decoder does: ```mote // docs: whole state said = "" fn greeting(b: bytes, label: string): string = b.text(label) else "?" server fn greetingThere(b: bytes, label: string): string requires anyone return greeting(b, label) action read let sjis = bytes.of([130, 177, 130, 241, 130, 201, 130, 191, 130, 205]) let big5 = bytes.of([167, 65, 166, 110, 129, 128]) said = `${greeting(sjis, "shift_jis")} ${greeting(big5, "big5")} / ${greetingThere(big5, "big5")?}` button "Read" press=read text said ``` - **Why not the browser's own.** A browser's `TextDecoder` reads every valid sequence of these as the standard does, but Chrome (149) parts from it on some malformed ones: in Big5 a lead byte followed by a byte from 0x80 that names nothing is two U+FFFD in Chrome and one in the standard; in ISO-2022-JP an escape that is not one, followed by 0x0E, 0x0F or a byte from 0x80, loses an error. A message read on the page would then differ from the same message read on the back end. (Bun 1.4 reads these sets too, and as the standard does; the battery makes the answer not depend on which Bun.) `tests/all.sh real_charsets` holds the battery to every pointer of every index and to the browser, record by record, and says where the browser parts. - **Fetched only where it can be used.** The compiler gives the battery to a program only where a `b.text` can be given one of these labels: a label that is not written out (it is known when it runs), or one written out that names one of the seven. `b.text("latin1")` and `b.text("utf-8")` bring nothing. Where it is given: on the back end it is inside `server/main.js` (about 90 KB deflated), made when such a text is first read; on a page of `mote build` it is a file of the build (`assets/charsets..wasm`, 178 KB, 88 KB gzipped), brought before the code that can read one runs, as `re`'s engine is ([internals.md](internals.md#batteries)): the page waits for it at its start where its own lines can read one (its head asks for the file as the page arrives), else a component that can is drawn once it is here; an `off fn` that can read one asks for it before it runs, in its worker. In a page that is one file (`--single`) it is inside the page. - If the file cannot be fetched, the read fails with kind `offline`. ## Files and `use` ```mote use "./parts.mote" ``` `use` brings in that file's declarations: its states, fns, actions, shapes, components, resources. Of what the file would show, only its tasks and timers are kept: a named task in a used file starts with the page. Paths are relative to the file that says `use`. A file reached twice (by two spellings or from two files) is read once. All files share one set of names. There are no modules and no exports. Two folders beside the entry file ship with the page: - `public/`: every file ships as it is, under its own name (`net.get("posts.json")`). - `assets/`: only the files a page names ship, checked at build time ([markup.md](markup.md#pictures-and-assets)). ## Packages Another project's files: ```mote use "pkg:shop/engine/resolve.mote" ``` with a `mote.toml` beside the entry (or in a folder above it) that says where the package is: ```toml [packages] shop = "../libs/shop" ``` Local folders only; nothing is fetched. A `use "pkg:name/…"` is looked up in the `[packages]` of the program's own `mote.toml` (the nearest at or above its entry) first, wherever the line is written: so a package's file may take another package for the program (`use "pkg:usage/usage.mote"` in the admin extension's `usage.mote`), the program saying where both are. A name the program's `mote.toml` does not have is looked up as before, from the nearest `mote.toml` at or above the file that says `use`. A missing file or package is `H091`. ### What a package wants of its taker A package says, at the top of a file, the fns it calls and the program is to write: ```mote // docs: whole // (In a package: what it wants of the program that takes it.) wants fn shopMay(): bool wants fn shopGreeting(name: string): string = `Welcome, ${name}` // (In the program: its own `shopMay`; `shopGreeting` is left to the package's default.) fn shopMay(): bool = true state said = "" action hello said = shopMay() ? shopGreeting("Ada") : "" button "Hello" press=hello text said ``` - **`wants fn name(params): type`**, required: the program declares a fn of that name, or the build says, at the program's entry, what to write: `the program must declare fn usageMay(): bool for pkg:usage` (`H166`, with the fix and where the package wants it). - **`wants fn name(params): type = expr`** (or a block under it): optional. What follows `=` is the fn where the program declares none; the program's own declaration takes its place where it does. - **The program's declaration is checked against what is wanted**: the same parameters, the same types, the same type given back (`H166`, with the line to write). It may be in any file of the program, or in another package (the admin extension's `usage.mote` declares the usage extension's `usageMay`). Two packages that want a fn of one name want it alike. A name is still declared once: a second `fn usageMay` is `H022`. - **Whether it can fail is the taker's to say**: in a package's file `else` and `?` after a call of a wanted fn are right either way (no `H080`), the program's fn or the default being whichever it is. A package may also call a fn it does not declare at all, as before; `wants` is what says so where the build can check it. ## Refused, with the fix in the message Every diagnostic has a stable id (`H0xx`), a position, one line of what is wrong, and where possible the text to write instead. `mote check --json` gives them as data ([cli.md](cli.md#mote-check)). | You write | Write instead | |---|---| | `null`, `undefined` | `none` | | `xs.sort()` in a binding or derive | `toSorted()`, or sort in an action | | `xs.contains(x)` `s.len()` `xs.append(x)` | `includes` · `.length` · `push` | | `any` `boolean` `String` | `json` · `bool` · `string` | | `fn f(a)` | `fn f(a: string)`: a parameter needs a type | | `state xs = []`, `state x = none` | `state xs: string[] = []`, `state x: string? = none` | | a write in a `fn` | make it an `action` | | `net.get(url)` with nothing after it | `else fallback`, or `?` | | `{a: 1}` as an attribute's value | `({a: 1})`: a bare `{…}` there is a handler | | a tab in indentation | spaces | | `x.constructor`, `x.prototype`, `x.__proto__`, `Object.getPrototypeOf`, `Object.defineProperty`; `eval`, `Function`, `globalThis`, `self`, `import(…)` (`H246`) | what it is for, in Mote's own words: a copy of a record is `{...x}`, its keys `Object.keys(x)`; for what the browser has and Mote does not, as a last resort, [`extern js`](js.md) | | `window`, `document`, `navigator`, `this` | these are not names in Mote (`H020`) | A program cannot reach the host's means of running text as code: the names above are refused, and a key worked out while it runs (`o[k]`, with `k` the word `"constructor"`) finds there only a stand-in that refuses (`TypeError: Mote does not run text as code`), on the page, in its workers and in the back end alike. Markup's refusals (`className`, `onClick`, `text Hello`, …) are in [markup.md](markup.md#refused). ## Pitfalls - **A one-line `if` holds one statement each side.** `if c a = 1 else a = 2` is fine; for more than one statement, use a block. - **A lambda is one expression.** For several statements, write a `for` loop or a fn. - **`let` with `none` has no type.** `let x = none` is `json`; write `let x: T? = none` if it matters. - **Narrowing needs a name.** `if a.b != none` does not narrow `a.b`; `let b = a.b` then `if b`. - **`persist` uses the state's name as its key.** Renaming the state loses what was kept. Two apps on one origin share `localStorage`. - **A fn that is to run in a worker cannot read state.** Pass what it needs ([reactivity.md](reactivity.md#workers)). - **No `new`, no classes, no `try`.** Failure is `else` and `?`. - **Numbers are plain decimals.** `0xff`, `1_000` and `.5` are not read; write `255`, `1000`, `0.5`. ## In the source | What | Where | |---|---| | Tokens, strings, indentation | `compiler/src/lex.rs`, `lex` | | Declarations, statements, expressions | `compiler/src/parse.rs`: `Parser::body`, `stmt`, `expr`, `ty` | | The tree | `compiler/src/ast.rs` | | Types, narrowing, the standard library's signatures | `compiler/src/types.rs`: `check`, `Checker::call`, `narrow`, `fit` | | Logic to JavaScript, tracing writes | `compiler/src/emit.rs`: `Gen::expr`, `Gen::call`, `Gen::write`, `Gen::items` | | Reading files, `use`, packages | `compiler/src/build.rs`: `load`, `package` | | Diagnostics | `compiler/src/diag.rs` | | Recorded behaviour | `compiler/src/tests.rs`; `tests/pages/*/app.mote` | # JavaScript of your own `extern js` names a JavaScript file of the program's own and declares, with types, the fns it exports; `extern script` puts another site's script in the page's head. Everything else in a Mote program is checked by the compiler; these two lines are where that stops. **They are a last resort**: kept small on purpose, and meant to be used as little as possible. Back to the [map](README.md). **Reach for something else first.** In this order: 1. **A battery or the kit**: what Mote already has (`db`, `sql`, `net`, `fs`, `img`, `pdf`, `font`, `gl`, the kit's components) is checked end to end and works on every side. 2. **An extension** (`use "pkg:…"`, [../extensions/README.md](../extensions/README.md)): a service such as a payment or mail provider is reached by an extension written in Mote, with no dependency. 3. **The service's HTTP API**, from a `server fn` with `net.*` ([data.md](data.md#net)): nearly every service has one, and the secret stays on the back end. 4. **A program on the back end's machine** with `proc.run` ([back-end.md](back-end.md#other-programs)): a command-line tool, or a script beside the app. **What `extern js` is for**, when none of those will do: a widget or SDK that exists only as a script in the browser and has no HTTP API (a map, a card form that must run in the page), or a small piece of glue to something the browser has and the language truly lacks. It is not a way to bring in npm packages, and it will not grow into one. `mote build`, `mote check` and `mote check --access` list every `extern js` file (with its fns) and every `extern script` as "outside what is checked", so a reviewer sees the edge at a glance. ```text extern js "./glue.js" fn confetti(count: number): none fn mapOf(el: element, opts: {lat: number, lng: number}): json fn later(words: string): {said: string, length: number} state box: element? = none state said = "" action burst confetti(80)? action show if box != none mapOf(box, {lat: 51.5, lng: -0.1})? let l = later("hello") else err => {said: err, length: 0} said = l.said column gap=8 padding=16 button "Burst" press=burst button "Map" press=show column ref=box height=300 text said ``` ```js // glue.js, beside app.mote export function confetti(count) { /* … */ } export function mapOf(el, opts) { const map = new SomeMap(el, opts); el.addEventListener("mote:gone", () => map.destroy()); return { zoom: map.zoom }; } export async function later(words) { return { said: words.toUpperCase(), length: words.length }; } ``` ## Mental model - A fn under `extern js` is a plain `fn` whose body is the file's export of that name. It is typed like any other: a call is checked against the parameters, and what it gives has the declared type. - **Every call can fail** (`else` or `?`, as for a call to the back end): the file's code may throw, and the file may not load. **Every call waits**: a promise the export returns is waited for, and the compiler waits for the call wherever it is, as it does for `net` (nothing says `async`). - **What comes back is checked** against the declared type, in every build: a text where a `number` was declared is a failure that says so (`wrong(…), from glue.js, is to be a number; it is a text`), and a record's fields and a list's items are checked too. So the program never goes on with a value that is not what its type says. What the program *hands* the file has been checked by the compiler already. - The file is loaded once, the first time one of its fns is called (an `import()` of it as a module), and kept for the life of the page. - A fn is placed as a plain fn is: on the page where the page calls it, on the back end where a `server fn` does, in a worker where an `off fn` does and the file says `off`. Each place loads the file for itself. ## The forms ```text extern js "./glue.js" a file of the program's own (.js or .mjs), from the file that names it fn name(a: T, b: U): R one line for each export the program calls; every type said extern js "./work.js" off the file touches no page: its fns may also run in a worker extern script "https://js.stripe.com/v3/" another site's script, in the head extern script "https://…/x.js" integrity="sha384-…" the same, refused by the browser if its bytes differ ``` The compiler reads the file and refuses a declared fn it does not export (`export function name`, `export async function`, `export const name`, `export class`, `export { a, b as name }` are all read; a file that says `export * from …` is not checked, since its names are not known until it runs). ### Types at the boundary | Declared | What the file is handed | What it must give back | |---|---|---| | `string`, `number`, `bool` | a string, a number, a boolean | the same (a number is finite) | | `bytes` | a `Uint8Array` | a `Uint8Array` | | `T[]`, `T?`, `{a: T}`, a `shape` | an array, the value or `null`, an object | the same, item by item and field by field (a shape is checked as its fields) | | `none` (the answer only) | | anything; it is dropped, and the call gives `none` | | `element` | the DOM element a `ref=` holds | an element | | `json` | the value as it is | anything, unchecked | | `(x: T) => none` | a fn the file may call later (an action started, or a lambda) | not checked | A **callback** is a parameter written as a fn type: hand it `w => heard(w)`, a lambda that is nothing but a call of an action, and the action runs each time the file calls it ([language.md](language.md#a-call-that-can-fail): a `=>` may start an action that waits). ### An element, and when it goes A parameter of type `element` is given the element itself (`state box: element? = none`, `ref=box` on it: [events.md](events.md#the-element-itself)), so a third-party widget can draw inside it. The page owns the element and may take it away (an `if` turns false, a route changes, a row is removed). When an element that was handed to a file leaves the page, it is sent a `mote:gone` event: the file listens for it to clean up. ```js export function chart(el, rows) { const c = new Chart(el, { data: rows }); el.addEventListener("mote:gone", () => c.destroy(), { once: true }); } ``` Draw only inside the element you were given; what is outside it is the page's, and the runtime redraws it as state changes. ### Where it runs | Who calls it | Where the file runs | What the file may use | |---|---|---| | the page (an action, a handler, a fn the page calls) | the page | `document`, `window`, the element it was handed | | an `off fn`, with `extern js "…" off` | a worker | no page: `fetch`, `crypto`, `WebAssembly`, its own code | | a `server fn` (and what it calls) | the back end, in Bun | Bun and Node's modules, npm packages | A file without `off` is the page's: an `off fn` that calls one of its fns is refused (`H244`), and a heavy fn that calls one stays on the page with it. A file reached only by `server fn`s is never shipped beside the page. ## What ships | Build | The page loads | The back end loads | |---|---|---| | `mote build` | `assets/..js`, kept a year by the browser, in the service worker's list (so it is there offline) | `server/js/..js`, beside `server/main.js`, never served | | `mote build --single` | the file inside the page, as a `data:` address | as `mote build` | | `mote dev` | the file as it lies, beside the entry; a change to it reloads the page | the file as it lies | Only the one file ships. A file that imports another of its own (`import "./helpers.js"`) will not find it once built: bundle them into one file first, or import by a whole address (`import x from "https://esm.sh/…"`), which the browser fetches as it would any module. **npm packages on the back end** are the program's own business, and not something Mote helps with (a service's HTTP API, an extension or `proc.run` comes first). The file may `import { PDFDocument } from "pdf-lib"`: Bun finds the package from where the file is. Under `mote dev` that is the file's own folder (a `node_modules` beside the entry); in a build, `server/js/`, so install the packages where the back end runs (`cd dist && bun add pdf-lib`, or a `node_modules` beside `dist`). Mote downloads nothing and bundles nothing. ## Another site's script `extern script "https://js.stripe.com/v3/"` writes `