yumemi
Have a sweet Gleam. 設計を書けば、コードが生まれる。
A framework for Gleam on Cloudflare Workers and AWS Lambda. You describe an application in five words — Entity, Property, Type, Service, Authorization — and write each Service's logic; yumemi derives the Gleam code around that logic (types, codecs, reads, authorization checks, writes, the route table, SQL) and the HTTP entrance to it. MCP and CLI entrances are designed to come from the same description but are not generated yet.
Open source, coming soon. https://gleam.canon-ical.com/
Status
Under development. The API may change between 0.x releases.
Extracted from the framework/ directory of a production application on 2026-09-16, history included. Since 0.12 the module namespace is yumemi/* (it was framework/* up to 0.11) and the generator is the module yumemi/gen of the same package, so the Hex package yumemi carries both: the generator that runs is the yumemi version your manifest.toml locks. The database schema the runtime reads is still named framework (db/queries/framework/*.sql, keys such as framework/outbox_claim).
Layout
| Module | What |
|---|---|
yumemi/spec yumemi/er |
Entity / Property / Type ── the model and its derivation |
yumemi/entry yumemi/verb yumemi/party yumemi/require |
Entrances and Authorization |
yumemi/step yumemi/effect yumemi/query yumemi/io |
Service logic: read / guard / apply / call / done |
yumemi/connector yumemi/page yumemi/blob yumemi/vector |
Connectors, SSR pages, R2, Vectorize |
yumemi/secret yumemi/sealed yumemi/time |
Secrets, sealed values, time |
yumemi/front yumemi/front/* |
Faces: Layout, Page, Frame, Style, the client runtime (navigate.mjs) |
yumemi/server yumemi/server/*.mjs yumemi/gate |
The back-end runtime the generated code imports, and a face's gate |
yumemi/server/target/*.mjs yumemi/server/aws/*.mjs |
The Workers and Lambda shells' runtime and the AWS calls (0.16.0) |
yumemi/kit |
The yumemi kit / yumemi gear command (0.16.0) |
yumemi/gen |
The generator (reads the app's Gleam sources, writes the derived Gleam, SQL and JS) |
The generator
Run it from any package that depends on yumemi (the app's api/, or a face):
gleam run -m yumemi/gen -- <app dir> <out dir>
For example, in a repository with api/ and faces beside it, cd api && gleam run -m yumemi/gen -- . .. writes the back under api/ and each face's files under the face's package. It exits non-zero when the output is incomplete; the exit code says who fixes it (yumemi/gen/stop).
One version (0.12, article 41). The generator reads the manifest.toml of the app package and of every face it writes, and stops (exit 4) naming the package whose locked yumemi differs from the version that is running (<dir>/manifest.toml: yumemi の lock <locked> が走っている生成器の版 <running> と違う); run gleam update yumemi there. A package without a manifest.toml is not checked, and packages the generator does not read or write (another app's auth service, say) are outside the check.
A face's priv/static/_yumemi/client.mjs is bundled with the esbuild the face's lockfile installed (<face>/node_modules/.bin/esbuild). When it is missing the generator stops with exit 3 and names the path — add esbuild to the face's devDependencies and run npm ci in the face. It does not fall back to npx.
Developing yumemi
npm ci # the esbuild the generator tests bundle with
gleam test # the runtime checks and the generator tests (fixtures in gen/fixtures)
gen/fixtures (sample apps) and gen/scripts (one-off verification scripts from earlier releases; the ones that ran the old yumemi_gen package were removed in 0.12) are not part of the Hex package.
To generate a fixture in place, run the generator from the root (gleam run -m yumemi/gen -- gen/fixtures/article gen/fixtures/article). The fixture faces have no package.json, so first link the root's esbuild into each face that has a client (public in article: mkdir -p gen/fixtures/article/public/node_modules/.bin && ln -s "$PWD/node_modules/.bin/esbuild" gen/fixtures/article/public/node_modules/.bin/esbuild); without it the generator stops with exit 3. When yumemi's [dependencies] change, run gleam update yumemi in each fixture face, or its client build cannot see the new packages.
Targets: Cloudflare Workers and AWS Lambda (0.16.0)
An app can run the same generated code on Cloudflare Workers, on AWS Lambda, or on both at once (for example one serving and one standing by). Declare the targets in src/server.gleam:
pub const targets: List(server.Target) = [server.Workers, server.Lambda(faces: [])]
Without targets the app reads as [Workers], and the generated output is that of 0.15.0 apart from the changes the CHANGELOG lists under "Upgrading from 0.15.0". yumemi does not deploy: the generator writes the shells and a table for your deploy script, and choosing and running the AWS and Cloudflare resources stays with the app.
The contract. The runtime no longer reads Workers bindings or execution directly. Each request carries a Target (yumemi/server/target.mjs): after(promise) for work after the response, secret(name) (a plain string or a Secret Store binding's .get(), null when absent), vars(name), outbox, limit, signal, app and assets. On Workers the generated shell.mjs builds it with workersTarget(env, execution). Hooks and connectors get x.after, x.secret and x.vars; prefer them over x.env and x.state.execution.waitUntil, which stay for 0.16.0. The runtime reads its own non-secret variables (<ENTRY>_HOST, COOKIE_DOMAIN, MCP_AUTHORIZATION_SERVER, the Origins variables) through vars. SECRET_HMAC, the Sealed key and the browser key may be plain secrets as well as Secret Store bindings.
What a declared app gets.
src/gen/build.mjs, the release mark{yumemi, input, targets}.inputhashes the yumemi release,manifest.toml, the declarations, every hand-written file undersrc/(any extension) and SQL, and the generated back.GET <prefix>/_yumemi/healthon each entry. It runsSELECT 1with a 2-second limit and answers 200 (or 503 when the database did not answer) with{"target","yumemi","input","db"}only: no authentication, no secret, no row. A standby that still runs an older Service or hook shows a differentinputfrom your localbuild.mjs. On Lambda an app withedgealso lists what Lambda drops indropped(below).- With
Lambda:src/gen/shell.lambda.mjs(exporthandler) andsrc/gen/targets.json, the table a deploy script reads — the handler, every env name markedvarsorsecret(including the framework's own,YUMEMI_OUTBOX_QUEUE_URLandYUMEMI_ORIGIN_SECRET), each cron expression paired with its EventBridge Schedulercron(…), the SQS mapping, the static files, and the CloudFront path split with the viewer-request Function.
What the generator stops (only in an app that declares targets).
- Article 58 (exit 4):
targetsis empty, names a target twice, or has aFaceEntrywhose face is not an entry. AFaceEntrymodule file that does not exist is exit 3. - Article 59 (exit 4, only with
Lambda): everyserver.cronexpression must translate to Scheduler — five fields, not both day-of-month and day-of-week set, weekdays by name only (SUN–SAT, ranges such asMON-FRI, lists such asTUE,THU, andFRI#2). Weekday numbers (0–7) and a loneLare refused because the two targets may read them differently. - Article 61 (exit 4): no route, alias or attached path may sit under an entry's
<prefix>/_yumemi/; that space (health,live,mcp,system/…and the other framework paths) is yumemi's. 0.15.0 did not check this. - Article 62 (exit 4): every env name a declaration reads is
[A-Z][A-Z0-9_]*, and withLambdanone of them is a name Lambda reserves (AWS_…,_HANDLER,LAMBDA_TASK_ROOTand the rest of Lambda's defined variables). - Not stopped: when the app declares
Lambdaand its ★ JS touches Workers parts (env.X.get(…),caches.default,new HTMLRewriter,new WebSocketPair, …), the generator prints oneexit 0warning with the first place and the count. ★ is the app's code, so the generator only warns.
The Lambda shell
yumemi/server/target/lambda.mjs exports lambda(app, options), which the generated shell.lambda.mjs calls. The one handler answers a Function URL (payload 2.0; set the invoke mode to RESPONSE_STREAM), an SQS event source (outbox delivery), EventBridge Scheduler (cron, with the input {"yumemi":"cron","cron":"<the Workers expression>","at":"<aws.scheduler.scheduled-time>"}) and the API Gateway WebSocket routes of the live signal. Any other event throws.
- Behind CloudFront. The handler answers 403 unless the
x-yumemi-origin-secretheader equals the secretYUMEMI_ORIGIN_SECRET, and only then takes the host fromx-forwarded-host. The viewer-request Function intargets.jsonoverwritesx-forwarded-hostfromHoston every request. Never pass the viewer's ownx-forwarded-hostthrough: a viewer could then claim any<NAME>_HOST. - Work after the response. Work passed to
x.afterstarts whenx.afteris called and is awaited after the response stream is closed; the handler waits for it before it returns. Work that fails is dropped. - Secrets. Names listed in the
secretsoftargets.jsonare read from Secrets Manager with the execution role's credentials and kept for five minutes. If a read fails, a value read earlier in the same execution environment is used, even after the five minutes, and one line naming the secret (never its value) is logged; without such a value the read throws. Any other name — a before-hook's or a ★ hook'sx.secret(name)included — is read as a plain string fromprocess.env. x.envon Lambda is a frozen copy of the string environment withoutAWS_SECRET_ACCESS_KEYandAWS_SESSION_TOKEN. Bindings (.get(),.send(), …) do not exist there.- Failures. A failure inside SQS delivery returns every message of the batch for redelivery. A failed Scheduler run logs one line without values and returns normally; the next wake and the cron sweep pick the work up. A response with no body keeps its status and headers.
- Body size. A request body that goes through the function is cut at about 4.5 MB (413) and a response at about 6 MB. Upload large media with
x.blobs.upload(below), whose parts do not go through the function. - Rate limits. API key rate limits are counted in Postgres (
framework.counter, one-minute windows) instead of Cloudflare's Rate Limiting binding. The Postgres count is exact where the binding is an approximate per-location count, and every API key request whose key resolves writes one statement — requests over the limit too, which on Workers are refused without touching the database. Unknown keys are refused with 401 without being counted. Applydb/framework/counter.sqlbefore deploying a Lambda target. - AWS calls.
yumemi/server/aws/holds SigV4 and four calls (SQSSendMessage, Secrets ManagerGetSecretValue, CloudFrontCreateInvalidation, API Gateway@connections), written with WebCrypto andfetchonly — no SDK, noaws4fetch. The signatures equal botocore's (a fixture test pins them). Credentials are the execution role's temporary keys (AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_SESSION_TOKEN,AWS_REGION), and the session token is signed too.
Faces on Lambda
The Lambda shell puts the app and every face in one function and routes by host and path: a path that starts with an entry's <prefix> or with media.path goes to the app, any other path to the face of the host's entry. A face's env.APP.fetch is a function call inside the same process, so it does not take a second concurrent execution.
- Bundling. Run
gleam buildin each face's directory and in the app's, then bundlebuild/dev/javascript/<app>/gen/shell.lambda.mjswith esbuild. The shell imports the faces' builds by relative path. Copy each face'spriv/staticfrom thestaticsentry'sfromintargets.jsonto itsto(static/<face>) in the function's bundle; the shell answers only the paths in the table the generator wrote. - Any bundler setting. The runtime tells the generated values apart by the export names of their modules, not by class names, so the back bundles with any setting —
esbuild --bundle --minifywithout--keep-namesincluded. The generator writessrc/gen/names.mjs(the app modules that declare constructors, imported bysrc/gen/registry.mjs). A value of a class that is in none of those modules fails withunnamed_typeand the class name in the log; regenerate the app if you see it. - A hand-written face entry.
server.Lambda(faces: [server.FaceEntry(face: "www", module: "worker/entry")])makes the entry of the facewwwthe modulewww/worker/entry.mjs: a path from the face's directory, without extension, outsidesrc/. Like a Workers main it exports adefaultwithfetch(request, env, ctx)(or a namedfetch). A face that is not an entry is exit 4, a missing file exit 3 (article 58). - Workers routes. yumemi does not write the
routesof yourwranglerfiles. For the app's Worker, list both<host><prefix>and<host><prefix>/*for each entry (and both<host><media.path>and<host><media.path>/*). With<host><prefix>/*alone, a request for the bare<prefix>or<media.path>goes to the face's Worker on Workers, while the Lambda shell sends it to the app, so the two targets answer it differently. - What differs from Workers. A face's env on Lambda holds only the strings of Lambda's environment: no bindings. Static files are answered only when the path equals a path in the table; the html extension rules (
/about→about.html) and_headers/_redirectsdo not exist on Lambda.
cron on both targets
- One run per scheduled time. In an app that declares
Lambda, both targets wake on the same expression, and each wake first inserts(expression, scheduled time)intoframework.cron_lease. Only the side that inserted the row runs the jobs; the other logs{"yumemi":"cron.skipped","cron","at"}and does nothing. Apply the generateddb/framework/cron_lease.sqlbefore deploying the shells. Lease rows are deleted after seven days. - At most once. If the lease insert fails, that wake runs nothing (skipping once is better than running twice;
EachDuerows come back on the next wake). A wake whose jobs fail after it took the lease is not run again by the other target. Watchlambda.failedlines with"entry":"cron"(and failed Workers cron runs); to run a lost wake again, delete itsframework.cron_leaserow and wake the job again.purgeIdempotencyand the other per-wake sweeps run only on the wake that took the lease. atis the scheduled time. In an app that declarestargets, a job'sat, the idempotency purge and the windows readcontroller.scheduledTime(Workers) and the Scheduler'sat(Lambda), so both targets see the same string.- Ids do not move on a retry. An outbox delivery derives its seed from the outbox row's id, and a cron job in an app that declares
targetsfrom(expression, scheduled time, job name[, row id]). A retried delivery or wake therefore gets the samenew_<entity>()ids, and the receiver can drop duplicates by id. The cron jobs of an app withouttargetsstill draw a new seed per run. These seeds are not secrets: a cron job's ids can be computed from the expression and the time, so never use them as capability keys in invitation tokens or URLs. - Workers Cron Triggers still need every expression in
wrangler.toml;targets.jsonlists the Scheduler side.
The live signal on Lambda
On Lambda the live signal uses an API Gateway WebSocket API. Point its $connect, $disconnect and $default routes at the function (function in targets.json) and route only the path <entry prefix>/_yumemi/live to that API in CloudFront; the browser keeps the same URL as on Workers. CloudFront adds the secret header x-yumemi-origin-secret and x-forwarded-host as for the Function URL, and passes the query token, Cookie and Origin to the API.
- Put the
@connectionsendpoint (https://<api-id>.execute-api.<region>.amazonaws.com/<stage>) in the function's envYUMEMI_LIVE_ENDPOINT, and give the execution roleexecute-api:ManageConnections. WithoutYUMEMI_LIVE_ENDPOINTLambda issues no tokens and sends no signals. - Connections are kept in
framework.live_socket(generateddb/framework/live_socket.sql; apply it before deploying) with their token's expiry. An expired connection gets no signal and is closed on each cron wake — every minute withserver.wakes, otherwise at the interval of the app's own cron.
Kits (0.16.0)
When yumemi has no word for what a face needs, look in this order: 1. a yumemi word (yumemi/front), 2. a kit this face or your kit home already has, 3. write a kit in Gleam, 4. an escape (src/escapes/<name>.mjs) only when JS is needed.
A kit is a Gleam package with [yumemi] kit = true in its gleam.toml, kept in your own place on your machine (~/.yumemi/kits/<name>/, each one its own git repo) and added to a face by path or by your own git — never Hex. Faces import it like any dependency, and yumemi checks it with the same rules as a face.
- Every package in a face's lock is checked. It must be yumemi's side (yumemi and the packages yumemi depends on), a kit, or on the allow table (
gleam_stdlib,gleam_json,gleam_time); anything else, or a package whose source cannot be read, stops with exit 4 (article 46). A package with a[yumemi]table from Hex stops (article 47). ★ and kit modules import only their direct dependencies and, of yumemi's side, only yumemi (article 48). - A kit is written like ★. Its modules pass the same surface articles (no lustre, no
@external, noel.element/el.raw_text), live undersrc/<kit>/, write nostatic_src,static_sheetorcss.Tokenliteral and no face shapes such ascomponents(article 49). A kit may hold escapes insrc/escapes/<name>.mjs(DOM name<kit>.<name>) and helper JS insrc/escapes/lib/; an escape's JS imports only yumemi's side, kits and the face's own build (article 52). - Generated escapes. Run
gleam run -m yumemi/gen -- --kit <kit dir>in the kit to check it and to writesrc/<kit>/gen/escapes.gleam. The face generator rebuilds that file and stops (exit 3) if it differs (article 50). A kit's yumemi requirement must fit in one minor (article 51).
The yumemi command. First time only, set up ~/.yumemi as a small Gleam package that depends on yumemi, and the command:
mkdir -p ~/.yumemi/kits ~/.yumemi/src && cd ~/.yumemi
printf 'name = "yumemi_home"\nversion = "0.1.0"\ntarget = "javascript"\n\n[dependencies]\nyumemi = ">= 0.16.0 and < 0.17.0"\n' > gleam.toml
gleam deps download
echo 'yumemi() { set -- "$PWD" "$@"; (cd "${YUMEMI_HOME:-$HOME/.yumemi}" && gleam run --no-print-progress -m yumemi/kit -- "$@"); }' >> ~/.bashrc
Then:
yumemi kit new <name> # scaffold a kit in your place
yumemi kit check <name> # run yumemi's kit checks on it
yumemi kit publish <name> # check, then push to your own git (origin)
yumemi kit add <name> [--git] # in a face: add the kit (absolute path, or your origin pinned to a commit sha)
yumemi kit add <url> # take someone's published kit into your place, check it, then add it
yumemi kit update <name> # in a face: move a git kit to the kit's current commit
yumemi kit remove <name> # in a face: drop the kit (your place keeps it)
yumemi kit list # your kits, their yumemi requirement, the last check
kit add writes an absolute path; commit faces that build elsewhere (CI) with --git. This yumemi command is separate from an app's generated CLI entrance.
Taking someone else's kit runs its code. yumemi kit add <url> (and yumemi gear add <url>) checks the package with the yumemi locked in that package's own lock, which means building it: its code runs on your machine before you have read it. Read a kit or gear before you add it from a URL you do not trust. When your app is generated, its own locked yumemi applies the articles again.
Dependencies by git or path. A face may depend on a Gleam package by git (kit = { git = "file://…", ref = "<sha>" }) or by an absolute or relative path (kit = { path = "…" }). The generator copies the face to a temporary build before bundling; local paths are made absolute from the face's own directory and the .git of a git dependency is not cached, so neither shape stops the generator. The dependency cache is keyed by the gleam.toml of every path dependency, and a build that re-resolves versions is not cached, so a kit edited in place is rebuilt.
Gears (0.16.0)
A gear is the back's kit: a Gleam package with [yumemi] gear = true, kept in your place (~/.yumemi/gears/<name>/, each its own git repo) and added to an app by path or by your own git — never Hex (article 53). The commands are the kit's, with gear in place of kit:
yumemi gear new <name> # scaffold a gear in your place (no targets: it must run on every target)
yumemi gear check <name> # run yumemi's gear checks on it (articles 54–57, without an app)
yumemi gear publish <name> # check, then push to your own git (origin)
yumemi gear add <name> [--git] # in an app: add the gear (absolute path, or your origin pinned to a commit sha)
yumemi gear add <url> # take someone's published gear into your place, check it, then add it
yumemi gear update <name> # in an app: move a git gear to the gear's current commit
yumemi gear remove <name> # in an app: drop the gear (your place keeps it)
yumemi gear list # your gears, their yumemi requirement, the last check
- Functions and types only.
pub const service,collectionandallowbelong to the app (article 54). - The target contract only. A gear's JS imports only files inside the gear,
yumemi/server/target.mjsand the allow table (gleam_stdlib,gleam_json,gleam_time): no npm, nonode:*, nocloudflare:*, and nox.env/env/process.envreads — read secrets and settings withx.secret(name)andx.vars(name)(article 56). Packages a gear imports, other than Hex packages and gears, get the same check. - No app names. A gear takes names from the app as arguments:
x.secret(name), notx.secret("API_KEY")(article 57). - Targets. A gear that needs Workers parts says so with
[yumemi] targets = ["workers"], and an app that declaresLambdacannot use it (article 55). Such a gear, and a gear's Workers module, may use bindings (x.env.NAME.get(…),keyFromBinding(x.env.KEK)); write the binding in one expression fromx.env.NAMEand do not put the wholex.envin a variable.
A gear that needs Workers-only parts can still run on both targets with one module per target:
[yumemi.targets.workers]
module = "egress_do" # may use bindings and cloudflare:*; may export a Durable Object class
[yumemi.targets.lambda]
module = "egress_direct" # may use node:*
The generated Workers shell imports the Workers module and the Lambda shell the Lambda module; nothing else does. Each target module hands its implementation to a shared file of the gear at load time (for example provide(f) in egress.mjs), and the rest of the gear calls through that shared file. A target module must not import the other target's module, and a shared file must not import a target module; for a .gleam module the check covers its @external files too (article 86). A relative import that points inside the gear but cannot be traced to one of its files (with ? or #, without an extension, or to a file that is not there) stops too (article 86), since it might reach the other target's module: write the file's path with its extension (<path>.mjs for a Gleam module).
From the app, point at a gear's module as "<gear>:<path>" (the path from the gear's src/, no extension) in Hook, Fetch, Pure and DurableObject. Hook, Fetch and Pure are loaded by both shells, so they point at the gear's shared files; a DurableObject may point at the gear's Workers module, and the Workers shell exports the gear's Durable Object only when the app writes such a DurableObject(module: "<gear>:<path>"). A path that cannot be read or a missing file is exit 3; a shared hook pointing at one target's module is exit 4 (article 85).
Limits of the check. The checks read the text of the JS. They catch slips, not deliberate detours: a binding reached through a destructured alias, x['env'], a spread and similar shapes is not found. Editing a path gear does not change the input of targets.json and build.mjs. An app's ★ that imports a gear's Workers module directly gets no warning.
yumemi/front ── Elements and attributes (0.12)
A Block, a Layout's Block and the docs page are written with yumemi's own element tree; a ★ module imports yumemi/front/el, yumemi/front/html, yumemi/front/attr and yumemi/front/css, and never lustre or sketch/lustre (the generator stops on that import, exit 4, article 1; a face's gleam.toml listing lustre / sketch_lustre stops too, article 2). There is no exception: interactive Components are written with the same words (below). A .gleam file placed by hand under a face's src/gen/ (one without the //// GENERATED first line) is read as ★ and checked the same way. A ★ module may not use @external (exit 4, article 4); JavaScript goes in a named escape (below).
import yumemi/front/attr
import yumemi/front/css
import yumemi/front/el.{type Element}
import yumemi/front/html
const card = [css.Color(css.Token("ma-color-ink")), css.Space(css.Padding, css.Px(16.0))]
pub fn view(it: In) -> Element {
html.section(css.class(card), [attr.data("slug", it.slug)], [
html.h1_([], [el.text(it.title)]),
html.a_([attr.href(it.link)], [el.text("more")]),
])
}
el.Elementandel.Attributeare opaque and take no type parameter.el.text/el.each/el.none/el.fragment, the framework words (el.opener/el.closer/el.badge/el.each_modal/el.img/el.notice/el.dialog/el.dialog_opener/el.dialog_closer/el.stylesheet) andel.to_string(for tests) are public; the rest ofelis@internaland a ★ calling it stops the generator (article 3).htmlhas 53 tags a business CMS uses, the 8 a document needs (0.13.1:caption,del,em,h5,h6,i,kbd,sup) plussvg/path, each astag(class, attributes, children)andtag_(attributes, children), with sketch_lustre's names and argument order. There is nostyle,scriptorlink.attrhas typed attributes with lustre's names,data(name, value),aria(name, value)androle(attr.Status | ..). There is no free-name attribute, noclass(a class is the tag's first argument,css.class(styles)), nostyleand no event.- Rendering never fails a page: a
data/arianame that is not[a-z][a-z0-9-]*drops that attribute (a literal one stops the generator, article 7);href/src/actionare dropped unless the scheme ishttp,https,mailto,telor none (a relative URL); the same attribute written twice keeps the last one (written twice literally in one list stops the generator, article 8);</and<!--inside the generated<style>become<\/and<\!--. Fragments leave no comment markers, and atextarea/prewhose text starts with a newline keeps it. el.img(class, src, alt, attributes)(0.12).srcis anel.Src, made only by the generatedmedia.src(blob, media.W800)(src/gen/media.gleam, from the app's media table) orel.static_src("logo.png")(a file underpriv/static/: the path must be a string literal, exit 4, and the file must exist, exit 3; article 43). Anattr.srcinattributesdoes not override it.attr.data("yumemi-…", ..)renders nothing and a literal one stops the generator (article 7):data-yumemi-*attributes are the framework's marks (where a button sends, a Component's state, an escape).el.dialog(key, class, attributes, children)renders<dialog id="yumemi-dialog-<key>">;el.dialog_opener(key, class, children)/el.dialog_closer(..)render buttons withcommand="show-modal"/command="close"andcommandfor. Where the browser has no invoker commands (HTMLButtonElement.prototype.commandForElementmissing), the client callsshowModal()/close()on their click. A dialog may sit inside an interactive Component's form and hold a send button (a confirmation step). The generated CSS keeps a closed dialog hidden (dialog:not([open]) { display: none !important }, also inside an@layer), so a Style'sdisplayon the dialog does not show it closed. Likewise an element with thehiddenattribute stays hidden whateverdisplayits Style gives it (0.14.2:[hidden]:not([hidden=until-found i]) { display: none !important }, also inside an@layer);hidden="until-found"is left to the browser, which hides it withcontent-visibilityso find-in-page can open it.el.notice(class)is the place a Component's After message shows after a reload or aGoTo(put it in a Layout Block; article 16 stops when a Component declares a message and the Layout has none).attr.sandbox([attr.AllowScripts, attr.AllowPopups, ..])(0.16.0) writes an iframe'ssandboxfrom typed allow tokens (the 12 that Chromium supports);attr.sandbox([])forbids everything. There is no way to pass a raw string. Do not combineAllowScriptsandAllowSameOriginfor a same-origin frame.
The raw-CSS escape (0.12)
shell.stylesheets (below) and el.stylesheet(el.static_sheet("fonts/mincho.css")) in a Block load a .css file from the face's priv/static/. Both are an escape hatch that the generator checks and counts:
- the file must exist under
priv/static/(exit 3, article 28) and thestatic_sheetpath must be a string literal (exit 4, article 31) — a variable piped in orstatic_sheetpassed as a function value is not one;"a.css" |> el.static_sheetis. At run time a path holding//,\,:or a..segment points nowhere (/); - no selector may name generated output —
[data-yumemi-…], a generated class.css-<8 hex>, a[class…]selector whose value holdscss, or an element whose name starts withyumemi-(exit 4, article 29). CSS escapes and spaces inside brackets are undone before the check, and at-rule preludes (@scope (..)) are checked too. An interactive Component's own tag (like-button) and its:state()are fine, and so is readingvar(--yumemi-theme-*)in a declaration; - no
@import(exit 4, article 30); - the rules are counted per face — each top-level block is one rule, an
@mediablock is one, and a file read from two places counts once — in the face's escape line (below).
yumemi/front ── Markdown (0.13.1)
yumemi/front/markdown reads Markdown held in the database at run time and draws it with yumemi's elements: a plain view-function Component a Block calls. A face can depend on nothing but yumemi and el takes no raw HTML, so the Markdown is read into a tree (Block / Inline) and built from html tags. HTML written in the Markdown stays text and is escaped; there is no raw-HTML path.
import yumemi/front/css
import yumemi/front/el.{type Element}
import yumemi/front/html
import yumemi/front/markdown
fn look() -> markdown.Look {
markdown.Look(
..markdown.bare(),
paragraph: markdown.Part(css.class(style.para), []),
code: markdown.Part(css.class([css.OverflowX(css.OverflowAuto), css.Spaces(css.Pre)]), []),
link: markdown.Part(css.class(style.link), []),
)
}
pub fn view(it: In) -> Element {
html.article(css.class(style.page), [], [
markdown.view(it.article.body, markdown.document(), look()),
])
}
- What is read is chosen by
Options. Three are provided, and any field can be changed (markdown.Options(..markdown.document(), tables: False)):document()— headings#–######(h1–h6), paragraphs (lines joined), fenced code with the language name, tables (|rows with a|---|separator line;|inside code and\|do not split), quotes (>, read as blocks), nested bullet (-*+) and numbered (1.1)) lists, rules (---***___); inside a line code (`x`,<code>x</code>),**strong**,*emphasis*,[links](/relative/too),<https://autolinks>,\escapes and<>&"&#n;.post()— what a user writes in a post:#and##are level 2,###is level 3, paragraphs keep their line breaks (br), blank lines are kept and counted (Blanks(count), drawn as that many empty lines),-/*bullets and1.numbers one line each (written at the start of the line), a line of exactly---(spaces around allowed) is a rule, and inside a line only**strong**andhttp(s)links. Anything else (tables, quotes, code, emphasis, nesting) stays text.outline()— a terms-like document: front matter (---…---, read withmarkdown.field(doc, "status")), lines trimmed,#–###are levels 1–3,-bullets and1.numbers (the start is not kept), paragraph lines joined with nothing between them, no marks inside a line.
- Links pass a fence or stay text.
Links:WebLinkstakes onlyhttp:///https://URLs without spaces,",<or>;SafeLinkstakes whatattr.safe_urltakes (http, https, mailto, tel and relative URLs);NoLinksreads none. A[text](url)whose URL does not pass is left as text, so ajavascript:link never becomes an<a>. A link's text may not hold[or].is not read (no images). - The tree is public.
markdown.parse(text, options)gives aDocument(meta, blocks),markdown.blocksthe blocks; an app that draws with its own Blocks walksHeading/Paragraph(lines)/Code(lang, text)/Quote/Bullets(items)/Numbered(start, items)/Table(header, rows)/Rule/Blanks(count)andPlain/Strong/Emphasis/CodeSpan/Link(href, label). A list item is a list of blocks; a one-line item is oneParagraph.markdown.render(blocks, look)andmarkdown.render_inlines(items, look)draw a tree,markdown.inline_textandmarkdown.plain(text, options)give the text without marks (plainkeeps the line count and order, drops rule lines and keeps a number's1.; for excerpts),markdown.rule(line, options)tells a rule line. - How it is drawn is chosen by
Look. Each kind of element takes aPart(class, attributes);bare()gives none.headingis a function of the level,code_frame/table_framewrap thepre/tablein adivwhenSome,linkcarries e.g.attr.rel("nofollow ugc noopener"), andspaces: KeepSpaceskeeps leading spaces and runs of two or more as U+00A0 (CollapseSpacesleaves the text as is). The heading tag follows the level (h1–h6); a numbered list that does not start at 1 puts the start on its firstliasvalue; a code block's language goes todata-langon thepre; header cells getscope="col"; emphasis isem; a list item whose first block is a paragraph has the paragraph's text directly in theli. There is no syntax highlighting. - The code that reads and draws is the same in the Worker and in an interactive Component's client bundle. In node, a 29,000-character document (
gleam-for-php-users) is read and drawn in about 48 ms. - Text from writers who are not trusted can be drawn on every request. Reading takes time linear in the text: an opening mark that never closes (
[,`,**,<code>,<http) or a link whose URL fails the fence is not re-read up to the end of the line for every mark, and long runs of spaces inside a line do not slow it down. Quotes and list items nest at most 16 deep (document();post()andoutline()do not nest); a deeper>or list marker stays text. In node, 30,000 characters of such text (a line of 30,000[, 7,500 code spans, 30,000 nested>, unclosed<code>/<http, a list nested 170 deep) are read and drawn with each of the three readings in at most 40 ms on the first call of a fresh process (2–15 ms once warm), with no stack overflow. A table whose output is ten times the text (one row of 15,000 cells) takes about 100 ms on a first call.
yumemi/front ── Interactive Components (0.12)
An interactive Component is a src/components/<name>.gleam module with a few constants and a view that takes Args and returns elements. There is no update, no State, no Event and no lustre: the state lives in the form's controls and in the element's custom state (:state()), and the generated client runtime (yumemi/front/interactive.mjs) moves it.
import gen/live/article_publish as publish
import gen/live/article_create as create
import gen/route
import gen/service
import gleam/option.{None, Some}
import yumemi/front/css
import yumemi/front/el.{type Element}
import yumemi/front/html
import yumemi/front/live
pub const calls: List(service.Service) = [service.ArticlePublish, service.ArticleCreate]
pub const after_send: List(#(service.Service, live.After(route.Route))) = [
#(service.ArticlePublish,
live.After(ok: live.GoTo(route.ArticleArgSlug, notice: Some("Published")), error: live.Stay)),
#(service.ArticleCreate, live.After(ok: live.ReloadPage(notice: None), error: live.Stay)),
]
pub fn view(p: publish.Args, c: create.Args) -> Element {
html.div_([], [
html.input_([publish.bind(publish.Slug, p.slug)]),
publish.send(css.class([]), [el.text("Publish")]),
el.dialog_opener("copy", css.class([]), [el.text("Copy")]),
el.dialog("copy", css.class([]), [], [
html.input_([create.bind(create.Slug, c.slug)]),
create.send(css.class([]), [el.text("Create")]),
]),
publish.when(publish.Refused(publish.AlreadyPublished), [el.text("Already published")]),
publish.when(publish.Succeeded, [el.text("Version "), publish.out(publish.OutVersion)]),
])
}
callslists one or more Services (constructor literals, no repeats; article 10). An attached upload route goes in the same list asfront.Entry(api.BlobCopy)(the list's type is thenList(front.Target(service.Service, api.Attached)));pub const targetis gone.viewtakes each Service'sArgsincallsorder, plus an optional lastwith: With(article 11).Withis a record in the same module: display values the placing Block passes once at render time (labels, choices). It is not state, never reaches the browser as data, and may not hold a live type, anel.Element, anel.Attributeor a function (article 22) — nor through an unqualified import (el.{type Element}), a record of the same module held in a field (List(Item)withItem(icon: el.Element)) or a type alias (pub type Icon = el.Element).after_sendhas one#(Service, live.After(ok:, error:))per write Service incalls(missing: exit 3; for a read Service or twice: exit 4; article 12).live.ThenisStay,ReloadPage(notice)orGoTo(route.<Page>, notice).routeis the face's closed enum of Pages (src/gen/route.gleam). AGoTopath's holes are filled from the Service's Out fields of the same name (article 15); anerror:GoTomust name a Page without holes, since a failure body is not an Out (exit 4, article 15). Anoticeshows once in the Layout'sel.notice.reloads(optional):live.Reloads(read: service.<Read>, on: [<read>.<Field>, ..])calls the read Service again when one of those controls changes (article 17). If the read's Out has noList, the runtime calls it and fills itsoutspans (an earlier call is aborted). If it has one, the runtime moves to the same Page with the field in the query (?<field>=…), replacing the history entry, keeping the scroll and the focus; the placing Block renders the rows.- The generated live module (
src/gen/live/<service>.gleam) givesArgs,Field,Error,When(Idle,Waiting,Succeeded,Failed,Refused(Error);Failedshows for a failure the Component has noRefusedbranch for, so a refusal it branches on beside itswhen(Failed, ..)never also shows the generic failure branch, and one it does not branch on still showsFailed; aRefusedbranch nested inside the same Service'swhen(Failed, ..)is hidden with it, so it does not count — that refusal shows both texts, the generic one around the specific one;Errorhas the Service'sErrorconstructors plusDeclarationMissing/ConsentMissingwhen itsrequireshasDeclared/ConsentedorConsentedFor— the 403declaration_missing/consent_missing— andDeclarationMissingfor an attached route withNeedsDeclared),Slot(Out<Field>for each non-list Out field) andbind(field, value)(name<service>.<field>, plusminlength/maxlength/required/patternfrom the value type's Spec; on atextareawith no children the value is rendered as its content, since a browser ignores a textarea'svalueattribute),bind_check,bind_choice,bind_file(a Blob field: the runtime uploads the chosen file to/api/blobsand puts its key in the Args),when(state, children)(a<span>withdisplay: contents, so it may sit inside a<p>),out(slot)andsend(class, children). - Args are typed. Each
Argsfield has the Gleam type the Service's Args field has on the wire:Bool,Int,Float,Option(..)andList(..)as they are, andStringfor every other scalar (value types, ids, enums, dates — the back reads them as text). A Block writes initial values in that type —create.Args(slug: it.slug, tags: ["news"], note: None), nevertags: "[\"news\"]"or"true"— and the generatedargs_jsonwrites the JSON. A Service whose Args field is a record, a tuple, aDictor aListof non-scalars cannot be incalls(exit 4, article 11). - No chaining on the client. One send button calls one Service; the runtime drops a submit without a send button and ignores Enter in a control of another Service. A Component may not import the live module of a Service outside
calls(article 19), every Service incallsmust be sendable (a write needs asend, a read asendorreloads; a list read may not have asend; article 20), and anoutmay not sit insidetextarea/select/option(article 21; the generator follows pipes,letvariables and functions of the same module, and the runtime never writes a read's result into anoutinside those controls). Combine Services on the server, in one Service. - Placing it. A Block calls the generated
src/gen/interactive.gleam:interactive.article_manage(publish.Args(slug: it.slug), create.Args(..)). The Component renders on the server inside its tag (<article-manage data-yumemi-island data-yumemi-args="…"><form method="dialog"><fieldset>…), in light DOM, with the same generated class names and page<style>as a Block; JavaScript adds no style. There is no send without JavaScript: the form'smethod="dialog"makes a submit the runtime does not take (no JavaScript, still loading, or a script error) send nothing — a form without a method would put the body in the URL — and inside a dialog it only closes the dialog. A ★ form (html.form, e.g. aGETpager) keeps the method it is written with. A Component may not sit inside a ★ form (exit 4, article 44): HTML drops a form inside a form, so the Component's controls would belong to the ★ form and be sent with its method — through aGETform, in the URL. The generator follows pipes,letvariables and functions, also those of other modules that place a Component; put the Component beside the form. The tag is the module name with_→-and must be a custom-element name not starting withyumemi-(that prefix belongs to the runtime's elements such asyumemi-escape; article 18); a Component may not place another one. - State. The runtime sets
waitingandsent-<service>while a call runs (the fieldset is disabled andaria-busy="true"for a send, not for a single-value reload), thenokorerror(+refused-<code>for a code the live module'sErrornames, andfailedunless the Component holds awhenbranch for that refusal outside the Service'sfailedbranch). WhereElementInternals.statesis missing it writes the same names todata-yumemi-state; the generated CSS hideswhenbranches both ways (@supports selector(:state(x))and its negation). A Block's or Component's Style can react withcss.State(css.Waiting | css.Succeeded | css.Failed, ..);css.Failedfollowserror, so unlike the live module'sFailedit also matches a refusal the Component branches on. pub fn appin a Component stops the generator (exit 4, article 9). The 0.11 shape (app(),view(it: State),after_send: live.Afterwith two values,reloads: List(#(Field, Service))) no longer compiles.
yumemi/front ── Named escapes (0.12)
JavaScript a page needs and yumemi has no word for goes in src/escapes/<name>.mjs ([a-z][a-z0-9_]*, article 6) and nowhere else under src/ (exit 4, article 5). The file exports mount(element) (exit 3 when it does not), which may return a function to call when the element leaves.
// src/escapes/chat_socket.mjs
export function mount(element) {
const socket = new WebSocket(element.dataset.url);
return () => socket.close();
}
The generator writes src/gen/escapes.gleam with one function per file, escapes.chat_socket(attributes, fallback), which renders <yumemi-escape name="chat_socket" …>fallback</yumemi-escape>; the fallback shows without JavaScript. The client bundles the files and mounts each element when it connects (also after client navigation) and unmounts it when it leaves. An escape may sit inside an interactive Component and write its controls.
The escape line. Per face the generator prints one warning (exit 0, also in _diagnostics.txt) counting every escape hatch: [exit 0 警告] <face>: 逃げ道 ── escape <kinds> 種 <calls> か所(うち interactive Component の中 <n>)、生の CSS <files> file <rules> 規則、数える口の送り先 ToService <n>.
Uploading from an escape (0.16.0). The second argument of mount(element, yumemi) also carries yumemi.upload(file), which uploads a File or Blob to the runtime's blob route and resolves to its key. When the upload fails it rejects with an Error that carries the response status (for example 415 when the blob route refuses the content type). Escapes and kit escapes (<kit>.<name>) use it instead of writing the upload route themselves. Faces without escapes are generated as before.
yumemi/front ── Shell: the home screen, the service worker and the stylesheets (0.11.12, 0.11.15)
A face's src/shell.gleam holds the constants the generator puts in every page's <head>. lang, title and theme are required (as before; from 0.12 theme is pub const theme: theme.Defaults = theme.Defaults(background: "#FAF7F0", text: "#3D2419", accent: "#A93632", background_image: None) — the three colours are #rrggbb literals, exit 4 otherwise, and background_image is None or Some("<path under priv/static>"), exit 3 when the file is missing; article 26). Five more are optional String constants; each one that is present adds one element after the <title>, in this order, and a shell without them generates exactly what 0.11.11 did:
| Constant | Goes out as |
|---|---|
manifest |
<link rel="manifest" href=".."> |
theme_color |
<meta name="theme-color" content=".."> |
icon |
<link rel="icon" href=".."> (the favicon) |
apple_touch_icon |
<link rel="apple-touch-icon" href=".."> |
service_worker |
the generated priv/static/_yumemi/client.mjs calls navigator.serviceWorker.register("..") once when it loads |
stylesheets (0.11.15) is an optional List(String) constant: one <link rel="stylesheet" href=".."> per item, in list order, after the elements above. From 0.12 each file is checked and counted as the raw-CSS escape (above). Put the face's site-wide stylesheets here rather than in a Block: a <link> in <head> holds the first paint until it has loaded, and client navigation keeps it (see Client navigation below), where a <link> in <body> is rebuilt — and revalidated — on every navigation. An empty list adds nothing.
pub const manifest: String = "/manifest.webmanifest"
pub const theme_color: String = "#A93632"
pub const icon: String = "/favicon.svg"
pub const apple_touch_icon: String = "/apple-touch-icon.png"
pub const service_worker: String = "/sw.js"
pub const stylesheets: List(String) = ["/brand/tokens.css", "/brand/site.css"]
- The files themselves (the manifest, the icons,
sw.js) are the face's static assets underpriv/static/; the generator only links them. - The registration does nothing where
navigator.serviceWorkeris missing, and a failed registration is swallowed (the page keeps working). Client navigation does not reloadclient.mjs, so it registers once per page load. A face without interactive Components or escapes gets aclient.mjsthat only registers the worker (and the page loads it); a face with none of them gets noclient.mjs, as before. - Client navigation keeps the
<head>elements the next page also has and swaps the rest, so each element stays exactly once after a navigation. - A constant that is present but is not a non-empty
Stringconstant (another type, or"") stops the generator like a missingtitle: exit 3,<face>/src/shell.gleam: <name> は空でない String の定数で書く. Forstylesheetsthe same holds when it is not a list literal of non-empty strings:<face>/src/shell.gleam: stylesheets は空でない String の List の定数で書く.
yumemi/front ── Client navigation (0.11.4, 0.11.15, 0.12)
The generated client calls yumemi/front/navigate.mjs's start({routes, csp}). routes lists every Page route of the face; csp maps each route of a gate frame_src Page to the content-security-policy value the gate sends with it (frame-src https://<host> .. from the entry's frame_src hosts). A face without such Pages gets no csp key, exactly as in 0.11.14.
Since 0.12 the browser's Navigation API does the browser's part: it reports the navigation (navigation's navigate event), keeps history, restores scroll, resets focus, aborts a superseded navigation and handles fragments. navigate.mjs takes a navigation with event.intercept() and does the rest: the fetch, the swap check, the head diff, the stylesheet wait, the body swap, and the pageview mark. Interactive Components and escapes in the new body start by themselves: their custom elements are defined once, and each connects when the body is inserted (0.12 has no boot).
- Which navigations. A push or replace the user started (a link, a GET form) and a back / forward within the document, from a routed Page to a routed Page, whose destination has the same CSP as the Page that loaded the current document (both none, or the same value). A CSP header only takes effect on a page load, so a link to a Page with another CSP — or from a Page without one to a Page with one — is a page load, and the destination's policy holds. The browser handles everything else as it would without
navigate.mjs: modified clicks andtarget(another tab),download, POST forms, other origins, a fragment within the page, navigations a script starts (location.assign), a plainlocation.reload(), and links to unrouted paths. A back / forward within the document to an unrouted entry is taken and reloaded as a page load, so the URL and the page never disagree. - Without the Navigation API (Baseline 2026: Chrome 102, Firefox 147, Safari 26.2)
startdoes nothing: every link is a page load, and so is reload after a write. - Which responses. One fetch with
x-yumemi-navigate: 1(the gate, the adult declaration and the session go through the server as before), aborted with the navigation'ssignal. A same-origin redirect (a gate's 302, e.g. to/enter) is followed (redirect: "follow",mode: "same-origin", 0.14.7) and its final URL is opened as a page load instead of being swapped in, keeping the original#(a#inLocationis not visible tofetch): the server sees the original URL once and the final URL twice. A redirect to another origin fails the fetch before the request leaves, and falls back like the cases below. It falls back to a page load of the destination on a non-200 (except a face's failure page, below), a non-HTML body, acontent-security-policyheader that differs from the route table's value for that Page (or is present where the table has none, or missing where it has one), or a page with scripts other than the client. The URL has already changed by then, so the fallback islocation.replace(no extra history entry); the server sees the same GET twice. - The head. Elements whose
outerHTMLis the same in the current and the next<head>stay where they are (a stylesheet is not re-requested); the others are removed or inserted at the next page's positions, so the order follows the next page. The client script stays. - Stylesheets load before the body changes. A stylesheet new to
<head>, and a copy (in<head>, markeddata-yumemi-hold) of each stylesheet that only the next page's<body>links (an article's font CSS, say), is inserted withmedia="not all"and awaited (load or error, at most 3 seconds); then itsmediais restored, the old head elements leave and the body is swapped. A copy is removed once the body's own<link>has loaded. The old page stays on screen meanwhile, so no unstyled page shows; the swap waits for those downloads. - Scroll and focus follow
intercept()'s defaults once the new body is in: a push goes to the fragment or the top, back / forward return to the position the entry was left at; focus moves to theautofocuselement or<body>. Reload after a write is taken withscroll: "manual"and keeps the current position (the reload default would go back to the top, since the entry's position is only saved when leaving it). - A same-document change during a fetch. If a fragment link or
history.pushState/replaceStateaborts the fetch of the next page, and no newer navigation was taken, the current URL is reloaded (location.reload()), so the URL and the page never disagree. - History a script pushed. Back / forward to an entry a script pushed on the current page (an escape's
history.pushState) is left to the browser: the page is not refetched, a Component keeps its state, and no pageview is counted. 0.12's interactive Component runtime itself never pushes history (a listreloadsreplaces the entry). - Runtime navigations. A Component's
GoToand a listreloadscallnavigate.go(href, {replace, keep, count}), whichnavigate.mjstakes like a user's push (a listreloadsreplaces the entry, keeps the scroll and puts focus back on the same control). - A list
reloadsis not a pageview. It refetches the page because a field changed, not because the user navigated, so it passescount: false: the navigation'sinfocarriescount: falseand the pageview sender skips it (and, if it falls back to a page load, skips that load once, by a mark kept for 10 seconds under the session keyyumemi:uncounted). AGoTois counted asspa. - Reload after a write. A Component's After
ReloadPagecallsnavigate.reload(): on a routed Page it callsnavigation.reload()with a mark and takes that reload, refetching the current URL the same way (no history entry, scroll kept); otherwise, or without the Navigation API, it reloads the page. - Pageviews: the mark only. For the navigation fetch the gate puts
<meta name="yumemi-pageview">in<head>.navigate.mjsdoes not post pageviews (0.11.4 to 0.11.15 did); it replaces the mark on every swap, so whennavigationfiresnavigatesuccessthe document holds the next page's mark and never the previous page's. A pageview sender reads the mark there and the kind fromnavigation.transition.navigationType(push,traverse,reload).navigatesuccessalso fires for a same-document navigationnavigate.mjsdoes not take (a fragment within the page,history.pushState/replaceState);navigation.transitionis thennulland the current page's mark is still in the document, so a sender counts only whennavigation.transitionis notnull.startno longer takespageview. - No
yumemi-navigatedevent. Listen tonavigation'snavigatesuccessinstead (0.11.4 to 0.11.15 dispatchedyumemi-navigatedondocument).
yumemi/front ── The failure page (0.14.3)
A face may declare one failure page: a plain Page in <face>/src/failure.gleam.
pub const page: Page(service.Service, blocks.Block) = Page(
of: None,
layout: layout.main, // the face's Layout: frames the failures after the gate (not the gate's own)
theme: None,
vars: [Var("failure", Failure)],
sp: Frame(areas: [..], placements: [Fixed(area: "page", block: blocks.FailureNote, cell: Flow)], ..),
pc: None,
tablet: None,
)
Then the generated shell and gate answer a request that wants a page, and fails, with that page, keeping the original status code. A face without src/failure.gleam generates exactly what 0.14.2 generated.
Failureis a new variable source, allowed only on the failure page. Its value is a String:"forbidden"(401, 403),"not_found"(404, 405, 410 and any other 4xx) or"unavailable"(5xx and exceptions). One Block reads it and words the page; the status stays on the response.- What the failure page may hold (article 45; the generator stops with exit 4, or exit 3 when
src/failure.gleamhas nopub const page: Page(..)):of: None;Fixedplacements only (noWidget, noLive), whose Blocks read no Service (In = Nil); Page varsFailureandCurrentRouteonly (CurrentRouteis""there).OriginandAuthOrigincome from the Layout, as on any Page.Failureanywhere else (a Page, the Layout) stops the generator. On a face with a failure page the Layout'sFixedBlocks may not read a Service either (put a read in aWidget). So the page can be drawn from any URL's failure without the API. - The gate's failures have no frame. A failure the gate returns (the session read's 503 / 404 / 403,
Admitted,Deny, and an unmatched path stopped by anEveryrule) is drawn without the Layout: only the failure page's ownFixedBlocks (wrapped in<div data-yumemi-failure="bare">), and the Layout's Widgets are not read. The gate has not yet let the requester in, so they do not see the face's bars and navigation. Failures after the gate (the shell's reads, exceptions, an unmatched path for someone the gate let through) keep the Layout. - The Layout's Widgets are read (failures after the gate), and a Widget whose read fails (any non-2xx, an exception, a body the decoder refuses) is simply not drawn: when the API is down the page still shows, with the Layout's static parts and the page's own content.
- Which requests get the page.
GETorHEAD, withoutx-yumemi-block, withsec-fetch-dest: document, ortext/htmlinaccept, orx-yumemi-navigate(the client navigation's fetch). Every other request (the fragment answer, assets, an island's or a test'sfetch, aPOST) gets the plain text as before (forbidden,not found,unavailable, a gateDeny's body). - Which failures. The shell's: the root read's 403 / 404 / other 4xx / 5xx, a session read's 5xx, a
Sessionvariable without a subject (401), a path no Page matches (404). The gate's:Admittedand unknown checks (403), the session read's 404 / 5xx / other, andDeny(status, body)(the page withDeny's status; the body stays for requests that do not want a page). Redirects stay redirects. - Exceptions. On a face with a failure page,
renderPage,renderBlockand the reads' decoders run inside atry: an exception is logged (yumemi shell: render error) and becomes a 500unavailable(the failure page for a page request, the plain text for the fragment answer) instead of the Worker's exception page. - No loops. If the failure page itself cannot be drawn (an
Originenv var is missing, the render throws), the plain text goes out. The failure page is never wrapped in another failure page, and a missing env var's name never reaches HTML. - Paths no Page matches meet the gate. On a face with a failure page, a page request for an unmatched path goes through the checks of every gate
RulewhosepagesincludeEvery(theirexcept,ExactandPrefixare about routes and are not looked at). So a face that admits only its own users sends everyone else to sign-in (or its own refusal) rather than showing them its Layout around a 404. Faces without a failure page are not changed: an unmatched path still skips the gate. - The response.
content-type: text/html,cache-control: no-store,x-yumemi-failure: <status>, and the route'scontent-security-policywhen the URL matches a Page with one (also when the gate refused). For a path no Page matches, thecontent-security-policyof theCspdeclarations whosepagesincludeEvery. The pageview mark is not added (only 200s carry it). - Client navigation.
navigate.mjsswaps in an HTML response that carriesx-yumemi-failureas it would a 200 (same CSP check, sameswappablecheck), so a link to a missing page shows the failure page in place (with the Layout's bars and navigation after the gate, without them for the gate's refusal) with one request, and back / forward work as for any page. Faces without a failure page never send the header. - For the face's own entry. The generated
src/gen/shell.mjsexportsfailure(request, env, status), which returns the failure page for a page request and the plain text otherwise; an entry that answers some paths itself can use it instead of its own plain text. - Generated output. A face with a failure page gets
src/gen/load/failure.gleam(no fragment functions), afailureSpecand the failure runtime insrc/gen/shell.mjs, the gate's failure path insrc/gen/gate.mjs(serve(dispatch, failure),plain,isPlain,wantsPage,cspUnmatched),render_barein the failure loader, and the page's grid instyle.css. The route table, the gate's tables and the fragment answer are unchanged.
yumemi/front ── Page theme: where the colours come from (0.11.13, 0.12)
Page(.., theme: Some(name), ..) paints the page with a yumemi/front/theme.PageTheme read on the server; theme: None paints the shell's theme defaults only.
// yumemi/front/theme
pub type PageTheme {
PageTheme(background: Option(color.Color), background_image: Option(blob.Blob),
text: Option(color.Color), accent: Option(color.Color))
}
- Colours are a type.
yumemi/front/color.Coloris opaque:color.parseaccepts#and six hex digits only ("#fff;}</style>"is anError), and the output is rebuilt from the parsed digits (lower case). An Entity or a ServiceOutholdstheme.PageTheme(orcolor.Color) directly; the face copies (src/gen/out/*) keep yumemi's types instead ofString, and the back's codec reads a stored colour withcolor.parse. - Output: four custom properties on
body—--yumemi-theme-bg,--yumemi-theme-bg-image(url(".."), the URL built by the app'smedia.url(blob, media.W1600)as before),--yumemi-theme-text,--yumemi-theme-accent— and, on a page with a background image,data-yumemi-theme-imageonbody. A ★ reads them withcss.Theme(css.ThemeBackground | ThemeText | ThemeAccent)andcss.State(css.ThemeImage, ..), never by name. - Which Service and where in its
Out: unchanged from 0.11.13 — the first source whoseOutreaches aPageThemethrough labelled record fields (throughOption, records and aliases),namechoosing the last field's label — except that the field must be yumemi'stheme.PageTheme(an app type that is merely calledPageThemeis not taken). When no source of atheme: Some(name)Page reaches one, the generator stops (exit 4, article 27).
yumemi/front ── Style (0.11.10)
yumemi/front/css's Style is the typed vocabulary a Page / Area / component carries; yumemi/front/sketch_css maps it to CSS (sketch classes; from 0.12 a class name is a hash of the rendered CSS, so the same Style gets the same name in node, the Worker and a minified bundle, and an interactive Component's Style lands in the page's <style> like a Block's). css.class(styles) makes the Class a tag takes. Every word also works inside State(Hover / Focus / FocusVisible / HoverCapable / Disabled / Current / Waiting / Succeeded / Failed / ThemeImage, ..) and Responsive(SP / PC / Tablet, ..).
Colours are a closed type, css.Paint (0.12; before, a string passed straight through):
| Paint | CSS |
|---|---|
Hex("#a1b2c3") |
the hex, lower case — a string literal of # and six hex digits (exit 4 otherwise, article 23) |
Token("ma-color-ink") |
var(--ma-color-ink) — the name is [a-z0-9-]+ (exit 4 otherwise, article 24) |
Theme(ThemeBackground / ThemeText / ThemeAccent) |
var(--yumemi-theme-bg) / -text / -accent (Page theme, above) |
Mix(a, b, percent) |
color-mix(in oklab, a percent%, b) — percent 0–100 (exit 4 otherwise, article 25) |
Transparent / CurrentColor |
transparent / currentcolor |
| Style | CSS |
|---|---|
Color(value) |
color |
Background(value) |
background-color |
Border(edge: AllEdges / TopEdge / BottomEdge / LeftEdge / RightEdge, width, style: Solid / Dashed / Dotted, color) |
border / border-top (0.12) / border-bottom (e.g. the 2px tab underline), and (0.13.1) LeftEdge / RightEdge — border-left / border-right (a heading's side band, a quote's rule) |
TextAlign(align: TextStart / TextCenter / TextEnd) |
(0.12) text-align: start / center / end |
Center |
(0.13.1) margin-left: auto; margin-right: auto — centres a box in its parent; pair it with Space(MaxWidth, ..) for a reading column. The vertical margins are left alone |
OverflowX(overflow: OverflowAuto / OverflowHidden / OverflowVisible / OverflowScroll) |
(0.13.1) overflow-x — OverflowAuto lets a wide table or code block scroll sideways inside the text column |
Spaces(white_space: SpaceNormal / Pre / PreWrap / PreLine / NoWrap) |
(0.13.1) white-space |
Slant(slant: Upright / Italic) |
(0.13.1) font-style: normal / italic |
Outline(width, offset, color) |
outline-style: solid / outline-width / outline-offset / outline-color — the focus ring, inside State(FocusVisible, ..) (0.11.14; State(Focus, ..) also keeps it after a tap) |
Space(property:, value:) |
margin / padding / gap / width / height / border-radius, and (0.11.7) min-width / min-height / max-width |
Text(family:, size:, weight:, line_height:) |
font-family (System / SansSerif / Serif / Monospace, or Named("var(--ma-font-ui)") / Named("\"Noto Sans JP\", sans-serif"); each comma-separated Named item must be var(--<name>), a quoted family name or bare words of [A-Za-z0-9_-], else the value is unset), font-size, font-weight (Normal 400 / Medium 500 / SemiBold 600 / Bold 700), line-height |
Crop(fit: Cover / Contain / Fill / ScaleDown / FitNone, ratio: Ratio(w, h)) |
object-fit and aspect-ratio |
Sizing(box: BorderBox / ContentBox) |
(0.11.8) box-sizing — BorderBox counts padding and border inside width / min-height, so an input or an <a> button with min-height: 48px and padding stays 48px |
Marker(marker: NoMarker) |
(0.11.8) list-style: none — drops the ul / li bullet (clear the indent with Space(Padding, Px(0.0))) |
Decoration(line: NoDecoration / Underline) |
(0.11.8) text-decoration: none / underline — e.g. a row link without the underline, underlined again inside State(Hover / Focus, ..) |
Wrap(wrap: Anywhere / BreakWord / WrapNormal) |
(0.11.10) overflow-wrap: anywhere / break-word / normal — Anywhere breaks a long URL or an unbroken word at the line's width, so the row's scrollWidth stays its clientWidth (it also lowers the min-content width, so the word does not widen a flex / grid item); BreakWord breaks it too but keeps the min-content width |
State(FocusVisible, styles) |
(0.11.14) :focus-visible — the focus ring for keyboard focus only. Focus (:focus) also matches after a tap or a click, so a ring put there stays on a tapped button; put the ring here instead |
State(HoverCapable, styles) |
(0.11.14) @media (hover: hover) { .class:hover { .. } } — hover on devices that can hover (a mouse). On a touch screen :hover stays true after a tap, so a Hover background stays on the tapped button; this one is not applied there. Same specificity as Hover (the class plus :hover), so it beats the class's own background. Inside Responsive(at, ..) it becomes one media, @media (<at>) and (hover: hover) |
State(Current, styles) |
(0.11.9) [aria-current]:not([aria-current="false"]) — the item that is where the user is (aria-current="page", also step / location / true). Mark the nav item with aria-current (a Layout block learns the page from CurrentRoute, below) and give it e.g. the 2px underline with Border(BottomEdge, ..) |
State(Waiting / Succeeded / Failed, styles) |
(0.12) inside an interactive Component whose custom state is waiting / ok / error. Written twice: @supports selector(:state(x)) { .class:is(:state(x) *) {..} } and @supports not selector(:state(x)) { .class:is([data-yumemi-state~="x"] *) {..} } for browsers without :state(). Inside Responsive(..) the two selectors are written without @supports (sketch drops an at-rule inside a media) |
State(ThemeImage, styles) |
(0.12) .class:is([data-yumemi-theme-image] *) — on a page with a background image |
Hide |
(0.16.0) display: none. Inside State(Succeeded, [Hide]) (or Failed) it hides the element while the enclosing interactive Component's last send succeeded (or failed), and it wins over the class's own display from Flow. To name one Service of a Component that sends more than one, use the generated live module's succeeded: css.State(publish.succeeded, [css.Hide]) hides while that Service's last send succeeded and comes back when another Service is sent. css.SentOk itself is internal (article 3); write it only through the live module |
Flow(..) State(..) Responsive(..) |
layout, interaction states, breakpoints (unchanged). Animation was removed in 0.12 (no @keyframes was ever emitted) |
Lengths (css.Length) are Px(n) / Rem(n) and, from 0.11.9:
| Length | CSS |
|---|---|
Var(name) |
var(--name) — e.g. Var("ma-space-2"). The name passes only [a-z0-9-]; any other name (;, }, ), a space, upper case, empty) is written as unset by sketch_css, and the generator stops on it in an Area's gap |
Env(SafeTop / SafeRight / SafeBottom / SafeLeft) |
env(safe-area-inset-top, 0px) … (0px where the device has no safe area) |
Dvh(n) |
n dvh — e.g. Space(MinHeight, Dvh(100.0)) for a short page that still fills the screen |
They work everywhere a Length does: Space, Text, Border, Outline, Flow gaps, and an Area's flow gap in the generated grid CSS (literal or a style constant).
yumemi/front ── Grid style and the bottom bar (0.11.10)
StyledFrame(areas:, placements:, cols:, rows:, template:, style:)— aFrame(sp, pc or tablet) whosestyle: List(css.Style)goes on the grid element itself (data-yumemi-grid, the Layout's or a Page's). The other fields are those ofFrame, and a plainFrame(orstyle: []) generates exactly what 0.11.9 did. It is a second constructor rather than a new field, so every existingFrame(..)keeps compiling. Write the style like an Area's: astyleconstant (style: style.shell) or a list of them (style: [style.shell]); the generator stops on anything else. The sp Frame's style holds at every width; a pc / tablet Frame's style is wrapped inResponsive(PC / Tablet, ..)(the same widths as the grid's media rules). The style becomes a sketch class on the grid element, and every Area keeps its own class, so the two never share a rule. Columns, rows andgapstay with the Frame's fields (the generated grid CSS writes them); use the style for the rest.front.frame_style(frame)reads it ([]forFrame).- The screen-tall shell:
style.shell = [css.Space(css.MinHeight, css.Dvh(100.0))]withrows: [track.Auto, track.Fr(1), track.Auto]— the grid is at least the screen tall and the body row takes what is left, so a short page still puts the last row at the bottom of the screen; a long page is laid out as before.
- The screen-tall shell:
pin: BottomFlush— a bar stuck to the very bottom of the screen:position: sticky; bottom: 0; padding-bottom: env(safe-area-inset-bottom, 0px); z-index: 3. Its background reaches the bottom edge, and its content sits above the iPhone home indicator. The bottom padding of the Area is the safe-area inset (it wins over an Area style'spadding), so put any further space inside the bar's block.Bottomis unchanged (bottom: env(safe-area-inset-bottom), floating above the inset).
yumemi/front ── Layout vars and Overlay (0.11.9)
Var(name, CurrentRoute)— the route spelling of the Page being drawn, as the generated route table writes it (/rosters/:id,/). It is a constant the generator knows per Page; the request's argument values and query never enter it. It can sit in a Layout (wherePath/Query/Sessioncannot) or in a Page, and arrives as aStringblock arg of the same name — a header block compares it with its links' routes to setaria-current="page".pin: AnchoredOverlay(side: Below / Above, align: AlignStart / AlignEnd)— an Overlay Area that opens next to theel.openerbutton that opened it, below or above it, lining up its start or end edge with the button's. It is an Overlay in every other respect (el.opener/el.closer, popover, not in the grid). The generated CSS uses CSS anchor positioning inside@supports (anchor-name: ..)(position-area,position-try-fallbacks: flip-block) and leaves the backdrop clear. A browser without anchor positioning opens it likeOverlay: centred by the UA, with the darkened backdrop. With several openers for the same Area the anchor is the last one in document order.Overlayand[popover]::backdropare unchanged.
yumemi/front ── Area flow (0.11.8)
An Area's flow in a Layout or a Page's Frame now reaches the generated grid CSS (the <style> that htmlWithGridCss puts in SSR pages and _yumemi/style.css, which carry the same text): the Area's rule gets the flow's declarations after grid-area, so the blocks placed in the Area are laid out by it. Before 0.11.8 the Area stayed display: block and the flow was ignored.
flow |
declarations in the Area's rule |
|---|---|
Stack(gap:) |
display: flex; flex-direction: column; align-items: stretch; gap — blocks keep the Area's full width |
Row(gap:, wrap:) |
display: flex; flex-direction: row; flex-wrap: wrap / nowrap; gap |
Grid(cols:, gap:) |
display: grid; grid-template-columns: repeat(cols, minmax(0, 1fr)); gap |
GridTracks(cols:, gap:) |
unchanged (already written since 0.11.x: display: grid, the tracks, gap) |
Scroller |
display: flex; flex-direction: row; overflow-x: auto |
gapis a literal (css.Px(..)/css.Rem(..)) or a constant of the app'sstylemodule (style.s2). A gap the generator cannot read leaves the Area's rule without flow lines (as before).- Every variant writes its direction, so a
pc/tabletFrame that gives the Area another flow overrides thespone inside its media rule. An Area shown only at a breakpoint (hidden elsewhere) keepsdisplay: noneoutside it; inside the media rule its flow'sdisplayshows it, and nodisplay: blockis added. - An Area pinned
Overlaygets no flow lines (its display stays with the overlay).pinandstyleoutput is unchanged. yumemi/front.area_flow_css(flow)returns the declarations for onecss.Flow.
yumemi/entry ── The MCP endpoint of an entry (0.15.0)
An entry whose credential is SessionMcp also answers MCP. Its HTTP side is exactly a Session entry (cookie, checks 1–10, the same routes), and the same host gets <prefix>/_yumemi/mcp. Every Service that entry can route becomes a tool, with no declaration on the Service and no list of tools. Only the entry that turns it on is rewritten; every other entry's declaration stays as it is:
HttpApi(
name: "admin",
hosts: [AdminHost],
prefix: "/api/admin",
admit: Authenticated,
subject: Subjects([Staff]),
services: All,
credential: SessionMcp,
pages: AllPages,
)
entry.mcp(Entry) -> Bool tells whether an entry has the endpoint. A face folder belongs to an HttpApi entry whose credential is Session or SessionMcp (not ApiKey), as it does to an Http entry.
-
Same checks, same answers. The tools are the HTTP route candidates of the entry (
routesFor(entry)inhttp.mjs: no System Service, the entry's medium,ReadOnlydrops writes), under the entry's prefix; a route the app'sroute_skiphook drops from HTTP is not a tool either. Atools/callis matched by name instead of method and path, then runs the same check 7 (subject), 8 (Args, fromarguments), 9 (allow, suspension, requirements) and 10 (execute) functions as HTTP. The result is the HTTP response turned into a tool result:isErrorfor a 4xx / 5xx,structuredContentthe same JSON object as the HTTP body (a body that is not an object is wrapped as{value}),contentthe same JSON as text,_meta["yumemi/status"]the HTTP status. A tool name that is not a candidate isisErrornot_found, as HTTP's 404. -
Who. The endpoint reads only
Authorization: Bearer(an access token of aframework.grantrow); it never reads the session or browser cookie, so it has no Origin check. No token on anAuthenticatedentry, a malformed token, and a token whose grant is revoked, expired, belowcredential_flooror made for another entry are all 401 withWWW-Authenticate: Bearer resource_metadata="https://<host><prefix>/_yumemi/mcp/metadata"(HTTP answers "nobody" 403; this is the one difference in the answers). Because the browser cookie is not read, a Service that requires a browser declaration (Declared,NeedsDeclared) is alwaysdeclaration_missingon the endpoint. The metadata (RFC 9728) namesMCP_AUTHORIZATION_SERVER. -
The grant. Check 6 is one statement, the app's
db/queries/framework/grant_resolve.sql(★, holes: the access token's HMAC digest, at). It returns the same projection as the session statement plus the grant's columns. Every one of these columns is required, and the runtime checks them again and fails closed — a row without one of them is refused (401), never read as a default:column what the runtime requires partytext subject_partytext, equal to party(the party of the grant's subject row; NULL — the subject row is gone — is refused)suspendeda boolean (NULL is refused); trueopens the endpoint and makes every write 403suspended, as on HTTPentrythe entry's name grant_id,clientthe grant and its client (audit, logs) credential_version,credential_floorintegers, version ≥ floor; a NULL credential_flooris "no floor row"access_expires_at,expires_atafter atrevoked_atNULL ("not revoked") subject_kind,subject_id,handle,phase,consents,subjectsand the subject's columnsas in the session statement (checks 7 and 9) A second statement,
db/queries/framework/grant_subjects.sql(★, hole: the party), lists the party's subjects as rows{party, kind, id, name?}, under the same conditions as the session statement'ssubjects(for example only onboarded or retiring muses). The generator stops with exit 4 when aSessionMcpentry lacks either file. Tokens are random, kept asSECRET_HMACdigests only; an access token lives 1 hour, a grant until theexpires_atits issuer passes (the IdP'spolicy.session_seconds), extended on refresh. A refresh token works once; a spent refresh token presented again revokes its grant (OAuth 2.1 reuse detection: the spent digests are kept inframework.grant_refresh_used, so two refreshes racing with the same token also end in a revoked grant).AppSystemgainsgrant_subjects(party, entry) -> [{kind, id, name?}](the subjects the consent screen offers: the party's, whose kind is in the entry's subject set; rows of another party are dropped even if the ★ statement returns them),grant_issue(party, entry, subject_kind, subject_id, client, credential_version, expires_at),grant_refresh(refresh_token, expires_at)andgrant_revoke(grant id or token).grant_subjectsandgrant_issuethrow for a name that is not an MCP entry;grant_issuethrows for a kind outside the entry's subject set and for a subject thatgrant_subjectsdoes not list for the party (the app checks it, not only the IdP). The OAuth authorization server itself (registration, consent, token) is not part of 0.15.0. -
Tools are derived.
src/gen/mcp-tools.json(per entry) andsrc/gen/mcp_tools.mjshold, per Service:name(the module name),inputSchema(theArgsfields with the HTTP decoder's vocabulary; writes also take an optional_idempotency_key, which the endpoint puts in the call'sIdempotency-Keyheader before checks 7–10 and the app's hooks run, so a hook that takes the header off (anearlythat keeps a one-time secret out of the idempotency records) takes the MCP key off too:nullis no key, a value that cannot be a header (not a string) is 400idempotency_key, and anIdempotency-Keyheader on the MCPPOSTitself is ignored),outputSchema(a localOutrecord),description(the module's first////paragraph, cut at 1,000 characters) andannotationsfrom the HTTP method:GETread-only;POSTofcreatenot destructive;PUT,DELETEand any otherPOSTdestructive;openWorldHintwhen the Logic calls a Connector.tools/listshows the Services with a clause the entry's subjects can pass (anyone,party, or one of its kinds); the others can still be called by name and are refused by check 9 as on HTTP.upload_file(base64, to aPOST <prefix>/blobsattached route read as a raw body) andcurrent_subject(theReadSessionroute) are added when those routes are under the entry. -
The wire. Streamable HTTP, stateless: one JSON-RPC message per
POST, a JSON answer, noMcp-Session-Id, no SSE (GETis 405).initialize,notifications/initialized(202),ping,tools/listandtools/call. The body is limited before it is parsed: acontent-lengthover theupload_filelimit (20 MiB in base64 plus 64 KiB) is 413 before the body is read, a body without one is cut at that limit while it is read (413), and a message that is not anupload_filecall is 413 above 20 MiB (the HTTP upload limit). -
Audit and logs. Each write's audit rows carry
entry,medium(session,api_key,mcp) andclient(framework/audit_entry, every app; applydb/framework/audit_entry.sqlbefore deploying 0.15.0). A read through MCP logs one line{"yumemi":"mcp.read","grant":..,"tool":..}.
Writing a Service for people and models (0.15.0). The first sentence of a Service module's //// is what the Service does, in the words of the person who uses it ("Publish a draft article."). Design notes, release names and file references go after the first paragraph. The MCP tool's description is that first paragraph, so it is what a model reads to choose the tool. This is a convention; the generator does not check it.
yumemi/server ── what the app must provide (0.11.1)
The back-end runtime (yumemi/server/*.mjs) is JavaScript that the generated src/gen/*.mjs imports. It knows no application names: route names, cookie names, key bindings, declaration and consent kinds and the party a queue consumer reads its borrowed root as come from the app's src/server.gleam (attached_roles, browser, consents, hooks, roots' QueueParty). The generated face gate (<face>/src/gen/gate.mjs, declared in <face>/src/gate.gleam with yumemi/gate) reads the session through the ReadSession attached route. Gleam packages cannot declare npm dependencies, so the app supplies the following itself.
Generated live modules (0.11.2) send Args by their declared type: Bool as a JSON boolean (the live field's "true" / "false"), Int / Float as numbers. On a GET route the Args that are not path holes go on the query string (an empty Option is left out), and the runtime reads bool (true / false) and float spellings from the query of GET / HEAD requests. POST / PUT / DELETE bodies are read as JSON as before.
A live field for a List(X) Arg (X a scalar, value type, id or enum) holds a JSON array of strings (["a","b"], an empty field is []); each item is sent by X's rule. A field for a record, tuple, Dict or a List of those holds the JSON body itself (for example {"background":"#112233"}), which is sent as is and read by the back-end decoder. A field that does not parse is sent as a string, and the back end answers invalid_argument. Sum types with several constructors are sent as strings.
A Service whose logic runs step.commit and continues after it (and is not a queue consumer that only uses the commit as a boundary) ends in Accepted over HTTP: the runtime answers 202 with a one-field body ({"<root>": id}, a respond hook may rename the field). The generated live for such a Service (0.11.3) holds Reply instead of the Service's Out: Accepted(id) for the 202 body and Replied(out) for a 200 that ends before the commit. Both arrive as Done(Ok(_)) and go on to after_send (for example ReloadPage). Lives of other Services are unchanged.
0.11.4 adds, without changing the existing public types:
- Reads time out and retry once.
driver.mjscuts a read-only statement (oneSELECT/WITH/VALUES/TABLEwith no write keyword —INTOand row locks count as writes — and no call to a function outside the built-in allow list, read after one pass that strips strings, quoted identifiers and comments; seeyumemi/server/read_retry.mjs) afterDATABASE_READ_TIMEOUT_MS(default 10000) and retries it once when the failure is outside the database (timeout, fetch failure, HTTP 5xx; not an SQLSTATE). Writes and transactions are never retried and get no timeout. Every failure outside the database, read or write, is logged as one JSON line ({"yumemi":"driver.failed",kind,key,attempt,ms,code,status,name,body},kindisread/write/transaction) with the response body. - Attached routes with a framework role that reads a body send it: the live for a
SwitchSubjectroute hasArgs(kind, id)and sends{kind, id}. Other attached lives are unchanged (no Args,nullbody). - The
BlobCopylive copies a URL. Besides the file upload (Send),copy_from(state, url)sends{from: url}to the same route and reads{key}intoDone(Ok(key)). (0.12:blob_copy.Args(file, from)— the runtime uploads the chosen file, or sends{from}when no file is chosen, and putskeyinOutKey.) - Split records decode. A record Property stored with
Splitis rebuilt from its columns insrc/gen/codec.mjs. - Islands render sketch classes. The generated client registers each island through
yumemi/front/island_style.mjs'sstyled(app): the island gets its own sketch stylesheet while its view runs, and the CSS goes into a<style>inside the island (only when the island uses classes and does not render its own stylesheet). (0.12 removes this: a Component renders in light DOM with the page's<style>, see "Interactive Components".) - Client navigation between Pages. The generated client calls
yumemi/front/navigate.mjs'sstart({routes, boot, pageview}). A plain left click on a same-origin link, from a Page to a Page that are both in the face's route table (minus the gate'sframe_srcPages), fetches the next page with one request (the gate, the browser's declarations and the session go through the server as before), swaps<head>and<body>, re-runs the island registrations and pushes history; back / forward do the same. A redirect, a non-200, acontent-security-policyheader, a page with scripts other than the client, an already-registered given island, a modified click,targetordownloadfall back to a page load. (0.12 replaces this with the Navigation API and dropsboot, see "Client navigation".) - Pageviews count once per navigation. The navigation fetch carries
x-yumemi-navigate: 1; for it the gate puts<meta name="yumemi-pageview">in<head>instead of the pageview script (same conditions as the script, 200 HTML, apageviewPage) and addsvary: x-yumemi-navigate. The client posts the pageview (kindspa) only after it swapped that page in; a fallback to a page load gets the script as before. (0.12 replaces this: see "The gate and the CMS features" below.) - Reload after a write stays in the page. An island's
yumemi-donecallsnavigate.reload(): on a routed Page it refetches the current URL the same way (no history entry, scroll kept, pageviewkindreload); otherwise it reloads the page. (0.12: a Component's AfterReloadPage, see "Interactive Components".)
0.11.5 adds, without changing or removing the existing public types:
- Gate: send back with a return path.
Fail.RedirectBack(location, param)answers 302 to the face pathlocationand puts the request's path + search, URL-encoded, in the queryparam(joined with&whenlocationalready has a query). When the request's path + search is not a face path (theSafeParamcheck: it starts with//, or has a backslash or a control character) the param is left out, so the gate never sends anyone to another origin.locationmust start with/, not//, and carry no backslash, control character or#;paramis[A-Za-z0-9_.-]+— the generator stops otherwise (exit 4). A client navigation fetch gets the same 302; the client falls back to a page load as for any redirect. - Gate: a fixed redirect that keeps the query.
To.FixedKeep(location)answers 302 tolocationplus the request's query.Fixed(location)is unchanged (drops the query). The hash never reaches the server; on a page load the browser carries the original hash across a redirect without one, and a client navigation falls back to that page load.locationfollows the same face-path rule asRedirectBackand has no?either. - A gate that uses neither word gets the same
gate.mjsas 0.11.4, character for character. - A missing root statement stops generation. A Service with a root Entity reads its root with
db/queries/<service>/root.sql. Without it the runtime answers 503, so the generator now stops with exit 3 naming the Service. Services that build their root another way are not stopped: a Service answered by aservice_<name>hook (a Durable Object port), a queue consumer that borrows the root of a Service that has a root statement and calls it through the queue,Rootless, and roots with no Entity (Carriedonly). - Faces narrower than the entries are enforced at runtime. A Service that declares two or more faces gets
entries: [..]insrc/gen/registry.mjswhen an entry outside its faces could still route it (same credential kind; aReadOnlyentry only for a Read Service), and check 7 answers 403 on any other entry. A Service with one face keepsentry: '<name>'as before (the same face repeated counts as one); a Service whose faces hold every entry that could route it (all four session faces in our in-house service) gets neither.
0.11.6 changes when the outbox is swept, without changing the public types:
- A request that wrote to the outbox sweeps it, whatever its status. The fetch handler wraps the request's database handle and notes every statement or transaction that inserts into
framework.outbox(INSERT INTO framework.outbox, also inside aWITH, in generated and hand-written SQL alike; comments and string literals do not count, quoted identifiers are not recognised) and resolves, that is, commits. After such a request — 200, 4xx, 5xx or a thrown error —waitUntilruns the sweep, as a 202 always did (202 still sweeps). A request that only reads, or whose outbox insert failed or rolled back, does not sweep. The cron sweep is unchanged. - Each row is sent once by overlapping sweeps. The sweep claims a row with
framework/outbox_claim(a conditionalUPDATE … SET sent_at=now() … RETURNING id) before it sends it, and skips a row it could not claim. A second sweep that reaches the same row waits for the first one's row lock, re-reads the condition and gets no row.framework/outbox_sentis no longer called. A row whose send fails after the claim waits out the resend window (1 hour) like a lost message and is sent by the first sweep after it (a request that sweeps, a 202 or the cron); 0.11.5 resent it on the next sweep. Consumers stay idempotent. - The generator adds a default
framework/outbox_claimstatement tosrc/gen/sql.mjswhen the app has nodb/queries/framework/outbox_claim.sql; the app's own file wins. Its resend window (1 hour) must match the app'sframework/outbox_sweep.
0.11.7 adds, without changing the existing variants' meaning or output:
- Style grows the look vocabulary (see the Style section above):
Background,Border(all edges or bottom only),Outline(the focus ring, alwaysoutline-style: solidwithoutline-offset),min-width/min-height/max-widthinSpace,Named(..)font families (a CSS variable or a family name),SemiBold(600), andCrop(object-fit+aspect-ratio). Color values stay strings (var(--ma-*),color-mix(..)pass through). Generation from an unchanged app is byte-identical.
0.11.8 adds, without changing the existing variants' meaning or output:
- Style:
Sizing(box-sizing),Marker(NoMarker)(list-style: none),Decoration(text-decoration: none/underline), all usable insideState(..)/Responsive(..). - Area flow reaches the grid CSS (see the Area flow section above). Regenerating an app changes only the Area rules of the grid CSS.
0.11.9 adds, without changing the existing variants' meaning or output:
- Layout knows the page:
front.FromgainsCurrentRoute(see Layout vars above). The shell carries it as a constant per page; the shell's branch for it is written only for a face that uses it. - Style:
State(Current, ..)(aria-current), and the lengthsVar/Env/Dvh, read by the generator in Area gaps andstyleconstants too. - Overlay:
pin: AnchoredOverlay(..)opens next to its opener (CSS anchor positioning; centred as before without it). - Regenerating an app that uses none of these is byte-identical.
0.11.10 adds, without changing the existing variants' meaning or output:
- Grid style:
front.StyledFrame(.., style:)puts a Style on the grid element (see Grid style above). - Pin:
BottomFlush(bottom 0, safe area as inner padding);Bottomis unchanged. - Style:
Wrap(Anywhere / BreakWord / WrapNormal)(overflow-wrap). - Regenerating an app that uses none of these is byte-identical.
0.11.11 changes documentation only (one README sentence and one source comment). No code, type or generated output changes.
0.11.12 adds, without changing the existing output:
- Shell: the optional constants
manifest,theme_color,icon,apple_touch_icon(elements in<head>) andservice_worker(registered by the generatedclient.mjs) (see Shell above). A wrong type or an empty string stops with exit 3. - Regenerating an app that uses none of these is byte-identical.
0.11.13 fixes Page(theme: Some(name)), which always gave None at runtime (the shell looked up name at the top of the last source's Out):
- Page theme: the theme is taken from the Service the generator picked, along the field path to its
PageTheme(see Page theme above). Only the generatedshell.mjsof a face with a themed Page changes (the theme row and thepageThemelookup). - Regenerating a face with no
theme: Some(..)Page is byte-identical.
0.11.14 adds, without changing the existing variants' meaning or output:
- Style:
State(FocusVisible, ..)(:focus-visible, keyboard focus only) andState(HoverCapable, ..)(:hoverinside@media (hover: hover)), so a tapped button keeps neither the focus ring nor the hover background (see Style above).Hover,Focus,DisabledandCurrentrender exactly as in 0.11.13. - Regenerating an app that uses none of these is byte-identical.
0.11.15 changes client navigation and adds a Shell constant:
- Pages with a CSP navigate on the client. The gate's
frame_srcPages are now in the client's route table with their CSP (cspinstart), and the client takes a navigation only between Pages with the same CSP as the one that loaded the document, checking the response's header against the table (see Client navigation above). A face whose Pages all carry the sameframe_srcnavigates on the client everywhere. Only the generatedclient.mjsof a face withframe_srcPages changes (the routes line). - The head is diffed, and stylesheets are awaited. Navigation keeps identical
<head>elements in place, and swaps the body only after new head stylesheets and the next body's stylesheets have loaded (see Client navigation above). - Shell: the optional constant
stylesheets: List(String)(<link rel="stylesheet">in<head>) (see Shell above). - Regenerating a face with no
frame_srcPage and nostylesheetsis byte-identical (the framework code in the bundledclient.mjschanges with the version, as with any version that changesnavigate.mjs).
0.12.2 fixes five holes that an app shaped unlike our in-house service fell into (an entrance named apart from its Host variant, no queue kind, no subject Entity, no hand-written FFI, a page size chosen by the caller, an Entity whose id the app does not make), without changing the public types:
- The entrance host is looked up by the entrance's name. The generated
hoststable maps each entrance name to its<ENTRY>_HOSTvariable, and the runtime now reads it by name, soHttp(name: "api", hosts: [ApiHost], ..)answers onAPI_HOST(0.12.1 looked it up by the variant's name,api_host, and answered 404 to every request). An entrance whosehostslist is empty is reached on no host and is left out of the allowed Origins, as before. src/gen/verb.gleamtakesstagefrom the generatedsrc/gen/operations_ffi.mjsnext to it. 0.12.1 pointed atsrc/operations_ffi.mjs, which only an app with a hand-written bridge had, so the Worker bundle stopped.- An app with no queue kind gets a
src/gen/queue_runtime.mjs(sweepresolves to 0 without reading anything,consumedoes nothing), becauseshell.mjsandcron_runtime.mjsimport it; it imports neither the outbox runtime nor its SQL. The file of an app with queue kinds is unchanged.src/gen/runtime.mjsimports./subject.mjsonly when a subject Entity exists (the only casesrc/gen/subject.gleamis written). - A page whose size is a hole (
Paged(size: Param(..), ..)) is cut at the size of the request, the value bound to the SQL'sLIMIT $n + 1(the read's keyset carriessizeArg, the hole's place among the read's args). 0.12.1 cut every such page at 20, so a request for any other size got size + 1 items and nonext. A constant size (Paged(size: Num(n), ..)) is cut atnas before. A size below 1 is answered 400invalid_argumentwithfieldset to the hole's name (sizeFieldin the keyset,limitforParam(Limit)) before any SQL runs. There is no upper bound: the app caps the size itself. auto_key: the runtime makes the key. An Entity module may declarepub const auto_key: List(String) = ["id"], naming its key Property, when the app does not make the key itself. The Property is left out of the Entity'sDraft(the create Service passes no id), and the create verb'sINSERTstill writes the key column: the runtime fills it with a UUID derived from the request's seed (as it fills the key column of every created Entity), and theCreatedvalue the verb returns carries that key. 0.12.1 left the column to the database'sDEFAULT, but theCreatedvalue is built before the commit, so every create answered 400invalid_argumenton the key and wrote nothing. The key must be a single Property (not part of a composite key) whose value type isUuidinsrc/types.gleam(pub const note_id: Spec = Uuid); any other type (a serial number, a text) or a composite key stops the generator with exit 4.CreateMany(verbs.CreateMany) of anauto_keyEntity still leaves the key column out and needs a databaseDEFAULT(for exampleDEFAULT gen_random_uuid()). An Entity withoutauto_keyis unchanged: its key stays in theDraftand the create verb's SQL and runtime table are byte-identical.
0.13.0 adds idempotency keys for writes and a switch for the SQL endpoint. It needs a new table in the app's database (framework.idempotency, below), so an app moves from a 0.12 lock to 0.13 together with that DDL. The public Gleam types are unchanged and ★ sources need no edits; regenerating writes the new SQL, the DDL file and the purge into shell.mjs.
- A retried write lands once. A request to a write Service (effect
Write, run by the runtime; not aservice_<name>port, not an attached route) that carries anIdempotency-Keyheader is recorded inframework.idempotencyunder (party, key): the response's status, content type and body, written byframework/idempotency_recordas the first statement of the write's own transaction (the business statements, the outbox and the audit rows follow in the same transaction, so the record and the write commit or roll back together). A second request with the same key and the same body gets the recorded response (withidempotency-replayed: true) and runs nothing; the same key with another body is answered 409{"code":"idempotency_conflict"}. "The same body" is compared throughrequest_hash, an HMAC-SHA256 under the Worker'sIDEMPOTENCY_HASH_KEYof the Service name and the request's fields (query, JSON body and path holes, keys sorted), stored ash1:and 64 hex digits (0.13.2; 0.13.0–0.13.1 stored the plain SHA-256, which anyone who reads the table can reverse for a field with few possible values, such as a phone number — see below). A second request that arrives while the first is still running passes the first look-up, and its transaction then fails on the unique (party, key) and rolls back whole; the runtime reads the record again and answers the first one's response. Any failure of a keyed write (a business refusal without a write, a lost database response afterCOMMIT) also looks the record up once more before answering, so a write that did commit is answered with its response. - Who owns a record: the session's or the API key's party; without one, the signed browser mark (
browser:<id>); without either, one sharedanonymousowner. A key is looked up only under its owner, so another party that sends the same key gets its own write and never sees someone else's recorded response. Only the response that was sent is stored. - What is recorded: a write that commits (
step.doneafter staged verbs,step.commit's 202) and a refusal that writes its verb (step.reject, recorded in the refusal's own transaction). A business failure that wrote nothing (step.fail, a guard) is not recorded: retrying it runs the Service again. A field the database fills byRETURNINGis not known when the record is staged. For a generated create of an ordered Entity the record's body carries a mark whereordergoes, and the generatedverb/create_<entity>_idempotency_order(after the create, in the same transaction) replaces the mark with the created row'sorder, so the record matches the answer at commit and a retry after a response lost past the commit answers the database'sorder(0.13 r2; the mark is used only when the response shows the value as is — anapi_encodeorrespondhook that reshapes it keeps the repair below). A ★returned(a hand-written verb that copiesRETURNINGonto the value) is applied by the request that ran it: the runtime repairs the record withframework/idempotency_repairright after the transaction when the final response differs, and if that response is lost a replay answers the ★ fields as staged while the row itself is correct. - No key, no change. A request without the header (older clients, hand-written calls, cron, the outbox consumer) behaves exactly as in 0.12.2 and never touches the table. A key that is not 1–255 printable ASCII characters is answered 400
invalid_argumentwithfieldidempotency_key. Read Services ignore the header. - The client keeps the key until it has an answer. A Component's write send (not a read, not
GET, not an upload) makes a UUID for the Args it sends and puts it inIdempotency-Key. When the answer is unknown — a 5xx (the database's 503 included) or a network failure — the key and the form's input are kept and the error After (ReloadPage,GoTo) is not followed, so sending the same input again reuses the key. Any 2xx or 4xx drops the key; changed Args get a new key. A file field of a write send is uploaded once per chosen File: the blob key is kept with the key, so the retry sends the same Args under the same key instead of uploading again (an upload that answers a new key on every call would change the Args). Choosing another File uploads it and gets a new key; once there is an answer the kept blob keys are dropped with the key. - Old rows are purged by the cron. The generated
shell.mjsrunspurgeIdempotency(yumemi/server/cron.mjs) on every scheduled event, whatever the expression: it deletes rows older thanIDEMPOTENCY_RETENTION_HOURS(Worker env, a positive number of hours, default 24) withframework/idempotency_sweep. A retry after that window is a new write. The Worker needs at least one cron trigger for the purge to run. In an app that declaresLambda(0.16.0) it runs only on the wake that took the cron lease (see "cron on both targets"). - The DDL is generated, not applied. Every app with
src/server.gleamgetsdb/framework/idempotency.sql: the tableframework.idempotency (party text, key text, request_hash text, result jsonb, created_at timestamptz)with the primary keyidempotency_pkey (party, key)and the indexidempotency_created_at (created_at). Applying it is the app's DDL step. Until it is applied, a keyed write fails (503unavailable) and requests without a key are unaffected. - The SQL endpoint comes from the env.
driver.mjssetsneonConfig.fetchEndpointtoDLEAM_SQL_ENDPOINT(a full URL such ashttps://dleam.example/sql) when the Worker env has it, and leaves the driver's own endpoint (derived fromDATABASE_URL's host) when it does not; removing the variable goes back. It is set indatabase(env), so every database handle of the app's generated Worker (fetch, queue, cron,AppSystem) uses it. A Worker that callsneon()itself instead ofdatabase(env)callsuseSqlEndpoint(env)(exported bydriver.mjs) beforeneon(). - The generator adds default
framework/idempotency_find,_record,_repairand_sweepstatements tosrc/gen/sql.mjs; an app's owndb/queries/framework/<name>.sqlwins (to change the purge condition, for example).
0.13.1 adds the runtime Markdown Component, the 8 document tags and the document Style words (all above), and closes three holes a document site fell into. Public types only gain variants and modules; an app that does not hit the holes gets byte-identical generated output:
- A face no longer needs the back's static materials.
src/external_hosts.mjsand<repo root>/docs/api-v1.mdare each optional: when one is missing its copy (src/gen/external.gleam,src/gen/doc/api_v1.gleam) is not written to the faces, instead of stopping with exit 3. A file that is there and cannot be read, or whoseEXTERNAL_HOSTShas another shape, still stops.gen/doc/api_v1.gleamnames the face'sstyle.body,style.inkandstyle.heading; for a face whosesrc/style.gleamdoes not define all three aspub, it is written with no class (css.class([])). An app with both files and those names gets byte-identical output. - A
Pagedlist ordered by an integer, boolean, floating or text column reads. The keyset's first placeholder ($n IS NULL) of a list ordered in one direction gets the column's type (::integer,::bigint,::boolean,::double precision,::text), as the uuid / time ones already did; without it PostgreSQL could not determine the placeholder's type (the driver sends untyped placeholders and$n IS NULLsays nothing about it) and every page answered 503. Lists ordered by a uuid or time column keep their SQL, and the key's placeholder keeps the cast it had. - An internal failure is logged before it becomes
503 unavailable. When a request's failure is folded into{"code":"unavailable"}(not a business failure, not a connector failure, not answered by the app'sdb_errorhook),console.errorgets one JSON line{"yumemi":"request.unavailable","service":…,"code":<SQLSTATE>,"constraint":…,"table":…,"column":…,"name":…,"message":…}: a unique violation names its constraint ("code":"23505","constraint":"note_title_key"). Thedetail(which holds the key's value) is not logged, andmessageis logged only for SQLSTATE classes whose text holds no value (08, 23, 25, 40, 42, 53, 54, 57); it isnullfor class 22 (invalid input syntax for type uuid: "…"quotes the input) and for JavaScript exceptions (aJSON.parseerror quotes the input). The response is still 503unavailable.
0.13.2 keys the idempotency records' request_hash. An app that upgrades puts the secret in before it deploys: without it every write that carries an Idempotency-Key is answered 503 unavailable. There is no DDL change (request_hash text as before), the public Gleam types and ★ sources are unchanged, and the generated output is byte-identical.
- The hash is an HMAC under a Worker secret.
request_hashish1:+ the hex HMAC-SHA256, keyed by the Worker envIDEMPOTENCY_HASH_KEY, of the Service name and the canonical fields. The key is a Secret Store binding (its.get()returns the text) or a plain Worker secret (wrangler secret put IDEMPOTENCY_HASH_KEY); likeIDEMPOTENCY_RETENTION_HOURSthe app does not declare the name. It must be at least 32 characters (make one withopenssl rand -hex 32). The key's value and the HMAC's input are never logged, answered or recorded; replay and 409 behave as in 0.13.1. - No key, no keyed write. When
IDEMPOTENCY_HASH_KEYis missing, empty, shorter than 32 characters or cannot be read, a write that carries anIdempotency-Keyis answered 503{"code":"unavailable"}before anything runs or is written, andconsole.errorgets one line{"yumemi":"idempotency.key_missing","binding":"IDEMPOTENCY_HASH_KEY","reason":"absent"|"short"|"unreadable","service":…}(no value). It never falls back to an unkeyed hash and never runs the write without its record. Writes without the header, read Services, ports and attached routes are unaffected. The client keeps the key and the input on a 503, so the user's retry goes through once the secret is in. - Rotating the key. A record is also compared under
IDEMPOTENCY_HASH_KEY_PREVIOUS(optional, same forms), so a retry of a write recorded under the old key is still replayed (same body) or 409 (other body) after the switch; new records always use the current key. Rotate in three steps: (1) setIDEMPOTENCY_HASH_KEY_PREVIOUSto the current key's value (nothing changes yet); (2) setIDEMPOTENCY_HASH_KEYto the new value; (3) after the retention window plus the cron interval (by default 24 hours plus the time between two scheduled runs) removeIDEMPOTENCY_HASH_KEY_PREVIOUS. Setting the previous key first means no request ever sees the new key without the old one. A record whose key has already been removed from both bindings is answered 409, never written a second time. The comparison only works forward: while a deploy is still reaching every isolate, a retry of a record made under the new key that lands on an isolate holding only the old key is answered 409 (not a second write), and so is a 0.13.2h1:record retried on a 0.13.1 isolate during the upgrade or after a rollback to 0.13.1. - Rows from 0.13.1 are compared, not rewritten. A row whose
request_hashis 64 hex digits without theh1:mark (written by 0.13.0–0.13.1) is compared with the plain SHA-256 of the request, so a retry that straddles the upgrade is replayed (same body) or 409 (other body) exactly as before; no new row is ever written that way, and the cron purges the old rows within the retention window. A value of any other form is answered 409. Copies of the table (point-in-time restore, backups) taken before the upgrade still hold the unkeyed hashes until they expire.
0.14 tells the pages that are reading an Entity when someone else's write to it commits. The signal is one word (1) over a WebSocket: no body, no diff, no value of the Entity. The page that gets it reads again through the normal read Service, so whatever the reader may see is decided by the read as before. Using it takes three things in the app's Wrangler config and none in the declarations: the Durable Object binding, its migration and a secret.
- Where a signal goes. The destination is a Service's root Entity and the id of its root row (
<entity>:<id>, for examplenote:…). The generator writes the table insrc/gen/registry.mjs(export const live = { note_edit: ['note', 'id'], … }) and ★ writes nothing: a read and a write whose root is the same Entity meet on the same destination. Its write rows are every write Service with a root Entity; since 0.14.1 its read rows are only the read Services of Blocks that some face's Page places asLive(in 0.14.0 they were every read with a root Entity). The generator reads the faces and the api in the same run, so the api's table knows the faces'LiveBlocks without the api reading any face declaration at run time. A write that changes rows under another root (a list's order, an inbox count) does not signal that root's readers in 0.14. - A read carries a token. A read Service in the
livetable (the read of aLiveBlock, 0.14.1) that answers 200 on a session entrance (not an API-key one) gets the headerx-yumemi-live: <payload>.<signature>(both base64url). The payload is{"to":"<entity>:<id>","party":<the session's party>,"exp":<seconds>}, one hour out; a read without a session is bound to the browser instead,{"to":…,"party":null,"browser":<mark>,"exp":…}, where the mark is the first 16 bytes of the HMAC of thebrowsercookie's id under the same key (the id itself is not in the token), and a read without a session and without abrowsercookie gets no token, so no token is good for whoever holds it. The signature is the HMAC-SHA256 underYUMEMI_LIVE_KEYofyumemi-live/1\n<payload>. A read that did not pass (403, 404, a business failure) gets none, so only someone who could read the Entity just now holds a token for it. A read answered by the app'srespondhook with its ownResponsegets none either. A read that is not in the table gets no token and nox-yumemi-liveheader at all (0.14.1), even with a root Entity and a session: a token says "this person may hear when this root is written", and only aLiveBlock's read needs that. ALiveBlock's read must keep to the root's parties: a clause whoseownerisSelforVia<Entity>Partynarrows the root's rows to the session's party and passes; anAnyoneclause, aParty×NoOwnerclause (anyone with a session passes on any row of the root) and a clause the generator cannot read stop it (exit 4, see what the generator stops); an Entity subject ×NoOwner(Staff,AsFan) is let in with a warning (exit 0), since the generator cannot tell a trusted role from one anyone may sign up for. Narrowing byowneris not the whole answer: a party of the root still hears the time of every write under that root, including writes it may not read itself (a shop's private note under a cast member's root reaches that cast member as a signal); which writes go under aLiveroot is ★'s call. In 0.14.0 every read with a root Entity carried one, so a public read (Anyone) handed anyone a token that heard the same root's non-public writes (a ledger kept under the same root, say) as they committed; one word each, but at any time and for as long as the reader kept reading the public page. A page that holds a 0.14.0 token gets the new rule's token, or none, the next time it reads. The socket checks the token, not the table, so a 0.14.0 token is accepted until itsexp(at most an hour after the upgrade); changingYUMEMI_LIVE_KEYwithoutYUMEMI_LIVE_KEY_PREVIOUSat the upgrade refuses those tokens (signature, see rotating the key below), and sockets already open end at their token's expiry at the latest. - The socket.
GET <entrance prefix>/_yumemi/live?token=<token>withUpgrade: websocketgoes through the entrance's session checks and then, in order: the binding and the key are there,Originishttps://+ the entrance's host (or the app'soriginhook), the signature, the expiry, and the token's party equals the request's session party (a token without a party only for a request without a session, whosebrowsercookie has the token's mark). Then the entrance hands the destination'sYumemiLivean internal request that carries the token's expiry and party; the object keeps them on the socket and closes it at the expiry (close code4001, reasonexpired, through an alarm), andpublish()never sends to a socket past its expiry, so a socket opened before a logout or before the reader lost access hears at most until its token expires (one hour). A page reads again and opens a new socket with the new token. Anything else is 403{"code":"forbidden"}and one line{"yumemi":"live.refused","reason":"upgrade"|"binding"|"key"|"origin"|"token"|"signature"|"expired"|"party"|"browser"|<the entrance's refusal>,"entry":…}; the framework's lines never hold the token, the key or the destination. The token travels in the URL (a browser's WebSocket cannot send headers), so Cloudflare's request logs (Workers Logs, Logpush,wrangler tail) keep it with the URL; it holds the destination and the party, and it does not open a socket by itself: the session cookie and theOrigin(or, without a session, thebrowsercookie) are needed too. - Rotating the key. A token is also checked under
YUMEMI_LIVE_KEY_PREVIOUS(optional, same forms; a short or unreadable one is not used and logslive.key_missingwith its binding name); new tokens always useYUMEMI_LIVE_KEY. Rotate in three steps: (1) setYUMEMI_LIVE_KEY_PREVIOUSto the current key's value; (2) setYUMEMI_LIVE_KEYto the new value; (3) after an hour (the token's lifetime) removeYUMEMI_LIVE_KEY_PREVIOUS. Switching the key without the previous one refuses every token in use (signature) until the pages read again. - A write signals after it commits, without holding the answer. When a write Service's transaction commits, the entrance hands
publish()on the destination'sYumemiLivetowaitUntiland answers at once; the key is checked inside it too. A business failure, a refusal (step.reject, which commits only its own row), an idempotent replay and a write refused by its root (404) send nothing. A publish that fails (the object or the namespace throws) is one line{"yumemi":"live.publish_failed","service":…,"name":…}and the write's answer is unchanged. A write that commits and then fails while its answer is built (a 5xx) still signals. A write answeredAccepted(step.commit) signals once, when the HTTP request's transaction (with the outbox's parent row) commits; the rows the queue consumer writes later send nothing, nor do writes run by the cron, in 0.14 (only the HTTP entrance has thewaitUntil). Signals may be lost: a page reads again when it reconnects. YumemiLive. The generatedshell.mjsexports the class (fromyumemi/server/worker.mjs). It keeps no stored values (only an alarm for the next expiry), accepts sockets with the Hibernation WebSocket API, sends1to every socket within its expiry onpublish()and answerspingwithpongthrough the auto response (the object is not woken). A ★ Durable Object may not be namedYumemiLive(exit 4).- No binding, nothing changes. Without the
YUMEMI_LIVEbinding there are no tokens and no signals, and the socket is 403 (binding). With the binding but withoutYUMEMI_LIVE_KEY(missing, empty, shorter than 32 characters, unreadable; a Secret Store binding or a plain secret, asIDEMPOTENCY_HASH_KEY) reads answer without a token, writes send nothing, the socket is 403 (key), and each such read in the table or write logs{"yumemi":"live.key_missing","binding":"YUMEMI_LIVE_KEY","reason":…,"service":…}. Reads and writes themselves never fail for it. - The app's three steps (Wrangler config of the api Worker, nothing in
src/):
[[durable_objects.bindings]]
name = "YUMEMI_LIVE"
class_name = "YumemiLive"
[[migrations]]
tag = "yumemi-live"
new_sqlite_classes = ["YumemiLive"]
and wrangler secret put YUMEMI_LIVE_KEY (openssl rand -hex 32). The class stores no values (it sets only an alarm), but a Durable Object class still needs a migration; new_sqlite_classes is the kind every plan accepts.
- Generated output (api).
src/gen/registry.mjsgains thelivetable,src/gen/http_runtime.mjspasses it to the entrance, andsrc/gen/shell.mjsexportsYumemiLive. The api side adds no public Gleam type and no DDL.
On a face, ★ writes one word: Live in place of Fixed in a Page's placements. The Block is read again and applied in place when a write to its read's root Entity commits; what the user is typing (an IME composition included), open details and the scroll position stay.
import yumemi/front.{Bottom, Flow, Live}
placements: [
Live(area: "page", block: blocks.ChatThread, cell: Flow, edge: Bottom),
],
// in the Block: key the rows, and say where "new lines" are
html.ol(css.class(lines), [], [
el.each_keyed(it.lines, fn(line) { message_id.to_string(line.message) }, fn(line) {
line_view(line)
}),
]),
el.fresh(css.class(link), [el.text("新しい発言があります")]),
Live(area:, block:, cell:, edge:)is placed likeFixed. The destination is derived (the Block's read Service's root Entity and its id, as above); ★ writes no socket, no destination, no reconnect, no draft check and no scroll code.edgeis where new things arrive:Bottomfollows when the reader is at the bottom and otherwise stays and showsel.fresh;Topstays at the top when the reader is there and otherwise keeps the visible line where it was and showsel.fresh;Anywherekeeps the visible line and shows nothing. Without JavaScript nothing changes: there is no socket,el.freshstayshidden, and a link that reloads the page (★'s own) works as before.el.each_keyed(items, key, view)putsdata-yumemi-keyon each row's root element (not on a text or fragment root). Keys must be unique in the list. Rows that hold an interactive Component or adetailsneed keys: without them, a line inserted before an opendetailswould move the open state and the draft to another row.el.fresh(class, children)is a<button hidden data-yumemi-fresh>the runtime shows when a refresh changed the Block while the reader was away from the edge; pressing it goes to the edge and hides it again, and so does scrolling to the edge.- What the generator stops (exit 4).
Livein the Layout (Page placements only in 0.14), in apcortabletFrame's placements (onlyspplacements are drawn), the same BlockLivetwice on one Page, anedgeother than the three, a Block that does not take a read Service'sOut, a Block whose Service is a write, a Block whose Service has no root Entity (no destination), and (0.14.1) a Block whose Service is public, with anAnyoneclause in itsallow: its token would let anyone, signed in or not, hear when the root is written by any write, including writes the public may not see (… の allow に Anyone がある(公開の読みの札では、ログインしていない人も同じ root の非公開の書きの時刻を聞ける。Live の Block は root の当事者だけが通る読みにする)). Also (0.14.1) aParty×NoOwnerclause, shorthand (allow.Party) orClause(who: Party, owner: NoOwner, ..)with anyat: anyone with a session passes on any row of the root, so a signed-in third party could hear the root's writes (… の allow の句 Party(owner: NoOwner)は session があれば誰でも root のどの行も通す(ログインした第三者が同じ root の書きの時刻を聞ける。owner を Self か Via<Entity>Party にする)); and a clause the generator cannot read (a constant, a spread, anallowthat is not a List literal), which it cannot judge, as when it writes the read's SQL (… の allow の句が読めない: …). An Entity subject ×NoOwner(Staff,AsFan, thegen/allowshorthandallow.staff) is a warning (exit 0,… の allow の句 Staff(owner: NoOwner)は Staff なら誰でも root のどの行も通す(…)): whether that role is trusted or open to anyone is ★'s to know. A clause whoseownerisSelforVia<Entity>Partypasses. ALiveBlock's read is one only the root's parties pass; a page that is public and must still follow writes is not served byLivein 0.14.1. Warnings (exit 0): a keyless list in the Block (el.each,list.map,list.index_map,list.flat_map) whose rows hold an interactive Component or a plaindetails(html.details,el.element("details", …)), directly or through functions of the same module, andedge: Bottomwithoutel.freshin the Block. The check reads the Block's text, so it does not see rows built by functions of another module, by recursion orlist.fold, or a Component ordetailspassed in as a value; rows like these needel.each_keyedby ★'s own judgement. - What the face does. The shell wraps the placement in
<yumemi-live name edge token>(display: contents, so the Area's flow is unchanged) and copies the read'sx-yumemi-liveintotoken(no attribute when the api gives none: then the page opens no socket). A GET of the same URL with the headerx-yumemi-block: <name>(the Block's name in snake case) goes through the gate like the page (declarations, consents, session) and answers only<style>(the rules of the classes the Block used) and the<yumemi-live>element,cache-control: no-store: it reads the session if the Vars need it, the Block's read Service, and every other read of the Page and its Layout that is notoptional(for their 403/404; their bodies are dropped).optionalreads (the Layout's widgets, for example) are not read. The gate does not count it (no<meta name="yumemi-pageview">). A name that is not a Block of the Page (a Layout's Block, aWidget's Block, any other name) is 404 before any read; a read that is 403 or 404 gives the same status. Since 0.14.1 the same answer serves the Page'sFixedBlocks too (below). - What the browser does (
yumemi/front/live_block.mjs, started by the generatedclient.mjs). It openswss://<host><entrance prefix>/_yumemi/live?token=…with the token. On1it waits 0–500 ms (so a page many people watch does not refresh all at once), fetches the fragment and applies it; signals that arrive while a fetch is in flight fold into one more fetch. A gate redirect, 403 or 404 (and a 200 that is not the fragment) reloads the whole page (the client navigation's reload, or a page load); a 5xx, any other status and a network failure leave the page as it is and fetch again after 1 s, doubling up to 30 s, each wait jittered. The fragment's style rules that the document's current stylesheets do not have are added to one constructed stylesheet; the set of present rules is rebuilt from the document at every fetch, so a rule whose page<style>went away with a client navigation is added again. The element is applied by four rules: matched nodes never move (a forward-only match). The match does not skip over a node that holds focus, a Component with a draft or a control with a draft (and does not match such a node to a new node that cannot hold them) when a later new node can take it (the same key, holding the same Component or control); the new node in front is inserted instead. So a focused node or a draft leaves the document only when the new HTML has no node that can take it. Opendetailsare not guarded this way: in keyless rows they may move to another row (the generator warns); an interactive Component whose tag anddata-yumemi-argsare the same is not touched inside, and one whose Args changed is replaced only if its controls still hold the values they had when it connected and nothing in it has focus, otherwise it stays and gets:state(stale)(data-yumemi-state~="stale"where custom states are missing); the user's attributes stay (openofdetailsanddialog, the value of a focused control,hiddenofel.fresh), and an escape whose server attributes are unchanged is not touched; the key isdata-yumemi-key, then a Component's tag and Args, then the tag. The token that comes with a fragment is kept for the next socket; the socket itself lives until its token's expiry. - Reconnecting. Every time the socket opens (the first time too) the Block is read once, after the same 0–500 ms jitter, so writes between the page's render (or the last close) and the open are not lost. A dropped socket is reopened after 1 s, doubling up to 30 s, each wait jittered (between half and all of it), so a deploy that drops everyone's socket does not bring everyone back at once; the wait goes back to 1 s only after a socket stayed open for 30 s, so a socket closed right after it opens is retried with doubling waits too. A socket closed for its expiry (
4001) or refused before it opened waits the same way, reads the Block first and opens with the new token. Only the token drawn in the page has itsexplooked at: under a minute left, the Block is read before the socket opens; otherwise the Block is read once a minute before theexpand the socket reopened with the new token. A token that came with a fragment is opened without looking at itsexp(the server's4001ends it), so a client clock that is off does not loop. When the page becomes visible again (visibilitychange) a pending reconnect runs at once; with an open socket the Block is read once. - For escapes.
mount(element, yumemi)gets a second argument on a face withLive:yumemi.block(name, { href })reads the Blocknameofhref(default: the current URL). On the current URL it refreshes and applies the<yumemi-live>in place, as a signal would, and returns it; on another URL it returns that Block's<yumemi-live>element, not in the document, with its style rules already added and the URL it came from inhref, for the escape to place (for example withreplaceWith). A placed element reads again from itshrefon a signal and onvisibilitychange, andyumemi.block(name, { href })with that URL refreshes it in place. It returnsnullwhen the gate answers no fragment. Since 0.14.1 every face with escapes passesyumemi.block, and it also reads Blocks that are notLive(below). - Not in 0.14. The writer's own
ReloadPagestill replaces the body (it is not a morph yet). Rows under another root (a list's order, an inbox count) do not move. TwoLiveBlocks with different destinations open two sockets. - Blocks that are not
Live(0.14.1). The fragment answer also serves everyFixedBlock of the Page'sspplacements, on every face, with the same gate, Vars, session and reads as aLiveBlock (the Block's read Service, and the Page's and Layout's reads that are notoptional, for their 403/404). A Block that reads no Service (In = Nil) is drawn from the Vars alone; the Page's root read still runs for its status. The answer is<style>and<yumemi-block name>(display: contents, no token): the page itself does not wrap itsFixedBlocks, only the fragment does. When a Page places the same Block twice, the first placement (and its cell) answers; when a Block isLiveon the Page, theLiveone answers. Layout Blocks andWidgetBlocks stay 404.yumemi.block(name, { href })returns that<yumemi-block>(not in the document, its style rules already added, with the URL it came from inhref, also on the current URL), for the escape to place. It has no signal and never reads again by itself (not onvisibilitychangeeither);yumemi.blockwith the same URL reads it again and applies it in place by the same four rules and returns it, or returnsnull(and leaves the page and the placed Block as they are) for a redirect, 403, 404, 5xx or a network failure. A face withoutLiveloadsyumemi/front/block.mjsonly (the fragment, the style rules and the morph; no token, no socket), and only when it has escapes;live_block.mjsbuilds on it. - Generated output (face).
src/gen/load/**gains alive_<name>function perLiveBlock and (0.14.1) ablock_<name>function perFixedBlock of the Page,src/gen/shell.mjsthe Page'slivesand (0.14.1)blockstables and the fragment answer,src/gen/gate.mjsthe header check (0.14.1: on every face that has a fragment answer), andpriv/static/_yumemi/client.mjsthe runtime (live_block.mjson a face withLive; 0.14.1:block.mjson a face with escapes and noLive). The page HTML of a face withoutLiveis unchanged.
Imports outside the package
| Import | Imported by | Provided by |
|---|---|---|
@neondatabase/serverless |
yumemi/server/driver.mjs (Neon HTTP transport, database(env, observe)) |
the app's package.json |
cloudflare:workers |
yumemi/server/worker.mjs (DurableObject / WorkerEntrypoint) |
the Workers runtime (wrangler / workerd); not an npm package, so modules that import worker.mjs (the generated shell.mjs) do not load under plain node |
SQL — the runtime runs these keys through the app's SQL bundle (src/gen/sql.mjs, built from db/queries/**). The app writes them as db/queries/framework/<name>.sql against its own framework schema (DDL is the app's). Holes are positional, in the order below.
| Key | Holes | Used for |
|---|---|---|
framework/session_resolve_staff |
session id, at, first try | resolve a session cookie (a row with retry asks for a second pass) |
framework/api_key_resolve |
key digest, at | resolve an API key entrance |
framework/session_issue |
party, session id, credential version, expires at | issue a session (auth binding) |
framework/credential_floor |
party, floor | raise the credential version floor |
framework/session_revoke_party |
party, version | revoke a party's sessions below a version |
framework/session_revoke |
session id | revoke one session (auth binding) |
framework/session_onboard |
session id, party, subject id | bind a created subject to the session |
framework/session_subject_staff |
session id, party, kind, subject id | the SwitchSubject attached route |
framework/browser |
browser id, at, kind (0.12) | the Declare(attached, kind) attached route, once per declared kind |
framework/audit |
seed, stage, service, party, outcome, at | one row per entrance stage (used when framework/audit_entry is not in the bundle) |
framework/audit_entry |
seed, stage, service, party, outcome, at, entry, medium, client | one row per entrance stage with the entrance name, the medium (session, api_key, mcp) and the MCP client id (0.15.0; generated by default, needs db/framework/audit_entry.sql) |
framework/grant_resolve |
access token digest, at | ★, required with a SessionMcp entry (0.15.0): check 6 of the MCP endpoint, see below |
framework/grant_subjects |
party | ★, required with a SessionMcp entry (0.15.0): the party's subjects {party, kind, id, name?} for the consent screen and grant_issue's check |
framework/grant_issue |
id, party, entry, subject kind, subject id, client, credential version, access digest, access expires at, refresh digest, expires at, at | issue a grant (0.15.0; generated with a SessionMcp entry) |
framework/grant_refresh |
old refresh digest, access digest, access expires at, refresh digest, expires at, at | rotate a grant's tokens and extend it, keeping the old refresh digest in framework.grant_refresh_used (0.15.0; generated with a SessionMcp entry) |
framework/grant_refresh_reuse |
spent refresh digest, at | revoke the grant of a spent refresh token presented again (0.15.0; generated with a SessionMcp entry) |
framework/grant_revoke |
grant id or token digest, at | revoke a grant (0.15.0; generated with a SessionMcp entry) |
framework/outbox_parent |
id, dedupe key, payload (json), event id, at, folded | outbox parent row of a write |
framework/outbox_child |
id, kind, payload (json), parent id, at | outbox child row (one queue message) |
framework/outbox_done |
event id | mark a consumed event done |
framework/outbox_get |
id | load a queued message |
framework/outbox_sent |
id | mark a swept message sent (not called since 0.11.6) |
framework/outbox_sweep |
kinds | list unsent messages to resend |
framework/outbox_claim |
id | claim one swept row before sending it (0.11.6; generated by default, see above) |
framework/pageview_record |
event id, mark, face, at, kind, path, prev, referrer path, referrer host, client at, party, extra (json), dims (json), excluded | one counted event into the Store (0.12; generated by default, calls framework.pageview_record from db/framework/pageview.sql) |
framework/pageview_rollup |
at | the daily rollup of the Store (0.12; generated by default) |
framework/idempotency_find |
party, key | look up a recorded response before a keyed write and after its failure (0.13; generated by default) |
framework/idempotency_record |
party, key, request hash, result (json), at | record a keyed write's response, first in the write's transaction (0.13; generated by default) |
framework/idempotency_repair |
party, key, result (json) | replace a record whose response changed by RETURNING (0.13; generated by default) |
verb/create_<entity>_idempotency_order |
party, key, mark, created key, fallback | put the created row's order into the record in the create's transaction (0.13 r2; generated for an ordered Entity's create) |
framework/idempotency_sweep |
before | delete records older than the retention window (0.13; generated by default) |
Cron — a face whose gate counts into the framework Store makes the generated shell.mjs run the rollup on the cron expression 0 1 * * * (01:00 UTC, fixed by the framework). Add that expression to the Worker's triggers.crons.
Worker env — MCP_AUTHORIZATION_SERVER (0.15.0, the authorization server URL the MCP endpoint's metadata names; empty until the IdP has one), SECRET_HMAC (also the grant tokens' digests), DATABASE_URL, optionally DLEAM_SQL_ENDPOINT (0.13, the SQL endpoint) and IDEMPOTENCY_RETENTION_HOURS (0.13, default 24), IDEMPOTENCY_HASH_KEY (0.13.2, required for keyed writes; a Secret Store binding or a secret, at least 32 characters) and optionally IDEMPOTENCY_HASH_KEY_PREVIOUS (0.13.2, while rotating), COOKIE_DOMAIN, OUTBOX (queue binding), <ENTRY>_HOST per entrance, the key_binding of browser (a Secret Store binding or, since 0.16.0, a plain secret; at least 32 characters since 0.16.0), the KEK bindings of Sealed properties, optionally YUMEMI_LIVE (0.14, the YumemiLive Durable Object namespace) with YUMEMI_LIVE_KEY (0.14, a Secret Store binding or a secret, at least 32 characters) and optionally YUMEMI_LIVE_KEY_PREVIOUS (0.14, while rotating), and optionally ISOLATE_MARKER=1 (test header). 0.16.0 adds the names its declarations read (see "Targets" and "the 0.16.0 declarations"); for a Lambda target src/gen/targets.json lists every name, marked vars or secret.
yumemi/server ── Storage: where an Entity's table is and what it holds (0.14.5, 0.14.6)
pub const storage: List(server.Storage) in src/server.gleam overrides how the generator derives an Entity's table. InObject kept the Entity in a Durable Object instead of Postgres (closed in 0.16.0, below); Column, Text, Split and Array change how one Property sits in its columns. The holes stay one per Property; the SQL does the mapping. 0.14.5 adds two more. An app that declares neither generates the same files as with 0.14.4, byte for byte.
-
InSchema(entity:, schema:)puts the Entity's table in another schema thanapp. Every generated statement names the table<schema>.<table>: the verbs, the reads (FROM,JOIN,EXISTS, thewithchildren, the relation reads) and theallowclauses. Without it the table stays inapp. The schema must be a plain SQL identifier ([a-z_][a-z0-9_]*) and notframework, at most one per Entity (exit 4). Creating the table there is the app's DDL, as before. -
Derived(entity:, property:)declares a Property the table has no column for: the SQL that reads the Entity hands its value in from another table (aJOIN), under the Property's name. The generator writes no column for it: it leaves the Property out of the create and update verbs' columns and values,RETURNING, theDraftandCreatedtypes and the runtime's verb table, and generates noupdate_<entity>_<property>. The row decoders (the generated one or adecode_<name>hook) still read it, so every read that hands the Entity's rows must pass it: the hand-written root andManualReadstatements, e.g.JOIN … l ON …withl.<column> AS <property>(orto_jsonb(t) || jsonb_build_object('<property>', l.<column>)). WithoutReadFrom(below) a generated read cannot, so one that hands the Entity's whole rows (t.*offrom, ajoin'sto_jsonb, awithchild withoutPick, a relation read) is not written and stops the generator (exit 4,… の行を生成の読みで渡せない …), and so does a generated read naming the Property inwhere,order,grouporPick, filtering by it as thepartyof anallowowner (Via<Entity>Party) or orderingwithchildren by it asorder; pick the other columns withq.Pickor write the read by hand.Derivedstops the generator (exit 4) on a Property the verbs write or the table needs: a key orauto_key, theupsert_key, theordered_byfield or itswithin,version, the Lifecycle phase, a relation Property, a field of averbs.Updateorverbs.DeleteWhere, or one that also hasColumn,Text,Split,Arrayor a secondDerived. -
ReadFrom(entity:, relation:)(0.14.6) makes the generated reads of the Entity read another relation than its table, typically a view that joins in theDerivedvalues:ReadFrom(entity: "store", relation: "store_view")withCREATE VIEW app.store_view AS SELECT l.<column> AS <property>, s.* FROM app.store s LEFT JOIN … l ON ….relationis a name in the Entity's schema (app, or theInSchemaone). Every generated read names<schema>.<relation>where it named the table: thefrom, thejoins, the relation reads (to_<property>), thehasEXISTS, theallowclauses' path and thewithchildren. The verbs (create, update, put, delete, theirRETURNING, the statements that lock rows withFOR UPDATE) and the foreign keys still name the table, so the relation is never written. On an Entity withReadFrom, the generated reads may hand its whole rows and name itsDerivedProperties (the relation has those columns), so the readsDerivedalone stops are written; whatDerivedtakes out of the verbs,DraftandCreatedstays out.ReadFromwithoutDerivedis allowed. The relation must be a plain SQL identifier, at most one per Entity (exit 4). Creating the relation, and keeping its columns those of the table plus theDerivedones, is the app's DDL. An app that declares noReadFromgenerates the same files as with 0.14.5, byte for byte. -
InObjectis closed (0.16.0). An Entity's record of truth is Postgres. AstoragewithInObjectstops the generator with exit 4 naming it; the constructor stays in 0.16.0 only so that the generator can name it, and is removed in 0.17.0. Move the Entity's rows to a table before upgrading. -
durable_objectsleaves the framework's words (0.16.0). An app that declaresLambdaanddurable_objectsstops with exit 4 (article 60), except for aDurableObject(module: "<gear>:<path>")that points at a gear's Workers module (see "Gears"); a Workers-only app keeps its Durable Objects in 0.16.0. The constructor is removed in 0.17.0: use Durable Objects from a gear's Workers module.
yumemi/server ── the 0.16.0 declarations
0.16.0 adds declarations to src/server.gleam (types in yumemi/server; the requirement Challenged in yumemi/require) for work an app used to write as ★ hooks. An app that declares none of them generates as before, except for the changes the CHANGELOG lists under "Upgrading from 0.15.0".
Typed reads (Read)
Read(service:, query:, args:, returns:, imports:) in server.reads is a ManualRead without hook: the generator writes the row mapping from the returns type, so a read that cannot be mapped goes back to ManualRead by editing one line.
- An Entity (
List(e.E),Option(e.E),e.E) is decoded with the codec's Entity decoder. A SELECT column that does not match the Entity's fields (theirstoragecolumn names) stops the generator (article 68);SELECT *is checked at runtime. - An app record (a one-constructor record under
src/) is read by field name. Field types: value types,Int,Float,Bool,String,yumemi.Datetime,Date,PartyId,Key(<Entity>), andOption/Listof these (aListfield is an array or the JSON text of one). - A value type (
Option(v),List(v),v) reads one column.OptionisNonewhen there is no row or the column is NULL; a bare type with no row is 404. - A tuple
#(…)(written out, or an aliaspub type X = #(…)) is read by column position, with the same field types as a record. - Types are resolved through
importsand the record module's imports and type aliases. A nested record or sum field, a value-type read that selects two or more columns, a tuple whose size differs from the column count, repeated column names, column names made only of digits (JavaScript reorders such keys), nested tuples and Entity fields in a tuple stop the generator (article 68) with the one line that turns it back into aManualRead. - NULL is never a value silently. A NULL in a non-
Optionfield, a bare value type, a tuple field or aListelement — and, in an Entity read, in the column of a non-OptionProperty — fails the read with 503 and the log line{"yumemi":"read.columns","read":…,"null":[…]}naming the columns. Make such a fieldOption, orCOALESCEin SQL (LEFT JOIN and aggregates produce NULL). An Entity read assumes the table's non-OptionProperty columns areNOT NULL: an app whose DDL allows NULL there gets 503 where the codec used to read a NULLjsonblist as[].
Hand-written SQL verbs (verbs)
Declare pub const verbs: List(server.ManualVerb), ManualVerb(service:, name:, query:, args:, lock: False, checks: []), and put the statement in db/queries/<service>/<query>.sql with $1… in the order of args. The generator writes a typed mouth gen/verbs/<service>.<name>(…) -> Verb(Nil) that the Service's Logic calls with step.apply; the runtime stages it in the same transaction as the generated verbs, in the order the Logic calls them.
- Arguments are
#(name, type):String,Int,Float,Bool,yumemi.Datetime,yumemi.Date,yumemi.PartyId, a value type ofsrc/types.gleam(by its type name),Key(<Entity>)for an Entity with a generated key (passkey.<entity>(id); the database gets the key's text),Option(…)of these, andList(<type>)of any of them (the database getsjsonb). A value type goes through itsencode_<name>hook, alone and inside aList.yumemi.At(the request'sat) andyumemi.NewKey(a new id from the same series askey.new_<entity>()) are filled by the runtime and are not arguments of the mouth. lock: Truestages the statement at the head of the transaction — after the locks already staged, before every other statement — wherever the Logic calls it. A Service may declare one.checks: ["<name>"]stagesdb/queries/<service>/<name>.sqlright after the verb's statement, with the verb's values from$1up to the highest$nthe check uses. If the check returns no row, or a row whose first column is false or NULL, the transaction is rolled back and the request fails with the business failure<name>(its status fromfailures, else 422). Write a check whose first column is a boolean —count(*) > 0orEXISTS (…): a barecount(*)returns one non-boolean row and never fails.- Sharing. A mouth that several Services call is declared on one Service and imported from
gen/verbs/<service>by the others. - Stops (article 63, exit 4). An unknown Service; the same name twice in a Service; a type outside the list; a name that cannot be a Gleam name; two locks in a Service; a check name that is not lowercase snake case or is
conflict; a check reaching past the verb's values; aqueryor check that points atroot.sqlor a generated SQL file; two imports of the same unqualified name in the generated module. A missing SQL file is exit 3. The names of the generatedsrc/gen/key.gleammust not collide (an Entityxbesidenew_x, a module namedioorer; article 64).
More than one new id in a request (key.new_<entity>())
A Service that needs more than one new id in one request (a customer row and its first reservation, say) calls key.new_<entity>() from the generated gen/key module: use id <- step.read(key.new_reservation()). Each call returns the next id of the same per-request series that the generated create_<entity> verbs draw from (derived from the request's seed), so ids never repeat inside a request. An idempotent replay returns the recorded response with the same ids; a new request draws new ids; a retried outbox delivery draws the same ids (see "cron on both targets"). The ids are not secrets — anyone who can read the audit rows can recompute them — so do not use them as capability keys in invitation tokens or URLs. new_<entity>() exists for Entities whose key is a Uuid value type.
A Service per due row (wakes)
Work such as scheduled publishing ("call a Service once when the time written on a row has passed") is pub const wakes: List(server.Wake) = [Wake(service: "article_release", query: "due")]. The generator wakes every minute (* * * * *; you write no expression) and calls the Service for each row the read <service>/<query> returns, with the wake's scheduled time in $1.
- Write the read as "due by
$1and not done yet", returning every such row — not a window such aspublish_at > $1 - interval '1 minute': a wake that was lost is made up only by the next minute's read, and a window would leave its rows behind. The read isdb/queries/<service>/<query>.sqlor the Service module'spub const <query>: q.Select; a missing read is exit 3 (article 80), an unknown Service or the same(service, query)twice exit 4 (article 79). - An app that declares
Lambdagets the Schedulercron(* * * * ? *)intargets.json, and the minute runs once even when both targets wake. On Workers add"* * * * *"to the Cron Triggers inwrangler.toml. Aserver.cronEachDueon the same read is redundant and gets a warning (article 79); remove it — on a differently spelled every-minute schedule such as*/1 * * * *it runs the read a second time each minute. - A Service whose work takes more than 60 seconds overlaps the next minute's wake on the same rows. Whether the work then runs once depends on the Service's own compare-and-swap and phase; a Service that calls out before its commit can call twice.
- Declaring
wakesalso runs the per-wake sweeps (purgeIdempotency, leases, counters, blobs) every minute. - A row that fails with a business failure is skipped and logged (below); a row that fails on the database or a connector ends that wake, and the remaining rows wait for the next one.
Windows for cron Args (Windowed)
Work that calls a Service once with period bounds in its Args — yesterday's or last month's totals, purging rows past a retention period — needs no hook:
server.Windowed(service: "metrics_rollup", windows: [
server.PreviousDay(arg: "day", zone: "Asia/Tokyo"),
server.PreviousMonth(arg: "month", zone: "Asia/Tokyo"),
server.MonthsBefore(arg: "purge_before", months: 13, zone: "Asia/Tokyo"),
])
The windows are computed from the wake's scheduled time, so a late wake, a retry and either target give the same values. PreviousDay is the previous day's Date; PreviousMonth is the first of the previous month on the first of a month (Some(Date)) and None on other days; MonthsBefore is the same wall-clock time n months earlier (the end of a month clamps to the last day); HoursBefore is n hours earlier; ScheduledAt is the scheduled time (these three are Datetime). zone is an IANA time zone name (Asia/Tokyo, America/New_York) and follows daylight saving time. Every Args field is filled by exactly one window (article 81).
- Limit: a zone name is checked against the ICU of the Node that runs the generator, which prefers some older names. With current Node, 15 canonical names —
Asia/Kolkata,Europe/Kyiv,Asia/Ho_Chi_Minh,Asia/Kathmandu,Asia/Yangon,America/Nuuk,America/Argentina/Buenos_Airesand others — stop with exit 4 and the message names the older alias (Asia/Calcutta) to write instead (article 82). Both spellings work at runtime.
Daily caps per person (quotas)
pub const quotas: List(server.Quota) = [Quota(name: "search", services: ["search"], party: 500, browser: 100, zone: "Asia/Tokyo")] caps how many times a person may call a Service per calendar day.
- A request to one of
servicesis counted against its session's party (limitparty) or, without a party, against its signed browser mark (limitbrowser). The day turns over at midnight inzone, an IANA time zone name such asAsia/TokyoorUTC, spelled with the exact case (offsets like+09:00, abbreviations likeJSTandAsia/tokyostop with exit 4, article 71). A quota withbrowserabove 0 needs abrowser(BrowserCookie) declaration (article 71). - Past the limit the request is refused with
429 {"code":"quota_exceeded","quota":<name>,"reason":"exhausted"}. A limit of0keeps that kind of caller out. A request with neither a party nor a browser mark is refused with"reason":"unidentified"without being counted, so dropping cookies does not lift the cap. - The count is one
INSERT … ON CONFLICT DO UPDATEonframework.counter(generateddb/framework/counter.sql; apply it before deploying), run after the idempotency lookup and the human check and outside the Service's transaction: read Services gain one write per request, and a replay of the sameIdempotency-Keyis not counted. A request whose Service fails with a 5xx (database or connector) is given its count back, so a transient failure followed by a retry is counted once; business failures (4xx) stay counted. Windows are deleted two days after they start, on the wake that purges idempotency keys.
A step before the app (before)
pub const before: List(server.Before) = [server.Before(hook: "guard")] makes both generated shells call ★ functions, in the declared order, before they dispatch.
- Put the function in
hooksasHook(name: "guard", module: "front")and export it fromsrc/front.mjsunder its camelCase name (guard;media_frontismediaFront). Its shape isasync (request, x) => Request | Response: aResponseanswers there; aRequestgoes to the next step (or, after the last, to the app). xhas onlyx.after(promise),await x.secret(name)andx.vars(name): no env, no bindings. On Lambda a name that is not in thesecretsoftargets.jsonis read as a plain string fromprocess.env./_yumemi/healthand/_yumemi/system/…do not go through the steps. A step cannot see the response, so it cannot add headers after the response or put a response in the edge cache.- A step that throws is answered differently by each target: on Workers it is the platform's exception, on Lambda a 503 or 500 with a
lambda.failedline. - A name that is not in
hooksor is listed twice (article 74), a missing file or a file that does not export the name (article 75) stop the generator.
A human check (challenge, Challenged)
Challenged(action) in a Service's requires admits a request only after a human check. Declare the provider once: pub const challenge: server.Challenge = Challenge(field:, secret:, provider:).
fieldis the JSON body field that carries the widget's token,secretthe secret holding the siteverify key, andproviderthe env var whose value picks the provider (turnstilefor Cloudflare Turnstile,recaptchafor Google reCAPTCHA v3). Because the provider is an env value, each target can use its own: a Lambda target can run onrecaptchawhile Cloudflare is down.- The runtime takes the token out of the body before the arguments are decoded, so it never reaches the Service, its arguments, the idempotency hash or the logs, and posts it to the provider after the idempotency lookup and before the Service runs (a retry with the same
Idempotency-Keyreplays the stored response). - A token that fails, was issued for another
action, or was issued on a host that is not one of the app's entry hosts is400 {"code":"invalid_argument","field":<field>}(reCAPTCHA also needs a score of 0.5 or more). The entry hosts are the app's own; another host (such as an identity provider's) is not included. A token is single-use: resending it after a business failure gets the provider's duplicate answer, so 400. - If the provider cannot be reached, times out, answers something unreadable or says the key is wrong, or the secret or the provider value is missing or unknown, the request is
503 {"code":"upstream_unavailable","connector":"challenge"}with one log line without values. - The providers' published test secrets are accepted only on a target whose
YUMEMI_CHALLENGE_TESTvar is1: there they skip the hostname check (and reCAPTCHA's score), accept an answer withoutaction, and log onechallenge.test_keyline per pass; without the var a test secret gets the same 503. Never put a test secret orYUMEMI_CHALLENGE_TESTon a production target: together they let any token through. - Exit 4 (article 70):
Challengedwithout achallenge, anactionthat is not a literal of up to 32 letters, digits or_(what both providers accept),Challengedon a read Service, or afieldthat collides with the Service's arguments. A pageviewToServiceService withChallengedis not stopped, and its events are dropped.
Calls between apps (systems, SystemCall)
- Offer a read to another app.
pub const systems: List(server.System) = [System(name: "crm_read", methods: [SystemMethod(name: "ledger", service: "ledger_read", fields: ["id", "total"])])]makes the generator write two doors: on Workers aWorkerEntrypoint(export const CrmRead; the caller's wranglerservicesusesentrypoint: "CrmRead"), and on both targetsPOST <prefix>/_yumemi/system/<name>/<method>. A method's Service is a read, allowed only by theSystemclause (the subject is the door itself,SystemActor); only the declared fields are returned. A business failure comes back as{error, status}; an infrastructure failure is thrown (503upstream_unavailableon the caller's side). Names are[a-z][a-z0-9_]*,appis reserved, and the env names derived from a name must not collide with the app's other declarations (article 69). - Call another app.
server.Connector(name: …, ports: [server.SystemCall(name: "remote_ledger", system: "crm_read", method: "ledger")])is the service bindingCRM_READ's RPC when that binding exists and hasfetch(a service binding), and otherwise a signedPOSTto the envCRM_READ_URL(the callee's URL up to its entry prefix, for examplehttps://api.example.com/api). A Durable Object namespace, KV, R2 or Secret Store binding with the same name is never used as the door. - Keys. Each door has its own key, at least 32 characters, the same value on both sides:
YUMEMI_APP_SYSTEM_KEYforAppSystem(the session and grant methods the identity provider calls,<prefix>/_yumemi/system/app/<method>), and<NAME>_SYSTEM_KEY(CRM_READ_SYSTEM_KEY) for a door ofsystems. While rotating, put the old key in<KEY>_PREVIOUSon the receiving side. Give each app its ownYUMEMI_APP_SYSTEM_KEYvalue: an app holding the value can issue sessions in every app that accepts it. - Signature. A request carries the time, a per-request nonce and an HMAC-SHA256 over the method, the target host, the path and the body's hash (
x-yumemi-system-*headers, signaturev2). The receiver refuses with 401 (and asystem.refusedline without values) a request without a valid signature, more than five minutes off, or whose nonce it has seen: nonces go intoframework.system_nonce. An app that declaressystemsorLambdagetsdb/framework/system_nonce.sql; apply it before deploying, or signed requests answer 503. Workers'AppSystemRPC through a service binding needs no key.
Declarations met by a consent (ConsentDeclaration)
ConsentDeclaration(kind:, claim:, max_age_days:, consent:) in browser.declarations reads a declaration from the account for a signed-in browser request.
- If the session's party holds the consent
consent(a name inconsents, else exit 4), the declaration is met; if it does not, the declaration is absent even when the browser cookie carries it. An anonymous request reads the cookie only; an API key or MCP request reads the cookie only (an MCP request has no cookie, so it staysdeclaration_missing). This is one rule for every Session entry, applied at the head of check 9 before thejudgehook, so the hook can still override it per entry. - When the
ReadSessionroute answers a party that holds the consent and the cookie lacks the declaration, it writes the declaration onto the cookie (keeping the mark, or making one) withSet-Cookieand aframework/browserrow, so the browser keeps it after signing out. If that fails (the database or the browser key), the response is unchanged and one line is logged without values. A declaration a hook met without the consent is never written. An app'sconsent_bake(s, kinds)hook, if present, is called with the kinds about to be written (afterjudge); when it returns false nothing is written for that request, so an app can keep a subject or an entry from writing the declaration. - A written declaration cannot be taken back. After the consent is lost (its version goes up, or it is withdrawn), signed-in requests are refused, but after signing out the browser reads as declared for the cookie's
max_age_days. - The declaring attached route (
Declare) still writes the cookie for a signed-in party without the consent, and answersdeclared: true, while the next session read answersfalse. - Counting pageviews is outside this rule: its
onlyand aToServiceService'srequiresread the cookie only, even for a signed-in request. The receiver always answers 202, so nothing is revealed. - The written declaration reaches the browser. The generated face gate and shell pass the browser cookie's
Set-Cookielines (thecookiename ofbrowseronly — not the session cookie) from their own/api/sessionread onto the response: the page, the gate's sign-in andRedirectresponses, itsDenyand 404 responses, and the failure page, when the session read answered 2xx. A signed-in browser gets the declaration on its first page and later pages do not write it again. This is done ingate.serve; an entry that callsbefore_route/after_responseitself does not get it. Faces of apps without aConsentDeclarationgenerate as before. An app that already passes these lines from its own entry should drop that bridge when it adoptsConsentDeclaration, or a page can carry the line twice.
Media storage (blobs)
pub const blobs: server.Blobs = server.Blobs(store: "MEDIA", record_party: True, orphan_hours: 24, reclaim: False, access: [server.BlobAccess(kind: "post", service: "post_read", fields: ["images"])]) makes the framework read and write the store and serve media at <entry prefix>/_yumemi/media/<kind>/<id>/<key>.
- Who may read. A medium is served only when the viewer can read the row
<id>withservice(a read Service whose first Args field is the id) and the key is in one offieldsof the answer (Blob,List(Blob)orOption(Blob)). The Service's gates (entry, phase,requires, allow) apply as on a direct call: 403 stays 403, everything else is 404. - The store. On Workers the R2 binding
MEDIA; on Lambda the S3 bucket named by envMEDIA(setMEDIA_ENDPOINTto point at R2's S3-compatible API instead). The DDL is the generateddb/framework/blob.sql. - Uploading. An Attached ★'s
x.blobs.put(bytes, {contentType, prefix})records the uploading party and time inframework.blob. A medium that no write Service has attached through aBlobArg withinorphan_hoursis deleted on a cron wake. Withrecord_party, only a write by the same party can attach it. - Large uploads (
x.blobs.upload, same on both targets): 1.x.blobs.upload({contentType, prefix, size})returns{key, upload, partBytes, parts: [{part, url, bytes}]}; 2. the uploader PUTs exactlybytesto eachurland collects theETags; 3. the ★ that finishes callsx.blobs.complete({key, upload, parts: [{part, etag}]})(orx.blobs.abort({key, upload})). On Lambda eachurlis a presigned S3 UploadPart URL, so the body does not go through the function; allow the face's origin toPUTin the bucket's CORS and addETagtoExposeHeaders. On Workersurlis the entry's/_yumemi/blobs/partand needsSECRET_HMACto sign its ticket. Completing and aborting work only on the uploader's (record_party) own media that are not attached yet and withinorphan_hours; anything else is 404. Unfinished parts are removed by the store: R2 after seven days; on S3 add a lifecycle rule withAbortIncompleteMultipartUpload. - One-shot uploads on Lambda.
x.blobs.presign('PUT', {contentType, prefix, size})makes and records the key and returns a URL for exactly that key, type and size (there is no form that takes a key).x.blobs.presign('GET', key, {expires})returns a timed read URL. A presigned PUT URL stays usable until it expires, even after the medium is attached. - Reclaiming. With
reclaim: Truemedia taken off a row, and media of deleted rows, are found by looking up everyBlobfield of the Entities (inside records,List,Optionand aliases too) and are deleted afterorphan_hours. Declare it only when attached media are found in EntityBlobfields alone; an app whose own tables also hold keys keepsreclaim: False, and attached media are then never deleted. A field type that cannot become a lookup stops the generator (article 78). Other mistakes inblobsare article 73. - Write
Blobitself in Entities a face reads. ABlobfield (Blob,Option(Blob),List(Blob)) of an Entity that a face reads must nameBlobdirectly, not an alias such aspub type Banner = Blob: the face's generated Out module cannot resolve the alias, and the generator stops with exit 1. - Lambda limits. The
raw_bodyupload route goes through the function and answers 413 above about 4.5 MB; usex.blobs.upload.uploadreturns every part's URL at once, so a very large number of parts can push its response past Lambda's 6 MB.
Image variants and the edge cache (edge)
pub const edge: server.Edge = server.Edge(images: Some("IMAGES"), cache: Some(server.EdgeCache(env: "MEDIA_CACHE", seconds: 86400))) (needs blobs and media, article 83) makes <entry prefix>/_yumemi/media/<kind>/<id>/<key>?v=<name> serve the media variant name.
- Variants. On Workers the Images binding
IMAGESconverts once to WebP and stores<key>/<name>. Lambda does not convert: it serves a stored<key>/<name>if there is one, else the original (x-yumemi-variant: original). - The edge cache holds only media a viewer with no session and no declaration mark could read. On Workers it is the Cache API, purged by tag with env
MEDIA_CACHE_ZONEand secretMEDIA_CACHE_TOKEN; on Lambda it is the CloudFront in front, by the response'ss-maxage, purged withCreateInvalidationon envMEDIA_CACHE_DISTRIBUTION(the execution role needscloudfront:CreateInvalidation). A target without its purge settings does not cache. - Purging. After hiding a row, call
x.blobs.purge([{kind: "post", id}])from an Attached ★. That is the only purge: after a Gleam Service's write, a cron job, a queue consumer or the framework's sweeps, edge copies stay up toseconds. - CloudFront. Put the query
vin the cache key, keep cookies out of it, and set the minimum TTL to 0 (above 0 CloudFront may keep aprivateresponse). - With
judge. An edge hit is answered at check 2, before theearly,origin_alwaysandjudgehooks, so ajudgethat tells requests apart by header does not work together with the edge cache. - What Lambda drops (conversion, the in-function edge) is listed in
/_yumemi/health'sdroppedand in a generator warning.
Per-owner sealing, key rotation and lookup values (seals, Rekey)
- Sealing. Declare
pub const seals: List(server.Seal), e.g.Seal(name: "chat", kek: "KEK_A", previous: Some("KEK_A_PREV"), dek: PerOwner(entity: "chat")), and type a fieldSealed(String, OwnerKey)on the owner Entity or on an Entity that holds it (Held/Has). Write it withsealed.for_owner(value). Each owner row gets its own 32-byte DEK, wrapped by the KEK read through the target'ssecret(kek)and stored inframework.<name>_key(applydb/framework/seal_<name>.sqlbefore deploying). The AAD binds the value to the Entity, the owner key and the row key. A read Service returns the plaintext only when its allow passed; elsewhere the field encodes asnull. There is no function to open a sealed value in Gleam (articles 76 and 77). - Rotation. Put the new key in
kek, the old one inprevious, and addserver.Rekey(seal: "<name>")to acronschedule. Each wake re-wraps up to 1,000 DEKs fromprevioustokekwith a per-row compare-and-swap; every DEK opens with one of the two keys at every point, even if a wake stops half way, and the next wake continues. Each wake logs{"yumemi":"cron.rekey",…,"rewrapped","failed","remaining"}; onceremainingis 0, remove theprevioussecret. ARekeywhose seal is not declared or has nopreviousstops the generator (article 84). - Rotation limit. Each wake starts from the beginning of the table. Rows that open with neither key are skipped and counted in
failed, but if more than 1,000 of them come first, no wake re-wraps anything andremainingnever reaches 0. Watchfailed. - Lookup values.
secret.lookup(value, label)makes an HMAC-SHA256 under the target'sSECRET_HMAC, separated bylabel(dotted lowercase words such ascustomer.phone). Put it in a read'sSecretargument to match stored values without storing the plaintext. A hand-written verb's ★ gets the same value fromx.lookup(label, value)— note the reversed order — which does not check the label: a swapped call stores a value no read will match.
Failure codes and statuses (failures)
pub const failures: List(server.Failure) gives a Service's business failures (the Logic's Fail) their HTTP status.
Status(code: "name_taken", status: 409)applies to the code everywhere;ServiceStatus(service: "store_read", code: "not_found", status: 404)only to that Service, and comes first. A code in neither goes to the ★ hookfailure_status, else 422. Statuses are 400–599 (article 65).Constraint(name: "note_title_key", code: "title_taken")turns a violation of the database constraintnote_title_key(unique, foreign key, check, exclusion) into the business failuretitle_taken({"code":"title_taken"}, status from the same table). A violation not in the table is still 503unavailable. The ★ hookdb_errorruns before the table.- A PostgreSQL
RAISEbusiness failure (SQLSTATEP0001), such as a failedchecksstatement of a hand-written verb, reads the same table:ServiceStatus, thenStatus, thenfailure_status, then 422.
Intake (intake)
pub const intake: List(server.Intake) overrides what an entry does before the Service.
EmptyIsNone(service:)reads an empty string''in anOption(_)of that Service's Args (inside records and lists too) asNone, for forms whose empty field arrives as''. Without it''isSome("").Idempotent(service:, enabled: False)turns the idempotency record off for that Service: a request withIdempotency-Key(or the MCP argument_idempotency_key) runs as if it had none — nothing is looked up or stored — so a response that must be shown once (a secret, a claim code) is never replayed.Trueis the default.Origins(entry:, env:)makes the Origin check of that entry's writes and live socket accept only the origins in the variable, separated by commas or spaces. An item without a scheme is a host (admin.example.com→https://admin.example.com), so a<NAME>_HOSTvariable can be named directly. Scheme and host are compared in lower case and without the default port (:443forhttps,:80forhttp); a refused write is 403 with one log line naming the request's origin and the entry. An empty or missing variable refuses every write and live socket of the entry. Without the declaration an entry accepts every host of the App, as before.- Exit 4: a name that is not a Service,
Idempotenton a read Service or bothTrueandFalsefor one Service,Originsfor an unknown entry, twice for one entry, or for an API key entry.
A record Arg is read from a JSON object. An Args field whose type is a record (one constructor, every field labelled, no type parameters, in any module of the app) is read from a JSON object by the same rules as an Args field — Option, List, value types, enums and nested records. A field that cannot be read is invalid_argument with field set to its path ("meta.inner.on"). On a GET the record is the JSON text in one query key, and a live module sends an empty List(record) as []. A record the decoder cannot derive (a tuple, a Dict, a record that contains itself) still needs the hook arg_<service>_<field>.
Business failures in queues and cron
- Not retried. When an outbox delivery ends in a business failure (the Logic's
Fail,step.reject, or aP0001RAISE), the row is marked done and one{"yumemi":"outbox.failed",kind,id,reason,code}line is logged; it is not retried by the queue or resent by the hourly sweep. Astep.reject's refusing verb is written in the same transaction as the done mark. A cronEachDueskips a row that fails that way, runs the rest, and logs{"yumemi":"cron.failed",job,reason,code}. Database and connector failures are retried as before. To run a failed piece of business again, create the row again (done rows are not sent). conflictis retried, and counted. A delivery that lost a verb's compare-and-swap (conflict) goes back to the queue. From the third delivery on it logs{"yumemi":"outbox.conflict_repeated",kind,id,attempts}(the count is the queue'sattempts, SQS'sApproximateReceiveCount). With wrangler'smax_retriesor SQS'smaxReceiveCountbelow 3 no line is ever logged, and a cronEachDueconflictis not counted.
The gate and the CMS features (0.12)
0.12 moves the features every business CMS needs into the framework: declarations, consents, counting pageviews (with uniques and visits), the CSP and image variants. The app only names kinds and values in closed vocabularies; nothing application-specific is spelled in the framework, the runtime or the generator. This is a breaking change.
The gate (<face>/src/gate.gleam, pub const gate: Gate):
Gate(
sign_in: SignIn(path:, fallback_origin:),
rules: List(Rule), // Rule(pages, except, checks)
redirects: List(Redirect), // Redirect(pages, when, to)
csp: List(Csp), // was frame_src (the entry's frame_src is gone too)
pageview: Pageview, // NoPageview | Pageview(pages, only, fields, sink)
)
Check = SignedIn(fail) | Declared(kind, fail) | SubjectKind(kinds, fail) | Consented(kind, fail)
When = WhenDeclared(kind) | WhenSignedIn
- Failure texts. These are every body the generated gate and shell answer on their own (a check's
Failanswers with what the app wrote:RedirectBack,ToSignIn, or aDenybody):503 unavailable— the session read (gate or shell) or a Page read (shell) answered 5xx, threw from theAPPbinding, or the session body was not JSON, and a gate without a session route. Never folded into401,403or an anonymous page; the original status and the cause go toconsole.error. When the gate cannot read the session on a page none of its rules or redirects cover, it hands the page on as not read, and the shell reads the session itself if the page needs it.401 unauthorized(shell) — a non-Optionsession field (FromSession) and no subject: the session is anonymous or its read answered 4xx. AnOptionfield getsNoneand the page renders.403 forbidden— the gate refused a permission (a subject mismatch, or a session read that answered 4xx other than 404 on a check; a 401 or 403 on asigned-incheck goes to itsFail), or a Page read answered 403.404 not found— the gate's session read answered 404 on a check, the root Page read answered 404, or no page matches and there is noSVELTEbinding (a widget read's 404 renders the widget asNone).<status> root read failed/<status> widget read failed(shell) — a Page read answered another 4xx; the status is the read's.500 PUBLIC_<NAME>_ORIGIN/500 PUBLIC_IDP_ORIGIN(shell) — the origin variable a page reads is unset or empty; the body is the variable's name.500 invalid variable source(shell) — a page variable with a source the shell does not know (a generator bug).
Declarations (Declared(kind)) are browser-level statements such as an age declaration. The app names the kinds in src/server.gleam:
pub const browser: BrowserCookie = BrowserCookie(
cookie: "_b", key_binding: "BROWSER_KEY", max_age_days: 400,
declarations: [Declaration(kind: "<kind>", claim: "<kind>_declared_at", max_age_days: 395)],
)
- The same
Declared(kind)shape is written in four places: the gate check,When, a Service'srequires, and the attached rolesDeclare(attached, kind)(sets the declaration) /NeedsDeclared(attached, kind)(403 without it). A kind that is not inbrowser.declarations, or any declaration withoutbrowser, stops with exit 4 (rule 32); duplicated kinds or claims, a kind outside[a-z][a-z0-9_]*or a declaration longer than the cookie stop with exit 4 (rule 33). - The signed cookie's payload is
{id, <claim>: time, ..}.id(32 hex) is the browser mark; each declaration is a field on it. A declaration older than its ownmax_age_daysreads as absent even while the cookie is valid. A 0.11 cookie ({id, <claim>}) reads as that declaration without being rewritten. - The key (
key_binding) is a Secret Store binding or a plain secret of at least 32 characters (0.16.0). A missing or shorter key is treated as missing: a request that would sign a mark or a declaration answers 503 and logs onebrowser.key_missingline (the env name and the reason,absentorshort; never the value), and cookies are not read, so marks and declarations read as absent. Changing the key invalidates every existing browser cookie (marks and declarations). - A missing declaration answers
403 {"code": "declaration_missing", "declaration": "<kind>"}. TheReadSessionroute returnsdeclared: {<kind>: true}(and no other declaration field).
Consents (Consented(kind), ConsentedFor(kind, subject: fn(args) -> String)) are party-level. The app lists the kinds in src/server.gleam (pub const consents: List(String)); a kind outside it in a requirement or a gate check stops with exit 4 (rule 40). ConsentedFor matches the consent's subject against subject(args). A missing consent answers 403 {"code": "consent_missing", "consent": "<kind>"}. ReadSession returns every consent the party holds as consents: {<kind>: true}.
The CSP is csp: [Csp(pages: List(Match), directives: [FrameSrc(hosts) | ImgSrc(hosts) | ConnectSrc(hosts) | MediaSrc(hosts)])]. The gate sets content-security-policy on HTML responses of the matched Pages (directives of every matching Csp merged in order, hosts as https://<host>). Every declared directive starts with 'self', added by the generator, because the pageview receiver, the client navigation fetch and /media/... live on the same origin: ConnectSrc(["api.example"]) becomes connect-src 'self' https://api.example. There is no way to drop 'self' in 0.12. Hosts are [a-z0-9.-]+ with one optional leading *.; a page outside the face's routes or a bad host stops with exit 4 (rule 38). There is no script-src. Client navigation still moves only between Pages whose CSP string equals the current document's.
Counting pageviews (Pageview(pages, only, fields, sink)):
onlyuses the gate'sWhen. The gate checks it when it marks a page, and the receiver checks it again when an event arrives; the app writes the condition once.fieldsis closed:NavKind(kind:initial/reload/spa, back and forward arespa),ClientAt,Path,Previous(prev, the tab's previous event id),Referrer(referrer_pathon the same origin, elsereferrer_host, only without a previous event) andFromQuery(name, param, Slug(max))([a-z0-9_]{1,max}, max 1–64). No regular expression strings are accepted. The framework always adds the eventid; the previous-event key isyumemi:pageview:<face>; the visit window (30 minutes) and the per-browser limit (60 per minute) are fixed. Duplicate field names, aFromQueryname that is one of the receiver's event fields (id,kind,client_at,path,prev,referrer_path,referrer_host), a badparamormaxstop with exit 4 (rule 35); a page outside the routes stops with exit 4 (rule 34).- One sender. The gate only adds
<meta name="yumemi-pageview">to a counted page (200 HTML, apagesPage,onlyholds), on a page load and on a client navigation fetch alike; it emits no inline script. The sender isyumemi/front/pageview.mjs, started by the generatedclient.mjs(a face with apageviewgets aclient.mjseven without islands). It posts once after a page load (afterrequestIdleCallback; a prerendered page waits for activation; a bfcache restore is not counted) and once per client navigation at the Navigation API'snavigatesuccess, reading the mark in the current document. Only a navigation that was intercepted (navigation.transitionis notnullatnavigatesuccess) counts; a fragment-only move and a same-documenthistory.pushState/replaceState(an island updating the query) firenavigatesuccesstoo but are not counted.navigate.mjsdoes not send. - The receiver is
<entry prefix>/_yumemi/pageviewson the face's entry and always answers202with no body. It drops bots and monitors (cf.verifiedBotCategory, user agent) and prefetches (Sec-Purpose: prefetch) without a row, keeps only the declared fields, and drops malformed events, all silently. An unexpected failure (an SQL error such as a missing table, an exception from the Service, a missing configuration) still answers202but is written toconsole.error, so lost events can be found. It also drops (0.16.0) an event whosepathcontains?or#, and drops such areferrer_pathfrom the event: the generated sender always sends a pathname. - The browser mark is set by the receiver: with
Store, the first event that passesonlyfrom a browser without a valid cookie gets a mark-only cookie ({id}); withToService, only such an event that also reaches a Service carrying the mark (Carried(.., name: "browser", ..)) gets one. The cookie has thebrowsercookie's attributes (HttpOnly; Secure; SameSite=Lax; Max-Age=<max_age_days>,Domain=COOKIE_DOMAIN). A later declaration adds its field to the same mark. sink: Store(resolve: Option(String), rollup_by: List(String), exclude_when: List(String))keeps events in framework tables (framework.pageview_mark/_visit/_event/_rollup); an event row keeps the mark and, when the request carries a signed-in session, its party (party). Same-id resends, the 61st event in a minute and two tabs at once are handled under the mark's row lock (framework.pageview_record).resolvenames a Service withArgs(path: String)whoseOutcarries the business dimensions;rollup_bynamesOutfields to roll up by,exclude_whennamesOutBoolfields whose true events are stored but not counted (the owner's and the operators' own views). The daily rollup (cron0 1 * * *) rebuilds the previous and the current UTC day and their months: page views, uniques (marks), visits and roaming visits (visits with 2+ views), per site, per path and perrollup_byfield. AStorewithoutbrowser, or whosefieldslackPath(the store counts by path), stops with exit 3; an unknownresolveor field stops with exit 4 (rule 37).- The DDL is generated, not applied. A
Storemakes the generator writedb/framework/pageview.sql(tables, indexes and the three functions). Applying it to a database is the app's DDL step. sink: ToService(service)is a named escape hatch: the receiver runs its checks (fields,only, bots, prefetch) and calls the app's Service with Args built from the event fields (rule 36:Argsmust haveid, else exit 3; every Args field must be one of the event's field names, fields that may be absent must beOption, and its type must decode from the event's value, a string, or one ofinitial/reload/spaforkind:String, a value type, anarg_*hook,Datetimeforclient_at, a bare enum with all three forkind, else exit 4; the Service'sallowmust have anAnyoneor aPartyclause, else exit 3, since the receiver passes events only through those two). The receiver evaluates the Service'srequires(declarations and consents, as for any call) and theanyone/partyclauses; an event that fails either never reaches the Service and sets no cookie. It does not applyphaseGates,suspended, or thejudge/write_gatehooks. The mark is set only when the Service carries it (Carried(.., name: "browser", ..)); the mark, the party and the subject reach the root as usual. Resends, the per-minute limit and concurrent tabs are the Service's job. The generator counts it in the face's escape line (exit 0, also in_diagnostics.txt). Since 0.16.0 the receiver is the only caller of that Service: its route is taken out of HTTP routing and the MCP tools (a direct call is 404); naming it inroutes(Route/RouteVia) oraliasesstops the generator (article 66), and so does a face that reads or calls it — a Block, a Widget, a Component'scallsorreloads(article 67). An app that took the route out with theroute_skiphook can drop that line.- Who is responsible. Pageview counting sets a signed, HttpOnly first-party cookie holding a random identifier, and sends only the fields you declare to your own API; nothing goes to third parties. Whether you must disclose this, ask for consent, or offer an opt-out depends on the laws that apply to your service (for example Japan's Telecommunications Business Act Art. 27-12 and the APPI, or the EU ePrivacy Directive Art. 5(3) and the GDPR). That responsibility lies with the operator of the application, not with yumemi; if your users need to opt in, count only after their action through
only.
Colours in Args. A Service's Args field typed color.Color (or Option(color.Color)) is decoded with color.parse; a broken colour answers 400 invalid_argument with its field and never reaches the Service.
Image variants. pub const media: Media = Media(path:, variants: [ImageVariant(name:, width:, height: Option(Int), fit: ScaleDown | Cover | Contain)], theme_background:) in src/server.gleam makes the generator write <face>/src/gen/media.gleam per face: a closed Variant type, name(variant), theme_background and url(blob, variant) (<path>/<key, each "/"-separated segment percent-encoded>?v=<name>). Duplicate or badly spelled names, or a theme_background outside the table, stop with exit 4 (rule 39). Serving, caching and purging stay in the app.