santoku-skills 1 >>> toku-setup --- name: toku-setup description: Install, verify or repair the toku toolchain for a santoku or Lua project. Use when the toku command is missing, setup-toku.sh fails, lua or luarocks are the wrong version, the wasm toolchain or openresty is missing, luarocks refuses a rock that pins lua 5.1, or a build fails before it compiles anything. Also covers running toku from the container image santoku-make ships when the native install keeps failing. --- # Getting toku running toku is the build, test and release harness for every santoku project. Do not substitute `make`, a shell build script, `luarocks install`, or a direct `lua` run over a spec file. ## Install 1. `curl -fSLO https://santoku.dev/setup-toku.sh` 2. Read the script. 3. `sh setup-toku.sh` 4. `export PATH="$("$HOME/.local/share/toku/rocks/bin/toku" setup --path):$PATH"` 5. `toku doctor` The script builds lua 5.1.5 and luarocks 3.13.0 from sha256-verified sources into `~/.local/share/toku` (honouring `XDG_DATA_HOME`) and installs santoku-cli and luacheck 1.2.0-1 there; `toku test`'s check stage needs luacheck and stops without it unless you pass `--skip-check`. It writes nothing outside that directory and edits no shell configuration. Prerequisites: `cc`, `make`, `tar`, `unzip`, `zip`, `curl`, `pkg-config`, `ps`, with `curl` 7.71+, one of `sha256sum`, `shasum`, `openssl`, and the pkg-config modules `blas`, `lapack`, `lapacke`. The script checks them all before it downloads anything. On a miss, it lists each missing prerequisite and prints the install command for the host's package manager. The commands for apt-get, dnf, brew and Android's pkg are at https://santoku.dev/install#install--install-the-prerequisites Walkthrough: https://santoku.dev/install#install--download-and-run ## Diagnose Run `toku doctor` first on any failure. It reports the mode, the resolved lua, luac and luarocks, drift against the pinned versions, PATH wiring, the managed node, and, inside a web project, whether the managed node, the wasm toolchain and openresty are present. It names the command that fixes each problem it finds and exits nonzero when anything is wrong. | Command | Use | | --- | --- | | `toku setup` | finish a partially built tree, or rebuild a luarocks built with older patches | | `toku setup --repair` | rebuild the tree at the pinned versions, keeping installed rocks | | `toku setup --resty` | add the pinned OpenResty for web projects | | `toku setup --node` | add node 24.22.0 for wasm tests (a PATH node 24+ where nodejs.org has no build) | | `toku setup --path` | print the managed bin directories for PATH wiring | | `toku setup --uninstall` | remove `~/.local/share/toku` entirely | Details: https://santoku.dev/install#install--doctor-repair-uninstall ## Escape hatch: run toku in a container A web project also needs OpenResty from `toku setup --resty` and node from `toku setup --node`, plus tailwindcss and esbuild. `toku test --wasm` runs only the node `toku setup --node` recorded, and stops with "wasm tests need the managed node; run: toku setup --node" without it. The wasm toolchain (wasi-sdk 34 and binaryen 133) downloads on the first wasm build on x86_64 or arm64 Linux and macOS; elsewhere it needs clang 18 or newer with wasm-ld, llvm-ar and wasm-opt on PATH. If the native install fails twice, switch to the images santoku-make ships rather than continuing to debug the host toolchain. ```sh curl -fsSL https://santoku.dev/setup-toku.sh | sh -s -- --container export PATH="$HOME/.local/share/toku/rocks/bin:$PATH" cd /path/to/your/project toku-web test toku-web -p 8080:8080 -- start --iterate toku-lib test ``` - `--container` needs only podman or docker: no compiler, BLAS or other host tools. It picks podman when podman is on PATH, else docker. - It fetches `toku-container.sh`, `toku-lib.sh`, `toku-web.sh`, `toku-lib.dockerfile` and `toku-web.dockerfile` from https://releases.santoku.dev/santoku-make/13.1.0-1/ into `$XDG_DATA_HOME/toku/container/13.1.0-1`. Those release files never change. - It builds the `toku-lib` and `toku-web` images, links `toku-lib` and `toku-web` into `$XDG_DATA_HOME/toku/rocks/bin`, and prints the PATH line. - The images carry a `dev.santoku.make` label with their santoku-make version. A rerun skips an image whose label names that santoku-make and rebuilds one whose label doesn't. `--rebuild` rebuilds them anyway. The wrapper refuses an image built from another santoku-make. - `--check --container` checks that both images carry that santoku-make and both commands link to its wrappers. It changes nothing. - `toku-web` and `toku-lib` run toku in the image with the current directory mounted at the same path. The build tree lands in your working directory as usual. - Everything after `--` is passed to toku, everything before it goes to the container runtime. - The wrapper keeps toku's download and built-rock caches in a named volume per image and santoku-make version, such as `toku-web-cache-`, mounted at `/opt/toku/cache`. A second run reuses the rocks the first built. - `toku start` serves on 8080 and the `toku test` server on 8081. Publish the port you need. The server must listen on all interfaces. A project whose nginx conf listens on a `BIND` address takes `-e BIND=0.0.0.0`. - One container reaches another's published port at `host.containers.internal:PORT`. podman provides that name, and under docker the wrapper adds it with `--add-host host.containers.internal:host-gateway`. - Use `toku-lib` for library projects and `toku-web` for anything with a `client/`. Library projects: https://santoku.dev/start-lib#start-lib--run-toku-in-a-container Web projects: https://santoku.dev/start-web#start-web--run-toku-in-a-container ## Your own image built with setup-toku.sh - Mount one build cache at the toku cache directory, `$XDG_DATA_HOME/toku/cache` (`/opt/toku/cache` with `ENV XDG_DATA_HOME=/opt`), on the setup-toku.sh RUN and on every toku RUN. Mount nothing else for toku. - setup-toku.sh and toku keep downloads in `downloads/` and built rocks in `built/` there. A rebuilt layer refetches nothing the cache holds. - `rm -rf $XDG_DATA_HOME/toku/src` after setup-toku.sh is safe. Never delete the cache directory inside a RUN that mounts it. - A download that moves less than 1 KB a second for 30 seconds fails and retries, up to 8 times. ```dockerfile ENV XDG_DATA_HOME=/opt RUN --mount=type=cache,target=/opt/toku/cache \ sh /tmp/setup-toku.sh --cli-version "$TOKU_CLI_VERSION" && rm -rf /opt/toku/src RUN --mount=type=cache,target=/opt/toku/cache toku build --env prod ``` Details: https://santoku.dev/install#install--keep-downloads-across-container-builds ## A private root, to test toolchain versions without touching the main tree `luarocks --tree DIR` alone doesn't isolate anything: toku's start-up prepends the managed `rocks/bin`, `luarocks/bin` and `lua/bin` to `PATH` and sets `TOKU_CACHE` to the managed cache, so builds still read and write `~/.local/share/toku`. Build a second root and point all three at it: ```sh D="$HOME/toku-private" sh setup-toku.sh --root "$D/toku" export XDG_DATA_HOME="$D" export TOKU_CACHE="$D/toku/cache" export PATH="$D/toku/rocks/bin:$D/toku/luarocks/bin:$D/toku/lua/bin:$PATH" toku doctor ``` `toku doctor` then reports `root: $D/toku`. The wasm toolchain downloads into `$D/toku/wasm` under the same `XDG_DATA_HOME`. Install the rock under test into that root with `toku luarocks install `. ## Failures with a known cause - `luarocks` refusing a santoku rock: santoku rocks pin `lua == 5.1`, and a system luarocks targeting a newer lua cannot install them. Use the managed pair, through `toku luarocks`. - A spec that fails when run directly with `lua`: specs run against the build tree `toku test` produces, including the installed rock tree under `build//`. Run `toku test`. - A web build failing one missing tool at a time: `toku doctor` inside the project lists all of them at once. >>> toku-project --- name: toku-project description: Navigate and build a santoku project driven by toku. Use when scaffolding a new Lua rock, web app or JSON API, when unsure where a new file belongs (lib, bin, res, test/spec, client, server, deps), when reading or editing make.lua, when a build lands somewhere unexpected under build/, or when choosing between toku test, build, start, install, pack and release. Covers the descriptor, directory conventions, environments and the toku test --iterate dev loop. --- # Project layout and the build loop `toku init --example NAME [name]` creates a project from one of santoku-make's examples, each complete and already building. With no `--example` it creates `lib`, a library rock. An unknown name lists every example and fails, and https://santoku.dev/examples shows each one's files. Add `--here` to scaffold into the current directory using its name. - `lib`: a library rock with a C module, a SQLite store and a command - `web`: a WebAssembly client plus OpenResty server. The todos stay in the server's SQLite, and the page calls the server for each read and write - `pwa`: the web app with its todos in SQLite in the browser, synced to the server, and a service worker so the app boots offline after a first visit - `api`: a JSON API with no frontend - `resty`: a library whose command and specs run under OpenResty's resty CLI, with santoku.async and santoku-http over santoku-resty - smaller examples that each demonstrate one rock, such as `search`, `classify`, `browser` and `websocket` ## Where files go | Path | Meaning | | --- | --- | | `make.lua` | the descriptor: name, version, license, dependencies, per-type blocks | | `make..lua` | an environment variant, selected with `--env ` | | `make.common.lua` | web scaffolds: the shared descriptor. `make.lua` (local, `minify = false`) and `make.prod.lua` (`minify = true`) merge over it | | `lib/` | Lua modules; `.c` files here compile as Lua modules with no extra configuration. For another rock's headers, add `rock.include("")` from `santoku.make.rock` to `cflags` and list the rock in `dependencies` | | `bin/` | executables; `toku install --bundled` compiles them to single native binaries | | `res/` | resources copied into the build and test trees, readable by specs and templates. A rock installs only `lib/` and `bin/` | | `test/spec/` | specs, discovered recursively, each run in its own interpreter | | `deps//` | a vendored template (Makefile plus helpers) copied into the build tree; its `results.mk` rule must list `Makefile` as a prerequisite, or the build stops | | `client/` | web projects: `bin/`, `lib/`, `res/`, `static/`, `test/spec/` | | `server/` | web projects: `lib/`, `test/spec/`, `nginx.tk.conf`, which renders `res/server/nginx.mustache` in the scaffolds | In every scaffold a hyphenated project name splits: the rock and the executable keep the hyphen, the Lua module and the C entry point use underscores, because `luaopen_my-lib_capi` is not a valid C identifier. `my-lib` publishes as `my-lib` and is required as `my_lib`, and `toku init --example web` for `my-app` writes `client/lib/my_app/main.lua`, required as `my_app.main`. Any file with `.tk` in its name is a build-time template. See the tk-templates skill. ## The build tree Output lands in `build/[-suffix]/`. `--env` defaults to `default` and selects `make..lua`. - `toku test` builds `build/default/test/` - `toku build` builds `build/default/build/` - `toku test --wasm` and `toku test --browser` build `build/default-wasm/test/` - `toku test --resty` builds `build/default-resty/test/` against OpenResty's LuaJIT and runs each spec with resty. A `*.resty.lua` spec runs only there. - `--wasm`, `--browser`, `--resty` and `--cuda` are one target flag set on test, build, install and clean. `--browser` implies `--wasm`. The others don't combine. - a web project builds one tree per environment: `build/default/dist/`, `server/` and `client/`. `toku test` adds `build/default/test/`, and its server runs in `build/default/test/run` Inside a test environment: a generated Makefile and `.d` files, a private `lua_modules/` install tree, copied `lib/` and `test/` trees, copied `deps/` templates, a generated rockspec. Upstream dependency clones and their installs live in the sibling `build//build-deps/`. `deps//` in the source tree is a template, never a build artifact, so never delete it. Prefer `toku clean` over manual removal. Because the test tree is a real installed rock, specs run against the installed layout rather than the source tree. Running a spec file directly with `lua` will not work. A spec for code that reads another program's output or a fetched file drives the real path. Put a stand-in binary on `PATH` that serves a verbatim copy of the real input, and compare the whole output against a pinned expected text. A short stub passed in through an option skips the read and hides format bugs. santoku-make 5.4.0 to 5.5.1 shipped three LICENSE bugs that way: lost blank lines, wrap orphans and joined paragraphs. A proof runs where the code ships. The proof root has every tool the release host and the image have (luacheck included, since `toku test` fails without it), and nothing they lack: to prove a tool can leave an image, build with that tool off `PATH` and check that `command -v ` fails first. A release that fetches prebuilt binaries is built once on arm64 Linux and once on Android before it ships. A negative control restores its file with `cp` and then `touch`, then `cmp`; `rsync -a` keeps the old mtime, and the build reuses the broken output. ## The dev loop Leave one of these running in a pane and edit in another: ```sh toku test --iterate # library toku start --iterate # web project: serve, rebuild, reload and rerun the specs toku test --iterate --show-logs # web project: the spec-only loop ``` What it composes: ```sh toku test # render, install deps, run specs, then luacheck toku test test/spec/foo.lua # one spec file toku test test/spec/core -s # the specs under test/spec/core, stop at first failure toku test ^test/spec/slow # every spec except those under test/spec/slow toku test server # web: the server suite only toku spec test/spec/foo.lua # run spec files with the spec runner, no project build toku test --skip-check # skip luacheck toku build # web: render client wasm and server tree toku start # web: run OpenResty against it toku stop # web: stops the server and a leftover test server toku build --env prod # web: the minified page, for an image or a deploy toku run lua script.lua # a script under the test tree's interpreter and paths toku run my-tool -x --flag # a bin/my-tool.lua from the test tree; every word passes through toku lua script.lua a b # bare interpreter, no project; put -- first for dash args eval "$(toku env)" # PATH, LUA_PATH and LUA_CPATH of the test tree toku install # install into the active rocks tree toku install --bundled --resty # each bin/ script as a resty launcher, tree in /share/toku/apps toku pack # rockspec and tarball, no release ``` Web notes: do not pipe `toku start`, because it backgrounds OpenResty and the pipe never closes. Flags that belong to another project type are rejected rather than ignored. - `build`, `start` and `stop` take no `--test`. - `toku build` reloads a running server when the build changes the dist. `toku start` on a running server rebuilds and reloads it. - `toku build` with no server running runs no `openresty`, so it opens no certificate or other file that `nginx.conf` names. `openresty -t` checks the config before `toku start` or `toku test` starts a server, and before a reload. A rejected config stops the command with openresty's text. - A pid file names a running server only when `ps -o args=` for that pid holds `-p DIR -c CONF`. DIR is the dist or `build//test/run`. CONF is `nginx.conf` for `server.pid` and `nginx-fg.conf` for `temp/server.pid`. toku signals nothing for any other pid file. - `toku start`, `toku test` and any command that finds a pid file need `ps -o args= -p PID` to work. When `ps` fails, the command stops before the build and removes no pid file. On Debian, install procps. `toku build` and `toku stop` with no pid file need no `ps`. - `toku start --iterate` starts the server, then after each rebuild reloads it and reruns the specs, all of them or only the spec file you edited. Its spec server runs beside the dev server. Ctrl-C stops the loop, the server and the spec server. `toku test --iterate` stays the spec-only loop. - A loop with no terminal runs under `setsid toku test --iterate`. End it with `kill -INT -- -PGID`, which reaches every child. - The loop polls the watched files every 0.5 s by stat (device, inode, size, and the nanosecond mtime and ctime). It sees edits on any mount, including a macOS bind mount under podman machine. An edit to one selected spec runs that spec alone. A web cycle runs every plain spec before any `.browser.lua` spec. - `toku test` starts the test server in `build//test/run`, on 8081. `toku start` serves on 8080, and a server that `toku start` runs stays up. - A server spec gets `PORT`, `DIST_DIR` (the absolute path of `build//dist`) and `RUN_DIR` (the absolute path of `build//test/run`). `toku test PATH...` selects specs by project path: - A PATH matches a spec whose path equals PATH or starts with PATH and a `/`. There's no pattern and no substring match: `test/spec/sync` leaves `test/spec/syncer.lua` out. - `^PATH` leaves the specs at or under PATH out. With no plain PATH, every spec that no `^PATH` matches runs. - A web project selects over its root, server and client specs at once: `toku test server`, `toku test client/test/spec/sync`, `toku test test`. - A PATH that matches no spec stops before the build with "PATH (command line) selects no spec". A named spec this build leaves out, such as a `.wasm.lua` spec without `--wasm`, stops with "no selected spec runs in this build". - A `.browser.lua` spec skips without `TOKU_CHROMIUM` or `CI`, unless a PATH equals the spec's path or its own directory. - `env.test.select = { "^test/spec/slow" }` in `make.lua` holds default PATHs for `toku test` and its loop. A plain command-line PATH at or inside a `^` entry lifts it, and plain PATHs replace the plain entries. `toku release [PATH...]` ignores the list. - Every run prints one `select` line: the count that runs, each exclusion with its source and count, and the suffix skips. `-v` lists each skipped file. The build tree holds only the selected specs. A spec that loads an unselected spec by a relative path (`fs.runfile("test/spec/other.lua")`) fails with "No such file or directory". Pass an absolute source-tree path instead. Sanitizers are an environment, so use `--env sanitize` with a `make.sanitize.lua` that bakes in the toolchain and flags, and preloads the runtime through `test.env_vars.LD_PRELOAD`. ## Local deps `env.local_deps` lists paths to lib projects, usually submodules, that install from source before the project. Since santoku-make 10.1.0 a local dep can list its own `local_deps`: the build installs one copy per `env.name`, dependencies first, and the project's own entry wins a name clash. A cycle raises `local_deps cycle`. A local dep's `res/` doesn't install, so embed templates in a Lua module (a mustache template pack) when a consumer needs them. ## Releasing `toku release` does not bump versions. Edit `version` in `make.lua` or `make.common.lua`, commit, then release from a clean tree; it tags, then runs the `env.release` hooks in order: push, host (`release.s3_upload` or `release.gh_release`), registry (`release.luarocks_upload`, key from `LUAROCKS_API_KEY`). A failed release names the phases that completed; rerunning reuses the tag when it points at HEAD, skips an upload whose published bytes match, and fails when they differ. Release in dependency order, dependencies first. Before tagging, a preflight fails the release when no version on luarocks.org meets a rockspec dependency, naming each one. After `s3_upload` and `luarocks_upload`, the release polls every public URL for about 159 s and fails naming one that never comes up. `luarocks_upload` also waits until `luarocks search` lists the version, so the next rock in a dependency-ordered batch passes its preflight. `toku release` runs test and check once for each test profile the rock declares, and prints one test line per profile. A profile that fails stops the release before the tag. `toku release PATH...` runs only the specs those paths select. With no PATH, every spec runs. | Profile | Declared by | | --- | --- | | native | every project | | `--wasm` | an `env.test.wasm` table, or a `*.wasm.lua` spec | | `--browser` | a `*.browser.wasm.lua` spec | | `--resty` | a `*.resty.lua` spec, unless `make.lua` sets `resty = false` | Before the release of a rock with C code that a web client bundles, build one consumer's page against the packed rock: follow the rock cache steps below, then run `toku build`. The rock's own suite and its consumers' native and wasi suites link no browser bundle. santoku-matrix 6.5.0-1 passed them, then failed two browser links with `undefined symbol: __multi3`. Before a batch, check every gate once, so the batch doesn't stop one rock per rerun: - every rockspec dependency is on luarocks.org or earlier in the batch - the release host's toolchain has what each suite calls (`toku doctor`, luacheck, a recorded node for wasm specs, `TOKU_CHROMIUM` for browser specs) - non-rock artifacts a release needs ship first: a versioned setup-toku, then the santoku.dev deploy that serves it, then the cli that pins it - a deploy handoff names the commit, the make, cli and setup-toku pins with flags, and every tool the build execs. It says whether another commit follows and by when, and it names the page paths and the text on each page that proves the deploy - a release runs under the installed santoku-make, so install the new make before `toku release`. Install it with `toku install --skip-tests`, because plain `toku install` runs the suite first santoku rocks are semver. Dependency constraints carry an upper bound (`"santoku >= 2.9.0, < 3.0.0"`); a bare `>=` admits the next major and breaks consumers at install time. A rock still below 1.0.0 breaks on its minor, so pin it like `"santoku-jwt >= 0.1.0, < 0.2.0"`. `toku luarocks search ` lists the published versions; start the range at the newest. A floor that crosses a dependency's major makes the rock's own release a major: santoku-fs 2.4.0 and santoku-sqlite 5.1.0 raised santoku to >= 3.1.0 in minors, and consumers on santoku 2 got two santoku versions in one tree. A release note lists every floor it moves, transitive ones included, and the consumers they reach. A consumer tests an unreleased rock from a rock cache: 1. In the rock, run `toku pack --skip-tests --cache DIR`. It writes `NAME-VERSION.src.rock` into DIR, rebuilds DIR's manifest and prints the rock's sha256. 2. Delete the consumer's build directory. A build tree that installed an earlier pack of the same version keeps it. 3. Run the consumer with `TOKU_CACHE=DIR`. A repack keeps the version string, so quote the `.src.rock`'s sha256 beside each result measured against it. ## Reference - https://santoku.dev/santoku-cli#santoku-cli--the-command-surface - https://santoku.dev/santoku-cli#santoku-cli--environments-and-the-build-tree - https://santoku.dev/start-lib - https://santoku.dev/start-web - https://santoku.dev/start-server >>> tk-templates --- name: tk-templates description: Write or edit a .tk file in a santoku or toku project (.tk.lua, .tk.c, .tk.html, .tk.conf, .tk.sh, .tk.txt). Use when putting build-time configuration into generated source, gating debug or verbose code out of a build, choosing between a runtime if and a build-time gate, or when a "<% %>" block is emitting the wrong thing. Covers value interpolation versus conditional inclusion with push and pop. --- # Writing .tk templates Any file with `.tk` in its name is rendered by santoku-template during the build and the `.tk` stripped from the destination: `main.tk.lua` becomes `main.lua`. It is rendered against the project environment from `make.lua`, so a template can read descriptor values the generated source cannot compute for itself. Expansion applies to every file in an environment, `test/spec` included. ## Interpolation versus gating | Goal | Form | | --- | --- | | Put a value into the output | `<% return expr %>` | | Include or drop a region of output | `<% push(cond) %>` text `<% pop() %>` | `<% return expr %>` substitutes the returned string at that point. Use it for data: a table field, a version string, a path. `push(cond)` opens a gate; everything between it and the matching `pop()` is emitted only when `cond` is truthy. Use it for code. ## The mistake to avoid Rendering a condition into a runtime `if` ships the dead branch and everything inside it: ```lua if <% return tostring(client.verbose or false) %> then js.console:log("...") end ``` Every non-verbose build now carries `if false then ... end`, the log call, and its string literals. Both forms compile and neither warns, so this survives review. The gate emits nothing instead: ```lua <% push(client.verbose) %> js.console:log("...") <% pop() %> ``` The else branch is `<% pop() push(not cond) %>`. ## Gate semantics - `push(cond)` ANDs with the enclosing gate, so an outer false gate silences everything nested inside it. - `showing()` returns the current gate state from inside a block. - Gating filters output only. Every block still executes, so an assignment made inside a false gate is visible after the `pop()`. - A block returning a non-string raises during render; a block that is not valid Lua raises during compile, before any render. - A block that returns nothing collapses the blank line it would have left behind. Verify against the source when in doubt: `push`, `pop` and `showing` are environment globals installed by `lib/santoku/template.lua` in lua-santoku-template. They are not fields of the module table, which exports `compile`, `render`, `serialize_deps` and `deserialize_deps`. santoku-template 3.0.0 reads no files: compile a file as `template.compile(fs.readfile(fp), fp)(env, global)`. ## What a template can see `readfile(path)` and `root_dir` let a small `.tk` file pull in a larger template kept under `res/`. `depend(path, prune)` records a file or a directory tree as a dependency without reading it, and returns `path`. Use it for anything a block reaches through `fs.runfile`, `require` or a directory walk, since `readfile` records only what it reads. Web projects additionally inject `hashed(name)` (the correct way to reference a content-hashed asset), `version`, the descriptor's `client` and `nginx` blocks, `modules`, `openresty_dir`, the lua package paths, and the output directories. The full list is on the santoku-template tab. ## Reference - https://santoku.dev/santoku-template#santoku-template--gates-with-push-and-pop - https://santoku.dev/santoku-template#santoku-template--nested-gates - https://santoku.dev/santoku-template#santoku-template--blocks-inside-a-false-gate - https://santoku.dev/santoku-template#santoku-template--tk-file-expansion - https://santoku.dev/santoku-template#santoku-template--tk-names-in-web-projects >>> santoku-primitives --- name: santoku-primitives description: Pick the right santoku module instead of the Lua standard library when writing Lua in a santoku or toku project. Use before calling string.*, table.*, os.*, io.*, math.* or package.*, before writing a helper that santoku probably already owns, and before assuming a santoku function name from surrounding code. Covers str, arr, tbl, fs, sys, env, err, utc, num, random, lua, serialize, validate, verifying names against source, and why fallbacks and compat shims are banned. --- # santoku primitives over the standard library Stdlib namespaces do not appear in application or library code. The owning santoku module carries the platform handling and the edge cases, and extending it means every consumer inherits the fix. Raw stdlib is legitimate only inside the primitive that wraps it, which is what `santoku.env.var` does over `os.getenv`. ## The mapping | Instead of | Use | Rock | | --- | --- | --- | | `string.*` | `santoku.string` | santoku | | `table.*` (arrays) | `santoku.array` | santoku | | `table.*` (maps, nested access) | `santoku.table` | santoku | | path strings: join, dirname, basename, extensions, relative | `santoku.path` | santoku | | `io.*`, file I/O, directory walking | `santoku.fs` | santoku-fs | | `os.execute`, `io.popen`, process spawning | `santoku.system` | santoku-system | | `os.getenv`, `package.path` | `santoku.env` | santoku | | `error`, `assert`, `pcall` | `santoku.error` | santoku | | `os.time`, `os.date` | `santoku.utc` | santoku | | `math.*` | `santoku.num` | santoku | | `math.random` | `santoku.random` | santoku | | `loadstring`, `setfenv` | `santoku.lua` | santoku | | writing a table back out as Lua source | `santoku.serialize` | santoku | | type and structure checks | `santoku.validate` | santoku | | `setTimeout`, a sleep loop, debounce, a retry loop, a cancellable request | `santoku.async` over a runtime | santoku | `santoku.num` merges `math`, so every `math` function stays reachable through it. `santoku.lua` merges its own C module, `santoku.lua.lua`, under `loadstring` and `setfenv`. Also present: `santoku.functional`, `santoku.op`, `santoku.inherit`, `santoku.fracidx`, `santoku.co`, `santoku.geo`. `err.pcall` and `err.xpcall` run `fn` in a `santoku.co` coroutine since santoku 5.0.0, so a sleep or an await inside them works in the browser's PUC Lua. `copcall` and `coxpcall` are gone. `require("santoku.async")(runtime)` returns `now`, `sleep`, `spawn`, `semaphore`, `latest`, `debounce`, `throttle`, `atleast` and `retry`. The runtime is `santoku.web.async` in the browser, `santoku.resty.async` under OpenResty and `santoku.system.async` in native Lua. Join spawned tasks with `semaphore(0)`, never a sleep loop. On the native loop, sockets, TLS, child processes and pipes yield inside a task, and a wait from the main thread runs the loop. Files, DNS and sqlite calls block. CPU-bound tasks run one after another, so parallel work means processes (`sys.sh` with `jobs`) or C with OpenMP. Under PUC Lua 5.1 a task can't yield inside a generic `for` iterator: drive `sys.sh`'s iterator with a `while` loop. Under OpenResty, `sys.sh` and `sys.pread` block the nginx worker. Use `santoku.resty.pipe`'s `sh` and `pread`, which take the same options and yield. santoku-websocket's reconnect uses `backend.runtime`. santoku-mysql pools when its tcp backend has `semaphore(n)`, which santoku.socket.tcp and santoku.resty.tcp both export. `db.retry_busy` and `jwt.remote_jwks` take `opts.runtime`. An app keeps one module that builds it, such as `return require("santoku.async")(require("santoku.web.async"))`, and every other module requires that one. The reference is https://santoku.dev/santoku#santoku--santoku-async. `sys.execute` and `sys.sh` take an argument list and exec it directly, with no shell between. Nothing in an argument is word split, glob expanded or interpreted, so values that came from a filename, a network response or user input cannot become commands. They also raise on a nonzero exit rather than returning a status to check. That is the whole reason to reach for them instead of building a command string: there is no quoting to get right, because nothing parses the string. Local aliasing at the top of a file is the house style: ```lua local str = require("santoku.string") local arr = require("santoku.array") local fs = require("santoku.fs") ``` ## Verify every name against source Never infer a santoku API from prose, from a neighbouring file, or from memory. Confirm it: - Lua module: read its `return { ... }` table. - C extension: read the `luaL_Reg` table in the `.c` file. - Either way: https://santoku.dev//llms.txt carries that rock's documented modules with working examples, and https://santoku.dev/llms.txt indexes the rocks. A fabricated name that looks plausible is the failure this rule exists to prevent. ## No fallbacks, no compat shims One implementation that works everywhere. Never a rescue path behind `pcall`, `or`, or a feature probe, and never an old branch kept alive in case something changes. A fallback that hides a failure is a bug: work one way or fail loudly. - `arr.spread`, never `unpack or table.unpack`. - `santoku.lua` owns loading, never `loadstring or load`. - No capability guards in code that only ever runs on Lua 5.1. ## Random numbers in C The fast generator in `` is one state per Lua state, shared by every C extension, and `random.fast_seed(n)` seeds all of it. Call `tk_fast_bind(L)` at the top of each entry point, or in `luaopen`, before `tk_fast_random`, `tk_fast_normal` or `tk_fast_seed`. A draw before any bind aborts. For a call-local stream, seed a `uint64_t` with `tk_hash_mix(seed)` and draw with `tk_fast_step(&state)`. ## Lua 5.1 only The whole stack targets 5.1, and exploits it: userdata `fenv` for per-object anchoring, userdata-only `__gc` for finalizers, a single `number` type, lightuserdata pointer keys. Do not add portability shims or "may break in 5.2" caveats to code, docs or comments. ## Parsing and text transformation `santoku.lpeg` exports finished parsers only (JSON field streaming, CSV, the HTML scanners, plus `santoku.lpeg.strip`), so a new parser is written one layer down, in either of two notations for the same engine: - `santoku.re` compiles a PEG pattern string: `compile`, `match`, `find`, `gsub`. Reach for it when the grammar reads better as text and every transform is a literal. - `santoku.re.core` is the vendored LPeg 1.1.0 engine: the constructors `P`, `S`, `R`, `B`, `V`, `utfR`, the capture family `C`, `Cc`, `Cp`, `Cs`, `Ct`, `Cg`, `Cb`, `Cf`, `Cmt`, `Carg`, and the operator algebra (`*` sequence, `+` ordered choice, `^n` repetition, `-` difference, unary `-` and `#` lookahead, `/` and `%` capture transforms) that grammars are built from. Reach for it when captures need Lua functions or rules are assembled from data. `require("lpeg")` does not reach the engine: the C module is registered as `santoku.re.core` so a project can depend on an external lpeg rock at the same time. Grammar construction in both notations is covered at https://santoku.dev/santoku-lpeg#santoku-lpeg--santoku-re-core >>> santoku-wasm --- name: santoku-wasm description: Make Lua or C behave correctly in a WebAssembly build of a santoku or toku project, or fix a spec that passes under toku test and fails under toku test --wasm. Use when a function is missing under wasm, when io.popen or another capability exists but raises when called, when a module needs a separate wasm implementation, when code must not be emitted into a wasm build at all, or when a rock can't build for wasm. Covers ifndef __wasm__, TK_WASM_WEB, the web and node Lua profiles, presence gates, invocation probes, .wasm. filename variants, build-time template gates and wasm = false. --- # Gating code for WebAssembly Four mechanisms make code differ under wasm. Picking the wrong one is the usual failure, and the choice follows from what is actually different about the build. | What is different | Mechanism | Form | | --- | --- | --- | | The capability is absent | gate on presence | `if fs.hardlink then ... end` | | It exists and always raises | probe once | `local ok = pcall(io.popen, "true")` | | A separate implementation exists | filename variant | `lib/santoku/web/js.wasm.lua` | | The text must not be emitted | template gate | `<% push(is_wasm) %> ... <% pop() %>` | A rock that can't build for wasm at all sets `wasm = false` in its descriptor's `env`, beside `name` and `version`. `toku build --wasm` and `toku test --wasm` then stop with ` is native-only`, and installing it into a wasm tree fails with the same message. Full treatment, with the code for each: https://santoku.dev/santoku-make#santoku-make--choosing-a-wasm-mechanism ## The toolchain and its two Lua profiles Wasm builds use clang with `--target=wasm32-wasip1` (wasi-sdk 34, fetched by toku, or a host clang 18+). Every wasm compile force-includes ``, which carries the JS interop macros `TK_JS`, `TK_JS_ASM` and `TK_EXPORT`. Makefiles branch on `_WASM`, set when `CC` contains `wasm32`. | Profile | Used for | Lua it gets | | --- | --- | --- | | node | `toku test --wasm` specs, `toku install --bundled --wasm` | the parser and every standard library; runs under the WASI of the node `toku setup --node` recorded (node 24.22.0, or a PATH node 24+ where nodejs.org has no build), which preopens the highest readable ancestor of the working directory. Without it the run stops with `wasm tests need the managed node; run: toku setup --node` | | web | client pages | bytecode only (no parser, so `loadstring` on source fails with `no parser`), no `io`, `os` or `debug`, no filesystem (`fopen` always fails with ENOENT), and error messages name no function (`bad argument #1 to '?'`) | ## Compiling a capability out clang defines `__wasm__` for every wasm build, and a browser build also gets `-DTK_WASM_WEB`. Guard the function body and its `luaL_Reg` entry together: an entry without a body fails to link, a body without an entry is dead code. lua-santoku-fs does this for `hardlink` and `symlink` in `lib/santoku/fs/posix.c`. When a module must keep the function and change what it does, guard inside the body and expose which build Lua got, the way `santoku.sqlite.db` sets a `wasm` field from the same ifdef. A web page links against a small libc that santoku-make ships, so a C module calling a libc function it lacks fails at the final link with `undefined symbol`. Filesystem calls are absent by design: keep modules that need them out of client pages. https://santoku.dev/santoku-make#santoku-make--compile-a-capability-out ## Gating a spec Register the test only when the capability is there, rather than skipping it inside the test: ```lua if fs.hardlink then test("hardlink", function () ... end) end ``` https://santoku.dev/santoku-make#santoku-make--gate-specs-on-a-capability ## When presence lies A presence check settles it only when the capability is genuinely missing. In the node profile `io.popen` exists and raises `'popen' not supported` when called, so `if io.popen then` reads as available and is wrong. Probe once, name the result, and gate on the name: ```lua local can_spawn = pcall(io.popen, "true") ``` The same trap applies to anything whose absence is behavioural rather than structural: a module compiled into a wasm bundle is not present on disk, so a `searchpath` lookup correctly returns nil and a test asserting otherwise is the thing that is wrong. https://santoku.dev/santoku-make#santoku-make--when-presence-checks-lie ## Filename variants `.wasm.` selects a wasm-specific source at build time, as in lua-santoku-web's `val.wasm.c`, `async.wasm.tk.lua` and its `*.wasm.lua` specs. This is variant selection; it does not help with a test that cannot run in this environment. https://santoku.dev/santoku-make#santoku-make--filename-variants ## Build and test - `toku test --wasm` builds into `build/-wasm/test/` and runs the suite there. - `test.wasm.bundle_ignores` in the descriptor lists modules the spec bundler skips under `--wasm`, beside the always-ignored `debug`. - `toku install --wasm` bundles to `build/-wasm/`. - Native and wasm variant flags live in the descriptor, on the santoku-make tab. - Green natively proves nothing about wasm. Run both. - Green under node proves nothing about a page. The web profile has no parser, no `io` and a small libc, and only a browser runs the page glue. - In a web project, cover each client page with a `*.browser.lua` spec, which drives Chromium through santoku-cdp. `toku test` skips that spec unless `TOKU_CHROMIUM` names a browser. With `CI` set, or a PATH that names the spec or its own directory, the spec runs and fails without one. - In a rock, name a spec that needs a DOM `*.browser.wasm.lua` and run `toku test --browser`. >>> santoku-web --- name: santoku-web description: Write browser-side Lua with santoku-web without tripping over the JavaScript boundary. Use when code touches santoku.web.js, santoku.web.val, val.lua, val.pack, val.unpack, santoku.web.async or :await(), santoku.async over the browser runtime (sleep, latest, debounce, atleast, retry), santoku.web.rpc, a Web Worker, MessagePort or MessageChannel, the santoku.web.sqlite worker or proxy, a JS callback such as a Promise executor or event listener, a timer, santoku.web.storage, or a santoku.web.app component (app.mount, app.define, app.router, and the handle c with c.commit, c.emit, c.root, c.scope, c.enter, c.hash_jump, c.on_stop), a latest and its santoku.web.dom targets. Covers what each side of the boundary receives, the this-first calling convention, await's two return values, how to start a task with spawn or task and where its errors go, and how arguments arrive in an rpc or sqlite worker handler. Also covers the component rules: the handle c that every handler gets after s, the attrs table that state gets, latest and the scope kill that aborts a component's requests, the shared santoku.web.http client, and { root, selector } targets, the connect and disconnect lifecycle, and the markup, focus, style, slot, state attribute, popover and modal dialog rules for a component template. --- # Browser interop with santoku-web Application code reaches the browser only through `santoku.web.js`, `santoku.web.val` and `santoku.web.dom`. It never writes JavaScript; the TK_JS shims live in the library's C core. Sources below are lua-santoku-web 10.0.0, cited by function. Navigation (`dom.go`), dialogs (`dom.alert`, `dom.confirm`), downloads (`dom.download`), the referrer and focus (`dom.read` kinds `referrer` and `focus`) and the clock (`async.now`) have dom and async primitives. Reach for `santoku.web.js` only for third-party libraries such as Chart.js. santoku-web's behaviour (APIs, and HTML that changes what an element does) uses only what is Baseline widely available. Status is read per API member or BCD key: `showPopover` is widely available though the popover feature as a whole isn't. The one exception is `Selection.getComposedRanges`, on the editor paths that read a selection inside a shadow root, where no widely available API reads it. Declarative CSS and HTML that a browser ignores when unsupported, such as `@property`, `@starting-style`, `transition-behavior`, `scrollbar-gutter` and `autocorrect`, is allowed as a hint. Write no feature detection, no polyfill and no fallback. An app may target fewer browsers than santoku-web does and states its floor in its own docs. Current status per key is on https://webstatus.dev. The spec `test/spec/santoku/web/baseline.tk.lua` fails on a denied name in the shipped JS, CSS and glue, from `test/res/baseline.json`. To refresh that list, run `toku lua test/res/gen-baseline.lua /data.json` in lua-santoku-web. It raises when a denied key or the exception has turned widely available. ## Two kinds of JS value | You hold | Comes from | Method calls | Read a field | | --- | --- | --- | --- | | object proxy | `js.Name`, results of calls on proxies, `val.lua(v)` | `obj:method(x)` | `obj.field` | | bare val | `val(x)`, `v:get(k)` | none: `v:get("m"):call(v, x)` | `v:get("field"):lua()` | - `val.lua(v)` turns a bare val into an object proxy, or into a Lua value for primitives (`val.wasm.c` `mtv_lua`, `object_to_lua`). - `val.unpack(v)` deep-copies plain objects and arrays into Lua tables in one call into JavaScript (`val.wasm.c` `mt_unpack`). null and undefined become nil. A Date, Map, Promise, Uint8Array, function or class instance arrives as a wrapper. A Lua value passes through. - A bare val has no method sugar, so `v:postMessage(x)` raises "attempt to call method 'postMessage' (a nil value)". When you see that error, the value needs `val.lua`. - Lua tables cross as live proxies by default. `val.pack(t)` sends a deep copy (`val.wasm.c` `mt_pack`). A nested JS value stays that JS value, and a Lua function becomes the proxy `val(fn)` gives. - `val.pack` raises on a thread, a userdata that isn't a JS value, or a key that isn't a string or a number. The message names the key path: "val.pack: can't encode a thread at .rows[2].owner". Nesting past 200 levels raises too. - santoku-web 5.0.0 removed the recursive argument. `val(x, true)`, `val.lua(v, true)` and `v:lua(true)` raise an error that names `val.pack` or `val.unpack`. - Arrays shift index at the boundary: JS index 0 is Lua element 1. https://santoku.dev/santoku-web#santoku-web--the-conversion-matrix https://santoku.dev/santoku-web#santoku-web--val-get-set-call-new https://santoku.dev/santoku-web#santoku-web--arrays-across-the-boundary ## The this-first convention It runs in both directions. - JS calling Lua: the Lua function receives `this` first. A Promise executor is `function (this, resolve, reject)`, an event listener is `function (_, ev)`, a `forEach` callback is `function (_, v)`. - Lua calling a bare JS function proxy: the first argument becomes `this`. Resolve a promise with `resolve(nil, value)`, as `async.wasm.tk.lua` `promise` does with `resolve(this, ...)`. `resolve(value)` resolves with nothing. - `obj:method(x)` supplies `obj` as `this` for you. Call timers on their owner: `js.window:setTimeout(fn, ms)`. A bare `setTimeout(fn, ms)` treats `fn` as `this`. https://santoku.dev/santoku-web#santoku-web--callbacks-and-the-this-first-convention ## Promises and async - `p:await()` returns two values, `ok` then the result: `local ok, v = p:await()`. `local v = p:await()` gets the boolean. - `santoku.web.async` is the browser runtime (`async.wasm.tk.lua`): `now`, `sleep`, `spawn`, `scope`, `run`, `kill`, `task` and `promise`. It isn't callable since 10.0.0. - `async.spawn(fn, ...)` starts `fn(...)` as a task and returns nothing. `async.task(fn, ...)` does the same and returns a promise of `fn`'s first value. Use `task` only where a caller needs a promise, such as a router `on_change` hook or JavaScript. - Both run `fn` to its first block before they return. - `:await()` and `sleep` work only inside a task. Outside one they raise "await called outside async context" or "sleep called outside async context" (`waiter`). - `:await()` raises "await: require santoku.web.async before awaiting a promise" until something has required `santoku.web.async` (`val.wasm.c`). - An error in a task rejects the promise `task` returned, before the first block or after one. Neither `spawn` nor `task` raises in the code that calls it. - A promise that the caller neither awaits nor catches is dropped. A dropped promise whose `fn` raised is an unhandled rejection. The page gets `unhandledrejection` with the error as `reason`, the santoku-cdp runner fails the run, and node exits non-zero. Call `:catch(function (_, e) ... end)` on the promise to handle the error. - An error in a spawned task, or in a task the library starts (an app action, `start`, `route`), reaches `unhandledrejection` too (`async.wasm.tk.lua` `spawn`, `internal.spawn`). The library adds no `unhandledrejection` listener. An app that shows such errors adds its own. - `err.pcall` and `err.xpcall` run `fn` in a `santoku.co` coroutine since santoku 5.0.0, so they can span an await or a sleep. A raw `pcall` can't. - `kill(s)` aborts each fetch the scope's tasks await, clears each sleep, and kills the child scopes. A killed task never resumes, and its `task` promise resolves with nil. - `async.promise(function (complete) ... end)` hands you one callback. `complete(true, v)` resolves, and `complete(false, e)` rejects. `js.Promise:resolve(v)` builds a resolved promise. https://santoku.dev/santoku-web#santoku-web--santoku-web-async https://santoku.dev/santoku-web#santoku-web--promise-helpers ## Timers and storage - santoku-web 10.0.0 removed `santoku.web.timer` and `santoku.web.latest`. Timers, debounce, atleast and latest come from `santoku.async` over this runtime. - An app keeps one module that builds it, `client/lib//async.lua`: `return require("santoku.async")(require("santoku.web.async"))`. Every other client module requires that module, as `local async = require("myapp.async")`. - A timer is `async.spawn(function () async.sleep(ms) fn() end)`. A cancellable timer is a latest that sleeps and then calls `fn`, stopped with `l.cancel()`. - `async.sleep(ms)` blocks the calling task and returns nothing. Don't call `:await()` on it. - `async.debounce(fn, ms)` returns a callable with `fn`'s signature. A call blocks for `ms`, and a newer call kills the waiting one, whose caller never resumes. Spawn the call when the caller mustn't wait: `async.spawn(d, ...)`. - `d.cancel()` kills the waiting call of a debounce or a throttle (santoku 5.1.0). Use it in place of a `latest(async.sleep)` gate. - `async.atleast(fn, ms)` returns `fn`'s values no sooner than `ms` after the call. Call it inside a task. - The wrappers compose: `async.latest(async.atleast(get, 125))`. - latest is under the component rules below. - `dom.painted()` waits in the calling task until the browser has painted every flush made before the call (`dom.wasm.tk.lua` `painted`, `res/web/dom.js` `__tk_dom_painted`). It flushes nothing and returns nothing. For a bare frame callback, call `js.window:requestAnimationFrame(fn)`. To yield to the task queue, call `async.sleep(0)`. - `local storage = require("santoku.web.storage")` (`storage.wasm.lua`). `storage.set(k, v)` stores a string, and a nil `v` removes the key. `storage.get(k)` returns the string, or nil. Both raise where the global has no localStorage. - `require("santoku.web.history").arrived()` returns true for a fresh visit, and false for a reload or a back-forward visit (`history.wasm.lua` `arrived`). https://santoku.dev/santoku#santoku--santoku-async https://santoku.dev/santoku-web#santoku-web--timers https://santoku.dev/santoku-web#santoku-web--santoku-web-storage ## rpc: the values on a port From santoku-web 11.0.0, `rpc.client(port)` returns a channel, and `rpc.serve(port, handlers)` answers it over the same persistent port. | Direction | Content | Source | | --- | --- | --- | | call, sent | the call id, the method name and the arguments as `santoku.pack` bytes in one transferred ArrayBuffer | `rpc.wasm.lua` `client`, `rpc/core.wasm.c` `tk_rpc_post` | | handler arguments, received | the same Lua values: nils in place, tables as tables, a `__pack` userdata rebuilt by its module | `rpc/core.wasm.c` `tk_rpc_read` | | handler returns, sent | the call id, `true` and the results as `santoku.pack` bytes | `rpc.wasm.lua` `reply` | | call result, received | `chan.call` returns `true` and the results, or `nil` and `"failed: ..."` or `"lost: ..."` | `rpc.wasm.lua` `client` | - Calls carry Lua values only. A JS value (a port, a Uint8Array, any val) raises at the call with "it takes Lua values only". Hand a port to a worker with `rpc.register_port`. - Call `chan.call` inside a task. It blocks that task until the reply or `chan.lose(detail)`. - A missing method returns `nil, "failed: rpc: no method named "`. A handler error returns `nil, "failed: "`. - `rpc.serve` runs each message as a task, one at a time per port, in call order, so a handler can call `async.sleep` or `:await()`. - A killed caller abandons its call, and the channel drops the reply. https://santoku.dev/santoku-web#santoku-web--santoku-web-rpc ## Workers and the sqlite proxy - The database lives in a dedicated worker, since OPFS SyncAccessHandles exist only there. `santoku.web.sqlite.worker(path, handler)` calls `handler(db)` and serves the table it returns over rpc, so the rules above apply to every function in it. The handler raises to fail. A handler that returns `true, handlers` fails the worker. - `santoku.web.sqlite.proxy(bundle_path, opts)` returns `core, ready`. Await `ready` before using `core`. - `core` is a `santoku.async.proxy`. Each `core.name(...)` call blocks its task, so call it inside a task. It returns `true` and the handler's values, or `nil` and `"status: detail"`. A handler error returns `nil, "failed: "`. - `err.checkok(core.name(...))` returns the values or raises the status. `local ok, r = core.name(...)` branches on `ok`. - The proxy stops the worker on pagehide. Every pending and later `core` call then returns `nil, "lost: the database worker stopped when the page was hidden"`. A back-forward cache restore starts a new worker and calls `opts.on_restart()` once it's ready. https://santoku.dev/santoku-web#santoku-web--santoku-web-sqlite https://santoku.dev/santoku-web#santoku-web--santoku-web-sqlite-proxy ## Components, commits and DOM targets Sources are `app.wasm.lua`, `dom.wasm.tk.lua` and `dom/buf.wasm.c`, cited by function. - The framework writes no field on a state table, and `s` holds plain data only. Every handler except `state` gets the component handle `c` after `s` (`attach`): | Field | Result | | --- | --- | | `c.commit()` | renders that one component and flushes | | `c.emit(name, detail)` | dispatches a component event at the next flush | | `c.root` | the root handle: a defined element's shadow root, or the root `app.mount` got | | `c.scope` | the router scope of a spec with `scope`, and nil otherwise | | `c.enter(undim)` | commits, waits for the paint, calls `undim()` and commits | | `c.hash_jump(ev)` | scrolls to the clicked hash link's target under `c.root` | | `c.on_stop(fn)` | registers a disconnect step, such as a `dom.listen` stop function | - Handlers: `start(s, c)`, `route(s, c, dir)`, `derive(s, c)`, `rewrite(s, c, k, ev)` and `actions[name](s, c, ev)`. `state(attrs, scope)` gets no `c`. `route` reads the new values with `c.scope.read()`. - `derive(s, c)` runs just before every template update, and `app.define` runs the update after it. `render(s, c, update)` is gone and raises. - A spec's router scope is one field: a list of plain query names, with `name` as its only named field: `scope = { "t", "q", "p", "o", name = "matcher" }`. `name` shares one scope by name. A top-level `keys`, `drop`, `empty` or `shared`, a key that isn't a plain string, `drop`, `empty` or `default` in the scope, or a string `scope` raises. - The router has no aliases, defaults, empty lists or dropped keys. Apply a default where the component reads the value: `c.scope.read().t or "deal"`. Leave a key such as a result offset out of the table a search writes. - A state field named `commit`, `root`, `scope` or `emit` belongs to the app. Keep no function, handle or request on `s`. App handles such as a latest go on `c`. - The render after an action, a `route` and `start` is the same per-component commit. - Run work that no action starts, such as a startup load or a timer, in `async.spawn(function () ... c.commit() end)`, with `c` from `start`. End a task that queues dom writes and never commits with `dom.flush()`. - A `dom.listen` callback runs in a spawned task, so it can block. Call `ev:preventDefault()`, `ev:stopPropagation()` and other synchronous work before the first block, since after it they have no effect (`dom.listen`). - An error in an action, `start` or `route` reaches the page as `unhandledrejection`, and the commit after it doesn't run. - A component that shows another component's state doesn't render when that state changes. The code that changes the state calls the reader's `c.commit()`. - Or both components share a scope with `scope.name`. Then each `route` runs on a followed link and on Back and Forward. `scope.push` from one sharer doesn't call the other sharers' `route`. - A commit after the element left the page renders nothing, and an emit sends nothing. - `c.emit(name, detail)` queues a `CustomEvent` that bubbles and is composed, sent from the component's root at the next flush (`attach`, `res/web/dom.js` op `0x29`). - `name` has no colon, such as `job-title`. A colon raises "c.emit: name must not contain a colon", because `data-action` splits at it. - `detail` is nil or any value `cjson.encode` takes. A listener outside reads the host as `ev.target`. - Listen from page JavaScript with `document.addEventListener(name, fn)`, from another component with `dom.listen("document", name, fn)` and `val.unpack(ev.detail)`, or from a parent with `events = { name }`, `data-action="NAME:action"` on the child's tag and `val.unpack(ev.event.detail)`. - An emit in an action adds no crossing: it rides the commit's flush. - To load more as the user scrolls, put `data-action="visible:more"` on a sentinel and list `{ "visible", margin = "200px" }` in `events`. Don't build an IntersectionObserver through js. - For hover effects on nested elements, put `data-action="enter:in leave:out"` on each element and list `{ "enter", pointer = true }, "leave"` in `events`. Don't walk `relatedTarget` through `ev.event`. - `spec.states = { "stale" }` shows state fields as boolean host attributes named `state-` (`define`, since santoku-web 12.0.0). - Each commit reads `s[name]`. A truthy field sets the attribute to "", and a false or nil field removes it. `s.no_results` is the attribute `state-no_results`. - Component CSS selects `:host([state-stale])`, and page CSS selects `job-list[state-stale]`. Don't use `:state()` or `attachInternals`. - The `state-` prefix keeps a state off author attributes: a `stale` attribute on the tag stays the author's, and `attrs` never holds a declared `state-` attribute. - A non-string entry raises "app.define: a states entry must be a string". A name outside lowercase letters, digits, `_` and `-` raises "app.define: a states entry must be lowercase letters, digits, _ and -". - `app.define(spec)` registers one element. `spec.template` is one entry of the table `loader.templates` builds. `app.define` raises "app.define: spec.template must be a template" with the tag when the entry is missing or names no compiled template. - `app.router(opts)` sets the router's `mode` and `scroll` once, before the first keyed component connects. Without it they're `query` and true. The history always batches, and `batch` raises. A second call raises "app.router: called twice", and a call after the router starts raises "app.router: the router already runs". - `spec.state(attrs, scope)` gets a plain table of the element's attributes (`define`, `internal.attrs`). - Each name loses a leading `data-`, and each `-` turns to `_`: `data-list-style` reads as `attrs.list_style`. - An empty attribute (`sales=""`) and a naked one (`compact`) both read as `""`, and an absent one reads as nil. Test presence with `attrs.compact ~= nil`. - `data-x` wins over `x`. - At connect, before `spec.state`, `app.define` seeds the scope: an attribute named for one of the spec's keys wins over the URL, and the URL fills the rest. It writes the canonical URL with one replace and runs no `route`, so `scope.read()` in `state` returns the seeded values. An empty or naked attribute seeds nothing. - Each sharer of a named scope seeds its own keys at its connect and keeps the other sharers' values. The last connect wins a shared key. - The attributes ride the connect event, so `state` reads them with no crossing. - Don't call `el:getAttribute` in `state`. To read attributes later, use the read op `dom.read({ "attrs", target })`. - `attrs` holds the attributes at connect. A `setAttribute` after that reaches no hook, so set every attribute before the element enters the page. - Every value is a string. Convert a number with `tonumber(attrs.limit)`. - Write a boolean attribute naked, ``. `compact="false"` is still present, so `attrs.compact ~= nil` is true for it. - Don't give a component an attribute of its own with a global attribute's name, such as `title`, `hidden`, `lang`, `dir`, `class`, `id`, `style`, `slot`, `part` or `tabindex`. The browser acts on those names. Use a `data-` name: `data-title` reads as `attrs.title`. - Every component renders into an open shadow root, and `c.root` is its handle (`res/web/define.js` `rootOf`). Page code and a browser test reach the root as `el.shadowRoot`. Code in the component uses `c.root`. - A spec takes `sheets`, a list of constructed stylesheets such as `app.stylesheet(css)` returns (`stylesheet`, `res/web/define.js` `define`). `app.page` as the first entry of `sheets` clones the page's stylesheet link and style elements into the start of the root on each connect. `app.define` raises when `app.page` comes later, and on the removed `page_sheets` field. - The `