Skip to content

The prelude ​

From the spec

This page is spec/std.md, the specification the compiler and the backends are written from. It is rebuilt from the spec with every deploy (how).

The prelude is the language's types and their methods; every free function is imported. In scope everywhere without an import: the types (number, string, boolean, lists, tuples, records, Map, Set, Task, Bytes, Range, json, Error, Parts, Async) with their methods and their own functions (Map(…), Set(…), Error(…), Bytes.of(…), String.fromCodePoint(…), Task.all(…)); and, in components, the host's values the schema types (lib, env, dialogs), the framework's declarations (page, dialog, permissions, shortcut, gesture) and, in apps, routes. Everything else comes from a standard-library module, named by purpose:

modulewhatwas
std/mathPI, E, NaN, Infinity, abs, floor, sqrt, min, max, clamp, … (below); parseNumber(s): number ! ParseError, parseInt(s, radix?): number ! ParseErrorMath.*, Number(s), parseInt, parseFloat (which gave NaN)
std/randomrandom(): number, uuid(): string (effectful)Math.random, uuid
std/jsonparse(s): json ! SyntaxError, stringify(v, indent?)json.parse, json.stringify
std/loglog(...), warn(...), error(...) (effectful)console.*
std/formatnumber, plural, date, time, timeAgo, duration, count, join, first, last, percent, round, capitalize, keys (Formatting, below)ambient helpers
std/timenow(), sleep(ms), timers (setTimeout, setInterval, clearTimeout, clearInterval, client only), and its own types (time.md)now, sleep, timers
std/reactivedebounce, throttleambient
std/reflectfields<T: data>()ambient
std/motionslide, fade, scale, glide, … (motion.md)import … from "motion"
std/regexregex"…", compile, find, replaceAll, … (regex.md), Weft over a linear-time matcher—
std/cryptohashes, HMAC, timingSafeEqual, randomBytes, uuidv7, signatures, jwt (crypto.md)—
std/urlparse, build, query, encodeComponent, … (url.md)—
std/testingassert, assertEq, assertPanics, mount, queryTree, queryCall (tests only)ambient test names, assertThrows

Signatures are Weft. A function-typed parameter runs during the call unless it is marked escaping. "Effectful" names can't be used by pure units (derived values, provide, markup expressions). I/O lives in the client host's lib and, on the server, in std/http, std/db, std/s3, std/live, std/process, std/fs, std/net, std/sandbox, std/auth and std/app (std/*.md). A name used without its import is an error with a fix-it adding the import.

Errors and panics (language.md, Errors): a function here that can fail for a reason the caller should handle says so in its type (! ParseError); a misuse that is a bug (a RangeError below: a position out of range for a write, toFixed(25), a step of 0) is a panic.

Positions (i, start, end, from) are numbers converted as ECMA-262's ToIntegerOrInfinity (truncated, NaN → 0), then clamped as JS clamps them. A method panics only where JS throws, and where this page says so; a panic here is named RangeError unless it says otherwise. Strings and lists are bounded (language.md, Limits): a result past the bound panics.

Callbacks run during the call are error-polymorphic (language.md, Errors): such a method takes the callback's error type E (xs.map<U, E>(f: (x: T, i: number) => U ! E): U[] ! E), inferred from the argument: never for a callback that can't fail, so the call can't either. A failing callback ends the method at once and the call fails with its error; a mutating method (sort) leaves its receiver as it was. Escaping callbacks (timers, handlers, then) can't fail.

Error types ​

In the prelude, the errors of the language's own operations:

Error{ name: string, message: string, data: json }, the general error type: Error(message: string), Error(e: { name?: string, message: string, data?: json }) (name defaults to "Error" when missing or null, data to null)
CastError { path: string, expected: string }what a checking x as T fails with: the failed value's path, rooted at value (value.people[1].age), and the type expected there
HostError { name: string, message: string }what a lib call fails with, unless its schema entry lists its own errors (schema.md)
Panic = { name: string, message: string }what @try's @catch e binds (language.md, Panics); not an error: nothing fails with it

Every other error type is its module's: a variant type (one variant named like its type when it has one, { kind: "SyntaxError", … } in json and on the wire), exported and imported by name to be written or matched (import type { SyntaxError } from "std/json"). A value of one flows without the import (inferred). They are std/math's ParseError, std/json's SyntaxError, std/time's TimeError (below) and the I/O modules' (std/http's NetworkError and StoreError, std/db's DbError, std/s3's S3Error, std/auth's AuthError and MailError, std/auth/client's PasskeyError, std/sandbox's TreeError and RunError).

Numbers ​

n.toString(radix: number = 10): stringradix 10: Number::toString (shortest round-trip, exponent form from 1e21); 2–36: the integer part only, in that radix; otherwise a panic
n.toFixed(digits: number = 0): string0–20, ECMA-262 rounding (ties to the larger magnitude of the exact decimal value); otherwise a panic
n.toPrecision(precision?: number): string1–100 significant digits, ECMA-262 (exponent form when the exponent is below -6 or not below the precision; ties as toFixed); without one, as toString; otherwise a panic
n.toExponential(digits?: number): stringone digit, 0–100 more after the point, then e±n (ECMA-262); without digits, as many as the value needs; otherwise a panic. A non-finite n gives its toString in both
n.round() floor() ceil() trunc() abs() sign(): numberas std/math's
n.isNaN() isFinite() isInteger(): boolean
a..b, a..=b (Range)r.start, r.end, r.inclusive, r.length, r.includes(n) (tests the interval: start ≤ n < end, or ≤ end when inclusive; (0..3).includes(1.5) is true), r.toList(): number[], r.step(k): number[] (k ≠ 0, else a panic); for i of r counts up by 1

A range's ends are any numbers. for i of a..b yields a, a + 1, … while i < b (i <= b for a..=b): 0..2.5 yields 0, 1, 2; 5..0 yields nothing; a NaN end yields nothing; 0..Infinity runs until something stops it. r.step(k) yields a + i * k for i = 0, 1, … (computed from a each time, so error doesn't accumulate) while before the end in k's direction ((5..=0).step(-1) is [5, 4, 3, 2, 1, 0]); k of 0 or NaN panics. r.length is the count for would yield (Infinity for an endless range); r.toList() on one panics. Parsing numbers and Math's functions are std/math's (below).

Strings ​

s.lengthcode units
s.at(i): string?one code unit; negative from the end
s.charAt(i): stringone code unit, "" outside
s.codeUnitAt(i): number?, s.codePointAt(i): number?null outside, negative positions included
s.slice(start = 0, end?: number): string
s.includes(t, from = 0), s.startsWith(t, at = 0), s.endsWith(t, end?): boolean
s.indexOf(t, from = 0), s.lastIndexOf(t, from?): number-1 when absent
s.toUpperCase() toLowerCase() trim() trimStart() trimEnd(): stringUnicode default case mapping, no locale; JS's whitespace set
s.padStart(n, fill = " "), s.padEnd(n, fill = " "): string
s.repeat(n): stringnegative or infinite: a panic
s.split(sep: string, limit?: number): string[]"" splits into code units
s.replace(a: string, b: string), s.replaceAll(a, b): stringb inserted literally (no $ patterns)
s.normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD" = "NFC"): stringUnicode normalization; lone surrogates stay as they are
s.localeCompare(t): number-1, 0 or 1 in one order for every language: by the letters with accents and case taken off (NFD, combining marks removed, lowercased), then with the accents, then lowercase before uppercase, each by UTF-16 code units; canonically equivalent strings are 0 ("é" and "e\u0301"). Not a locale's collation: std/intl will add collators by locale (Swedish ä after z, German phone-book order)
String.fromCharCode(...units: number[]), String.fromCodePoint(...points): stringan invalid code point: a panic

for c of s iterates code points. Regular expressions are std/regex's (std/regex.md: regex"\d+", a linear-time dialect); migrate reports each JS use.

Lists ​

non-mutating
xs.length
xs.at(i): T?negative from the end
xs.first(): T?, xs.last(): T?, xs.isEmpty(): boolean
xs.slice(start = 0, end?), xs.concat(...more: T[][]), xs.toReversed(): T[]
xs.toSorted<E>(cmp?: (a: T, b: T) => number ! E): T[] ! Estable; without cmp only for number[] (numeric, NaN last) and string[] (code units); otherwise error. Every sort is a top-down merge sort, so the comparator's calls (and the fuel they spend) are the same on every backend
xs.with(i, x: T): T[]outside 0 … length - 1: a panic
xs.includes(x): booleanSameValueZero at the top level (finds NaN; items inside records and lists compare with ==)
xs.indexOf(x, from = 0), xs.lastIndexOf(x, from?): number== (never finds NaN); -1 when absent
xs.join(sep = ","): stringitems shown as templates show them (null as nothing); items that can't be shown are an error
xs.map<U, E>(f: (x: T, i: number) => U ! E): U[] ! E, xs.flatMap<U, E>(f: (x: T, i: number) => U[] ! E): U[] ! E
xs.filter<E>(f: (x: T, i: number) => boolean ! E): T[] ! E
xs.find(f): T? ! E, xs.findLast(f): T? ! E, xs.findIndex(f), xs.findLastIndex(f): number ! Ef as filter's
xs.some(f), xs.every(f): boolean ! E; xs.count(f): number ! Ef as filter's
xs.reduce<U, E>(f: (acc: U, x: T, i: number) => U ! E, init: U): U ! Ethe seed is required
xs.forEach<E>(f: (x: T, i: number) => void ! E): void ! E
xs.entries(): [number, T][], xs.flat() (on T[][]: T[])
xs.sum(): number, xs.min(): number?, xs.max(): number?on number[]
mutating (the receiver is a place, borrowed mutably)
xs.push(...items: T[]): number, xs.unshift(...items): numberthe new length
xs.pop(): T?, xs.shift(): T?
xs.insert(i, x: T)0 ≤ i ≤ length, else a panic
xs.remove(i): T0 ≤ i < length, else a panic
xs.splice(start, count?: number, ...items: T[]): T[]the removed items
xs.sort<E>(cmp?: (a: T, b: T) => number ! E): void ! E, xs.reverse(), xs.fill(x, start = 0, end?), xs.swap(i, j), xs.clear()swap outside the list: a panic

A comparator that fails leaves the list as it was. A callback that writes the list it was called on: a non-mutating method works on a copy taken before the call (xs.forEach(x => { xs.push(x) }) visits the old items); a mutating one (sort) is an error (exclusivity, language.md).

Maps and sets ​

Map<K, V>
Map<K, V>(), Map(entries: [K, V][])construction; K and V are inferred from entries or the expected type
m.size, m.has(k): boolean, m.get(k): V?
m[k]reading an absent key: a panic; as a place, writing adds the key
m.keys(): K[], m.values(): V[], m.entries(): [K, V][], m.forEach<E>(f: (v: V, k: K) => void ! E): void ! Einsertion order
m.set(k, v), m.delete(k): boolean, m.clear()mutating
Map.groupBy<T, K>(xs: T[], f: (x: T, i: number) => K): Map<K, T[]>the items by f's key, keys in the order they first appear
Set<T>
Set<T>(), Set(items: T[])construction; T is inferred from items or the expected type
s.size, s.has(x): boolean, s.values(): T[]
s.union(t), s.intersection(t), s.difference(t), s.symmetricDifference(t): Set<T>in s's order, then t's
s.isSubsetOf(t), s.isSupersetOf(t), s.isDisjointFrom(t): booleanES2025's
s.add(x), s.delete(x): boolean, s.clear()mutating

Keys and items are primitive (language.md, Types), compared as SameValueZero.

Bytes ​

  • Bytes is immutable data: b.length, b.at(i): number? (0–255, negative from the end), b[i] (a panic outside), slices b[a..b] (as lists slice), b.concat(…), b == c by content. A Bytes costs 16 plus its length in memory.
  • Made by Bytes.of(list: number[]) (each an integer 0–255, else a panic), Bytes.fromUtf8(s: string): Bytes, Bytes.fromBase64(s: string): Bytes ! ParseError (the standard alphabet, with or without padding, no whitespace) and Bytes.fromHex(s: string): Bytes ! ParseError (either case); malformed text fails with std/math's ParseError { input }.
  • Read back by b.toUtf8(): string (malformed sequences become U+FFFD), b.toBase64(): string (RFC 4648, padded), b.toHex(): string (lowercase), b.toList(): number[].
  • In json and std/json's stringify a Bytes is its base64 text; j as Bytes decodes base64 text (a CastError otherwise). Across the network it travels as bytes. It can't be a map key. b[i] reads only (a Bytes never changes); iterate one with for x of b.toList().

Tagged strings ​

  • Parts = { strings: string[] }: a tagged string's literal pieces, with escapes applied (a tag whose compile-time check says so gets them as written: regex"…"); strings.length is the number of values plus one. The same Parts value is passed on every evaluation of one literal, so a tag can cache what it derives from it.

Tasks ​

  • Task.all<T, E>(ts: Task<T ! E>[]): Task<T[] ! E> fails with the first failure (the others' errors count as observed); Task.race<T, E>(ts: Task<T ! E>[]): Task<T ! E> settles as the first to settle; Task.of<T>(v: T): Task<T>.
  • Task.allSettled<T, E>(ts: Task<T ! E>[]): Task<({ kind: "ok", value: T } | { kind: "failed", error: E })[]> waits for every task and gives each one's end, in the tasks' order. Task.any<T, E>(ts: Task<T ! E>[]): Task<T ! E[]> settles as the first to succeed; when every one fails it fails with their errors, in the tasks' order (an empty list fails with []). Task.timeout<T, E>(t: Task<T ! E>, ms: number): Task<T ! E | TimeoutError> (effectful) settles as t does, or fails with std/time's TimeoutError { ms } once ms have passed first; nothing cancels t, which goes on and whose end is dropped. A panic in any task is the combined task's, as in Task.all.
  • Awaiting a fallible task is the fallible operation (try await t); calling an async function that can fail is not. A task's error that nothing observes is reported when the queue drains (not a panic); a cancelled task's error is dropped.
  • Async<T, E> is an async derived value, { pending: boolean, value: T?, error: E? }; Async<T> is Async<T, never> (language.md, Reactivity).

Routes ​

  • Route.path(s: string): Route is a route into a user tree (/u/anna/x) and Route.url(s: string): Route one to another site (https://…), unchecked by necessity (app.md, Links).

Modules ​

std/math ​

  • PI, E, NaN, Infinity; abs ceil floor round trunc sign sqrt cbrt pow exp expm1 log log1p log2 log10 sin cos tan asin acos atan atan2 sinh cosh tanh hypot min(...xs) max(...xs) clamp(x, lo, hi), as JS's Math (round rounds half up; min() is Infinity). + - * / (the operators) and sqrt are exact (IEEE 754) on every backend; the transcendental functions (pow, exp, log, the trigonometric ones, hypot, …) may differ in the last ulp between backends, as JS allows.
  • parseNumber(s: string): number ! ParseError: StringToNumber (expressions.md, ToNumber: surrounding whitespace, Infinity, 0x/0o/0b prefixes); empty or blank text, or a NaN result, fails.
  • parseInt(s: string, radix?: number): number ! ParseError: as JS (leading whitespace and a sign; a 0x/0X prefix skipped with radix 16 or none, where it makes the radix 16, else 10), up to the first character that isn't a digit of the radix; fails when no digit parses. A radix outside 2–36 panics.
  • ParseError = ParseError { input: string }: the text that didn't parse.

std/random ​

  • random(): number (in [0, 1)) and uuid(): string (a random version 4 UUID); effectful.

std/json ​

  • parse(s: string): json ! SyntaxError: RFC 8259. SyntaxError = SyntaxError { message: string, at: number }: at the code-unit offset where the text stopped being JSON (malformed text, or nesting deeper than 10,000).
  • stringify(v: data, indent?: number): string. A record's fields in its type's order (null fields included); lists; Map<string, V> as an object, other maps as a list of [key, value] pairs; sets as lists; non-finite numbers as null; strings with lone surrogates escaped as \uXXXX; nesting deeper than 10,000 panics. A type parameter isn't known to be data: error.
  • Conversion of a data value to json (implicit) follows the same rules.
  • j.keys(): string[], j.values(): json[], j.entries(): [string, json][]: a json object's keys, values and [key, value] pairs, in its order; on anything but an object, a TypeError panic. They are json's own (methods of every json, not std/json's): a list or a string isn't a receiver for them.
  • for x of j iterates a json list's items, or a json object's [key, value] pairs (as json: for [k, v] of j; j.entries() types the key as string); anything else is a TypeError panic.
  • j as Map<K, V> takes a json object (string keys) or a list of [key, value] pairs, each key and value checked as K and V (what Map<string, V> and other maps become in json, read back); j as Set<T> a list. A key or value that doesn't check fails with a CastError (try j as Map<string, number>). is takes only maps and sets.

std/log ​

  • log(...xs), warn(...xs), error(...xs) (effectful): one line, the arguments separated by spaces; strings as they are, numbers, booleans and null as templates show them, other data as stringify, functions as [function], handles as [handle kind]. Where the lines go is the host's (std/process.md). A lone surrogate in a line becomes U+FFFD on every backend (a string's own code units are kept; only the line written is changed).

std/format ​

The helpers number plural date time timeAgo duration count join first last percent round capitalize keys keep their semantics from expressions.md (Helpers, Formatting). The schema (schema/standard.json) gives their parameters' names and count and types each result (returns); every parameter is any (data), so a wrong count or a function argument is a compile error and any other value is coerced as expressions.md says. They are pure and can't fail.

std/time ​

Instants, durations, dates and time zones (std/time.md, written in Weft), and the clock and timers:

  • now(): Instant (effectful; now().epochMs is ms since the epoch; markup reads env.now).
  • sleep(ms: number): Task<void>.
  • Timers, on the client only, cancelled when their instance unmounts:
    • setTimeout(f: escaping () => void, ms: number = 0): number and setInterval(f, ms) return an id; clearTimeout(id), clearInterval(id) (an unknown id does nothing);
    • each callback is a turn; timers fire in order of due time, then creation; a delay below 0 is 0, and a 0 ms timer runs after the current flush; an interval's first run waits its period as each next one does, and a period below 1 ms is 1 ms;
    • test hosts drive a fake clock (conformance/lang/README.md).

std/reactive ​

  • debounce<T>(x: T, ms: number): T and throttle<T>(x: T, ms: number): T are derived values that start as x: debounce takes x's latest value once it hasn't changed for ms; throttle takes a change at once (leading), then at most once every ms, ending on the latest value (trailing). Delays are normalised as timers' are; each call site has its own timer per instance, cancelled on unmount. Usable only in derived initialisers and markup expressions, where they keep their own timer per instance.

std/reflect ​

  • fields<T: data>(): Field[], with Field = { name: string, type: string, optional: boolean, attributes: { name: string, args: json[] }[] }: a record type's fields in order, with their attributes (language.md, Attributes). type is the field's type as the formatter writes it (aliases kept by name; T? for optional fields). A name argument is { "$ref": "<module id>.<name>" }. T must be a record type (error otherwise).

std/motion ​

  • slide, fade, scale, glide, …: transitions and motion values (motion.md).

std/testing ​

Test-only (language.md, Tests): importing it outside weft test is an error.

  • assert(cond: boolean, message?: string), assertEq(actual, expected) (structural, with a diff): a failed one is a panic named AssertionError, which fails the test.
  • assertPanics(f: () => void, name?: string): f must panic (with a panic named name, when given); otherwise an AssertionError.
  • A test's body may propagate (try, fail): a test whose body fails reports the error and fails.
  • mount(Component, props): Handle<"mounted"> (the props checked as a tag's), on the deterministic test host. Each method performs its action as one turn, then drains every ready turn and flushes before it returns; an unknown test id, or no pending call, panics (TestError):
    • view.text(): string, view.click(id), view.type(id, text), view.advance(ms), view.pending(): string[], view.unmount() (language.md, Tests);
    • view.resolveTask(call, value: json); view.rejectTask(call, message) fails the oldest pending call named call with HostError { name: "Error", message } (a lib call) or NetworkError { message } (a server function).
  • queryTree<T>(q: Query<(row: T) => json>): json and queryCall<T>(q, row: T): json: a query closure's tree, and calling it (hir.md, Query trees).

Weft is in development. The reference is the spec as it stands today.