Skip to content
Playground(another site)

Type system

TypeValuesEmits
Intinteger literals (0, -42); a JS safe integer, ±(2^53 − 1)number
Floatfloat literals (1.5, 0.0, -3.14)number
Stringstring literals ("…")string
Booltrue, falseboolean
Durationunit literals (5.minutes, 30.seconds)number (millis)
Instantno literal — Clock.now() / Instant.fromEpochMillis(n) / Instant.fromIso(s)number (epoch millis)
Decimaldecimal literals (1.20d, 5d){ coefficient: bigint, scale: number }
Bytesno literal — Bytes.fromUtf8(s) / Bytes.fromBase64(s) / Bytes.fromHex(s) / Bytes.fromBase64Url(s) / Bytes.empty()Uint8Array

The unit type is written (). Int and Float are distinct and incompatible — there is no implicit coercion (bynk.types.no_numeric_coercion). Convert explicitly: i.toFloat() (Int → Float, total) or f.round() / f.floor() / f.ceil() / f.truncate() (Float → Int, a runtime fault when the result is not a safe integer); parse a string with Int.parse(s) / Float.parse(s), each returning Option and accepting a strict full-string decimal only (" 7 ", "0x10" and, for Int, "1e3" are None). An Int is a JS safe integer at every entry point: a larger literal, a wire value, a parse result or a conversion is rejected, and Int division by zero faults.

A String has no direct character access; its operations are methods. Lengths and indices count UTF-16 code units, except chars, which splits by code point, and the two percent-encoding methods, which work on the UTF-8 bytes.

MethodReturns
s.length()Intthe code-unit count
s.concat(t: String)Strings, then t (the same as "\(s)\(t)")
s.trim()Stringwithout leading and trailing whitespace
s.toUpper()Stringupper-cased (locale-independent)
s.toLower()Stringlower-cased (locale-independent)
s.contains(sub: String)Boolsub occurs somewhere in s
s.startsWith(sub: String)Bools begins with sub
s.endsWith(sub: String)Bools ends with sub
s.indexOf(sub: String)Option[Int]where sub first occurs; None when it does not, never -1
s.slice(start: Int, end: Int)Stringthe code units from start up to end; a negative index is 0, with no wrap-around
s.replace(from: String, to: String)Stringevery occurrence of from replaced by to, inserted literally (no $1 or $&)
s.split(sep: String)List[String]the pieces between each sep
s.chars()List[String]one string per code point, so an astral character is one element
s.percentEncode()StringRFC 3986 percent-encoding of the UTF-8 bytes: every byte outside A–Z a–z 0–9 - . _ ~ becomes %XX
s.percentDecode()Option[String]reverses percentEncode; None for a % not followed by two hex digits, or bytes that are not UTF-8. + stays +
s.matchesRegex(pattern)Boolthe whole string matches; see Regular expressions
s.containsRegex(pattern)Boola match occurs anywhere
s.findRegex(pattern)Option[List[Option[String]]]the first match and its groups
s.findAllRegex(pattern)List[List[Option[String]]]every match and its groups
s.replaceRegex(pattern, with: String)Stringevery match replaced; with reads $1, $<name>, $& and $$
s.splitRegex(pattern)List[String]the pieces between each match

Int.parse(s) and Float.parse(s) turn a string into a number (see above), and toString() on Int, Float, Decimal, Duration and Instant goes the other way. More string functions are in the bynk.string commons, and URLs and query strings in bynk.url, written over percentEncode and percentDecode (see Related first-party modules). A method not in this table is bynk.types.method_not_found.

Decimal is an exact base-10 number: an arbitrary-precision integer coefficient and a non-negative scale, the value being coefficient / 10^scale. It is the type for money and any other fractional quantity that must not drift (0.1 + 0.2 is exactly 0.3). It does not emit to a number: a Decimal is a frozen { coefficient: bigint, scale: number } object, and the generated code handles it through the runtime’s decimal module.

A literal is digits with an optional fraction and a trailing d: 1.20d, 5d, 0.005d, 1_000.50d. The scale is the number of fraction digits as written, so 1.20d has scale 2 and 1.2d scale 1. There is no exponent form, and no Float or Int literal is ever a Decimal.

commons guide.decimal
fn total(unit: Decimal, qty: Int) -> Decimal {
unit * Decimal.fromInt(qty)
}
fn halves(d: Decimal) -> Bool {
d + d == d * 2d
}
  • +, -, * and unary - are exact. A sum or difference has the larger scale; a product has the sum of the scales. 1.10d + 2.20d == 3.30d.
  • ==, !=, <, <=, >, >= compare by numeric value, so 1.20d == 1.2d. scale() still tells them apart. A Decimal is Ord and Key (a Map key or Set member holds 1.20d and 1.2d as one key). A Decimal prints in a string hole as its canonical text ("total: \(price)").
  • Aggregations. sum(key) takes a Decimal key, on a List and on a Query (a stored Map’s), and is exact: it returns a Decimal (0d when empty), never a float. min, max and sortBy take one too, as Decimal is Ord. average(key) does not (bynk.query.sum_needs_numeric): a mean is a division, and a Decimal division needs a scale and a rounding mode that average has no place for. Sum the key, then divide by the count as a Decimal: total.div(Decimal.fromInt(n), 2, RoundingMode.HalfEven).
  • / is not defined. A quotient has no exact decimal answer, so division states its scale and rounding mode: a.div(b, 2, RoundingMode.HalfEven) (bynk.types.decimal_division_unscaled). A zero divisor faults, as Int division does. Every Decimal has a scale of 0 to 100 and canonical text of at most 1000 characters; an operation whose result would exceed either (* summing scales, round/div asked for a larger scale, a long product) faults at the operation, so a value never exists that the wire could not read back. A literal over the limits is bynk.lex.decimal_literal_too_large.
  • d.round(scale, mode) returns the value at exactly scale fraction digits: a larger scale pads with zeros, a smaller one rounds by mode.
  • A Decimal never mixes with Int or Float (bynk.types.no_numeric_coercion). Convert with Decimal.fromInt(n), d.toInt() (Some only for a whole number in the safe-Int range) and d.toFloat() (lossy, by design).
Statics
Decimal.parse(s: String) -> Option[Decimal]plain decimal text only ("1.20", "-0.5", "7"): no exponent, no leading +, no .5 or 5., no whitespace, at most 1000 characters and 100 fraction digits
Decimal.fromInt(n: Int) -> Decimalexact, at scale 0
Methods
scale() -> Intthe number of fraction digits
toString() -> Stringthe canonical text, with the scale kept: 1.20d is "1.20"
round(scale: Int, mode: RoundingMode) -> Decimal
div(other: Decimal, scale: Int, mode: RoundingMode) -> Decimal
abs(), min(other), max(other)
toInt() -> Option[Int], toFloat() -> Float

Rounding modes are written RoundingMode.<mode> and are read where the rounding happens: a mode is not a first-class value, so it cannot be bound to a name or passed as an argument (bynk.types.rounding_mode_position).

ModeRounds2.5-2.52.4
Downtoward zero2-22
Upaway from zero3-33
Floortoward negative infinity2-32
Ceilingtoward positive infinity3-23
HalfUpto nearest; a tie away from zero3-32
HalfDownto nearest; a tie toward zero2-22
HalfEvento nearest; a tie to the even neighbour2-22

Refinements. Positive, NonNegative and InRange(lo, hi) apply, with Decimal literals as the bounds (Decimal where InRange(0.00d, 1.00d)); a bound of another numeric type is bynk.types.no_numeric_coercion. A bare Decimal has no zero value, so a Decimal field of an agent’s state needs an initialiser.

On the wire a Decimal is a JSON string ("1.20"), never a number: a number invites every client to parse it as a float. Decoding is strict (the rules of Decimal.parse, and in addition no leading zero: "007" is refused on the wire, though Decimal.parse("007") is Some(7)), and the scale survives the round trip. A string that is malformed, or a JSON number, is a StructuralMismatch at the field’s path; a well-formed string that fails the type’s refinement is a RefinementViolation. The encoding is part of a persisted agent’s stored state, so it is frozen. See Wire format.

Pairing a Decimal with an ISO 4217 currency is not part of the type; a bynk.money commons that does so is a planned follow-on. See Handle money correctly.

Duration (v0.86) is a span of time, erased to a number of milliseconds. A Duration literal is <int>.<unit> over a closed unit set — 5.minutes, 30.seconds, 1.hour, 2.days, 100.milliseconds. The unit agrees with its number: the singular unit with 1 (1.hour, 1.second) and the plural unit with every other number, 0 included (0.seconds). 1.hours and 5.hour are bynk.duration.unit_agreement, with a fix; any other word after an integer literal (5.hr, 1.week) is bynk.duration.unknown_unit. A negative duration is the negation of a literal (-1.hour). The operator surface is Duration ± Duration, Duration * Int / Int * Duration (scalar scaling), and Duration comparison (subtraction is unclamped — may go negative). Convert explicitly: d.toMillis() -> Int and the static Duration.millis(n: Int) -> Duration. It round-trips through the JSON codec as an integer. See Operators.

Instant (v0.90) is an absolute point in time, erased to a number of Unix epoch milliseconds. It has no literal: an Instant is minted by Clock.now() (typed Effect[Instant]) or built from an Int via Instant.fromEpochMillis(n). Arithmetic composes with Duration: Instant ± Duration -> Instant (advance/retreat) and Instant - Instant -> Duration (the span between). Comparison is chronological and Instant is orderable (so sortBy/min/max key on it) but not numeric (sum/average reject it). The escape to raw millis is t.toEpochMillis() -> Int; the zero is the epoch. Timestamp math goes through Instant — now + 5.minutes is Instant + Duration; the former Int + Duration -> Int clock-math coercion was withdrawn at v0.90, so every Instant↔Int mix is a no_numeric_coercion error. See Operators.

t.toIso() -> String writes an instant as RFC 3339 text in UTC, always YYYY-MM-DDTHH:mm:ss.sssZ: three fraction digits and Z, so the text sorts in time order. Outside the years 0000 to 9999 the year takes the expanded ±YYYYYY form, and an instant beyond ±8.64e15 ms (past any date) faults. toString() still gives the epoch milliseconds, and the JSON codec still writes a number.

Instant.fromIso(s) -> Option[Instant] reads the RFC 3339 date-time profile:

let utc = Instant.fromIso("2026-10-30T08:54:50.123+02:00") // Some(…06:54:50.123Z)
let bad = Instant.fromIso("2026-10-30 08:54:50Z") // None: a space, not `T`
  • YYYY-MM-DD, T (or t), HH:mm:ss, an optional fraction of any length, then Z (or z) or an offset ±HH:mm, converted to UTC. -00:00 (“offset unknown”, RFC 3339) reads as Z: the time written is UTC.
  • A fraction past milliseconds is truncated toward the earlier instant.
  • The date must exist (2026-02-29 is None, 2028-02-29 is not), and a leap second (:60) is None, since epoch milliseconds cannot name it.
  • Anything else is None: a space instead of T, a time with no offset (it names no instant without a zone), the basic form without separators, week and ordinal dates, and the expanded year.

A date-only string is None here. String where IsoDate (see refined types) validates the same calendar date; Instant.fromIso("\\(day)T00:00:00Z") is always Some for such a Day.

Instant.fromIso(t.toIso()) is Some(t) for every instant in the years 0000 to 9999. Time zones, calendar fields and ISO durations are not part of the kernel.

Bytes (v0.110) is an immutable octet sequence — the type for arbitrary binary data that String (UTF-8 text) cannot hold without corruption. It is the one base type that does not emit to number: a Bytes erases to a host Uint8Array. There is no literal; construct a Bytes with:

  • Bytes.fromUtf8(s: String) -> Bytes — the UTF-8 encoding of a string (total).
  • Bytes.fromBase64(s: String) -> Option[Bytes] — decode base64; None on an invalid string.
  • Bytes.fromHex(s: String) -> Option[Bytes] — decode hex. Either case, an even number of digits and nothing else: a 0x prefix, whitespace or separators give None. "" decodes to Bytes.empty().
  • Bytes.fromBase64Url(s: String) -> Option[Bytes] — decode base64url (RFC 4648 §5, the -/_ alphabet), with no padding or exactly the padding the length needs. A standard-alphabet + or /, wrong padding, an impossible length or non-zero spare bits in the last character gives None, so each value has exactly one accepted spelling ("Zg" decodes, "Zh" doesn’t).
  • Bytes.empty() -> Bytes — the zero value (the empty sequence).

The methods:

MethodReturns
b.length()Intthe octet count
b.concat(other: Bytes)Bytesb’s octets, then other’s
b.slice(start: Int, end: Int)Bytesclamped like String.slice: a negative index is 0, an end past the length is the length, and start >= end is empty
b.compare(other: Bytes)Int-1, 0 or 1 in unsigned lexicographic order; a proper prefix sorts first
b.toHex()Stringlowercase, two digits per octet
b.toBase64()Stringstandard base64, padded
b.toBase64Url()Stringbase64url, unpadded (the JWT form)
b.decodeUtf8()Option[String]None on an invalid UTF-8 sequence

Encoding is total; decoding is partial and surfaced as Option, never hidden. Every decoder round-trips its encoder: Bytes.fromHex(b.toHex()) is Some(b) for every b, and likewise for base64 and base64url.

compare and == are not constant-time: they stop at the first differing octet, so their timing reveals how much of two values matches. Never use them to check a signature, MAC or token against a secret: use Crypto.equal from bynk.crypto, which compares in constant time.

==/!= compare by content, byte for byte — so two independently-built Bytes with the same octets are equal (unlike the number-erased base types, a Bytes is not compared by host reference). Equality is structural throughout, so a record carrying a Bytes field compares that field by content too. Bytes is orderable, unsigned lexicographic by octet with a proper prefix first, so < and a sortBy key work on it (b.compare(other) returns the same order as an Int). It is a Key: a Map[Bytes, V] or Set[Bytes] holds bytes by content. It has no arithmetic.

On the wire a Bytes serialises as a base64 JSON string (and deserialising requires a valid base64 string), so it round-trips through any record or store field and crosses a bundle context boundary — a fully ordinary serialisable value, the opposite of a Stream. (One current limit: a bare Bytes directly in a workers cross-context signature is diagnosed as not-yet-supported — put it inside a record, whose typed codec base64-encodes it, or build with --target bundle.)

File is the record a @multipart body names an uploaded file part with. It is exported by bynk (consumes bynk { File }):

File = { filename: Option[String], contentType: String, bytes: Bytes }

filename is the client’s name for the file, None for a part with no filename; contentType is the type the client claimed; bytes is the whole part, and its size is bytes.length(). The name and the type are client-controlled, so neither is a storage key or proof of the content. A File is a field of a @multipart body record, alone, in an Option or in a List (one layer); a test builds one with a record literal. It is not a boundary type: bynk.types.file_at_boundary refuses it, or a record carrying one, in an agent’s store, a handler’s parameter or result, an event or a call argument.

A record field may carry @name("…") before it, naming the key the field has on an HTTP request where that is not an identifier:

type Filter = {
@name("page-size") pageSize: Option[Int],
@name("filter[status]") status: Option[String],
owner: Option[String],
}

The field is pageSize everywhere in Bynk (access, construction, defaults, refinements); only the key a request reader looks for changes. It is legal only on a field of a record used as the cookies, query or @form/@multipart body record of an on http handler (bynk.types.field_name_not_request_record), takes exactly one string literal, or a String constant bound to one (bynk.types.field_name_bad_arg), and such a record may not be used as a JSON body, a result, a store field, an event or a call argument (bynk.types.field_name_record_not_boundary), since its JSON key is the field name. Two fields may not read the same name (bynk.types.field_name_duplicate), a cookie name must be a token and no name may be empty (bynk.types.field_name_invalid), and cookie and query names that differ only in case are refused (bynk.types.field_name_case_conflict). The request readers apply it: a cookies, query or @form/@multipart body record reads each renamed field from its wire key (the typed system-test drivers and Form.encode write it there, and the OpenAPI document and hover name it), while a failure still names the field, as query.pageSize. A tracked follow-up moves examples/sessions to a typed @name("__Host-sid") read (#3343).

A name that two places must agree on can be a constant. @name accepts a bare reference to a constant declared exactly String (not a refined type) and bound to a string literal, or to another such constant, from this unit or a usesd commons:

const VisitsCookie: String = "__Host-visits"
type Prefs = {
@name(VisitsCookie) visits: Option[Int],
}

The compiler reads @name(VisitsCookie) as @name("__Host-visits"): the token rule and the duplicate and case checks run on the resolved text, and a diagnostic points at the reference and names the constant. Go-to-definition, hover and rename work on it.

Cookie is the record a handler attaches to a result with withCookie. It is exported by bynk (consumes bynk { Cookie }), with SameSite = enum { Strict, Lax, Unrestricted } (Unrestricted is SameSite=None):

Cookie = { name: String, value: String,
maxAge: Option[Duration] = None, expires: Option[Instant] = None,
domain: Option[String] = None, path: String = "/",
secure: Bool = true, httpOnly: Bool = true,
sameSite: SameSite = Lax, partitioned: Bool = false }

RequestCookies is the raw, read-only view of an HTTP request’s cookies, the type of a handler’s cookies parameter when it needs a name a record field cannot spell. It has get(name) -> Option[String], all(name) -> List[String] and names() -> List[String], and is built in a test with RequestCookies.of(pairs) or RequestCookies.empty(). It is not a boundary type: it cannot be stored, sent or returned. See Reading a prefixed cookie.

TypeVariantsPurpose
Result[T, E]Ok(T), Err(E)success or error
Option[T]Some(T), Nonea value or nothing
Effect[T]—an effectful computation yielding T
HttpResult[T]see HTTPan HTTP response
Stream[T]—a value-over-time source (see Stream)
Query[T]—a lazy read over store storage (see Query)
Set[T]—an immutable set of Key elements (see Set)
MethodReturns
o.map(f: T -> U)Option[U]f applied to the value, if there is one
o.andThen(f: T -> Option[U])Option[U]chain a step that may itself be absent
o.filter(p: T -> Bool)Option[T]the value only when p holds
o.getOrElse(default: T)Tthe value, or default
o.orElse(f: () -> Option[T])Option[T]o if present, else f() (run only on None)
o.isSome() / o.isNone()Boolwhether there is a value
o.okOr(err: E)Result[T, E]Ok of the value, or Err(err)
r.map(f: T -> U)Result[U, E]f applied to the Ok value
r.mapErr(f: E -> F)Result[T, F]f applied to the Err value
r.andThen(f: T -> Result[U, E])Result[U, E]chain a step that may itself fail
r.getOrElse(default: T)Tthe Ok value, or default
r.isOk() / r.isErr()Boolwhich outcome it is
r.ok()Option[T]the Ok value, dropping the error

The Result and Option guide shows them in use.

ValidationError is the error type returned by refined-type .of constructors.

A ValidationError has two String fields:

FieldMeaning
fieldthe name of the refined type or field that failed validation
messagea human-readable description of the failure

It has no string form, so "\(e)" is refused (bynk.types.interpolation_non_scalar); interpolate its fields instead: "\(e.field): \(e.message)". The offending value is also carried at runtime but is not reachable from Bynk yet, so e.value is refused (bynk.types.unknown_field).

Stream[T] (v0.100) is a lazy, pull-shaped sequence of values produced over time — the primitive for incremental output, distinct from Effect[T] (which resolves exactly once) and Query[T] (a snapshot read over storage). Like those neighbours it is non-serialisable, non-storable, non-boundary, and not value-comparable: a live source is built and consumed in place, never persisted, sent across a context boundary, or compared with ==.

Within a Worker a stream moves freely (#2623):

  • Through a capability. An operation may take or return a stream (fn read(key: String) -> Effect[Download]), since a capability’s provider runs in the same isolate as its caller, so nothing is serialised.
  • Inside a record or sum. A field may be a stream (type Download = { contentType: String, body: Stream[Bytes] }). The type is then stream-carrying: non-boundary like the stream, with no JSON codec, and refused wherever a stream is (a handler’s parameter or result, a store field, an event) with bynk.types.stream_at_boundary, whose note names the field the stream is reached through.

A stream is read once. Draining it with collect, or handing it to a response, consumes it, and reading it again faults with bynk: a stream can be read only once. A builder (map, take) consumes its source when it is first read, not when it is built. A stream from the platform can only be read once, so an in-memory one behaves the same.

The v1 vocabulary is deliberately minimal:

FormTypePurpose
Stream.of(xs)List[T] -> Stream[T]build a stream from a list (the deterministic source)
s.map(f)(T -> U) -> Stream[U]lazily transform each element
s.take(n)Int -> Stream[T]bound the stream to the first n elements
s.collect()Effect[List[T]]drain the stream to a list (the terminal)

Errors ride in-band as Result elements (Stream[Result[T, E]]); a fault in the producer aborts the stream as faults abort handlers.

A stream’s end-to-end uses are streamed HTTP responses: Streaming(stream) returns an SSE body consuming a Stream[String], and RawStreamed(body, contentType) a raw body from a Stream[Bytes]; and a @raw request body, which a handler can receive as a Stream[Bytes]. A richer combinator vocabulary and live runtime sources are later increments of the real-time track.

Query[T] (v0.92; ADRs 0115/0119) is a lazy read over a store’s storage — the lazy receiver of the same combinator vocabulary the eager List methods carry, dispatched by receiver provenance: a chain rooted in a store reservations: Map[K, V] field is a Query, while the same names on an in-memory List are eager. Like Effect/Fn/Stream it is non-storable and non-boundary — rejected in any storable or boundary position (bynk.types.query_at_boundary) — but is otherwise first-class: nameable, returnable from a pure helper, passable. A query is agent-local and reads staged state (read-your-writes).

Builders are pure and return a further Query — filter, map, flatMap, sortBy, sortByDescending, take, skip, distinct, plus the joins and groupBy below.

Terminals execute the query and are Effect-typed (awaited with <-), folding into the storage capability the store fields already carry (no new given):

TerminalResult
.collect()Effect[List[T]]
.first()Effect[Option[T]]
.count()Effect[Int]
.sum(key) / .min(key) / .max(key) / .average(key)Effect[…] (empty-total: Option, or the zero for sum)
.any(p) / .all(p)Effect[Bool]
.fold(init, f)Effect[acc]
.forEach(f)Effect[()]

Joins and grouping (v0.92+; ADR 0120) take an into: combiner that projects each result through a lambda into a user-named type — bynk has no anonymous pair/tuple, so a join row is always a named record. The arguments are positional (left:/right:/into: name them for readability):

FormYields
joinOn(other, left: T -> K, right: U -> K, into: (T, U) -> V)equi-join → …[V]
leftJoin(other, left: T -> K, right: U -> K, into: (T, Option[U]) -> V)left outer → …[V]
join(other, on: (T, U) -> Bool, into: (T, U) -> V)predicate (nested-loop) → …[V]
groupBy(key: T -> K, into: (K, List[T]) -> V)grouping → …[V]

Each yields a Query[V] over storage and a List[V] eagerly. Because every result is a named V, chained joins stay flat and named — no nested pairs. An equi-joinOn whose probed key is @indexed routes through the index.

A store Map[K, V] roots three key-aware queries (v0.158; ADR 0184):

AccessorYields
map.keysQuery[K]
map.valuesQuery[V]
map.entriesQuery[MapEntry[K, V]]

.entries exposes each entry as a MapEntry[K, V] — a compiler-known nominal record { key: K, value: V }, read with .key/.value. bynk has no tuple/pair (ADR 0120), so an entry is a named record; the whole single-argument vocabulary above applies to .entries unchanged. MapEntry is non-boundary (it is a generic-record instantiation, ADR 0183), so a read handler projects each entry into a named type before its terminal:

// the id lives in the key; project it back into the boundary shape
items.entries.map((e) => TodoItem { id: e.key, seq: e.value.seq, title: e.value.title, done: e.value.done }).collect()

This is what lets a stored value drop the denormalised copy of its own key. The accessors are paren-less builders on the storage map, distinct from the eager in-memory Map value methods .keys()/.values() that return Lists.

List[T] (v0.88; ADR 0116) carries the query algebra’s eager, in-memory combinator vocabulary as kernel methods, so a chain reads xs.filter((x) => x > 2).map((x) => x * 2) (the same names the lazy Query carries over storage; the receiver decides eager vs lazy).

MethodReturns
xs.length()Intthe element count
xs.get(index: Int)Option[T]the element at index (from 0); None when out of range
xs.first()Option[T]the first element; None when empty
xs.firstOrElse(default: T)Tthe first element, or default when empty
xs.last()Option[T]the last element; None when empty
xs.lastOrElse(default: T)Tthe last element, or default when empty
xs.isEmpty()Booltrue when there are no elements
xs.contains(item: T)Boolsome element == item (T must be Eq)
xs.reverse()List[T]the elements in the opposite order
xs.find(p: T -> Bool)Option[T]the first element for which p holds; None when there is none
xs.prepend(item: T)List[T]item, then xs
xs.append(item: T)List[T]xs, then item
xs.concat(other: List[T])List[T]xs, then other
xs.map(f: T -> U)List[U]f applied to each element
xs.filter(p: T -> Bool)List[T]the elements for which p holds
xs.flatMap(f: T -> List[U])List[U]each element’s list, joined in order
xs.sortBy(key: T -> K)List[T]smallest key first; stable
xs.sortByDescending(key: T -> K)List[T]largest key first; stable
xs.sort()List[T]the elements themselves, smallest first; stable (T must be Ord)
xs.take(n: Int)List[T]the first n elements (all of them when there are fewer)
xs.skip(n: Int)List[T]all but the first n
xs.distinct()List[T]repeats dropped, each element at its first position
xs.distinctBy(key: T -> K)List[T]the first element for each key
xs.fold(init: U, step: (U, T) -> U)Ustep applied from init across the list, in order
xs.count()Intthe element count (the same as length())
xs.any(p: T -> Bool)Boolp holds for at least one element; false when empty
xs.all(p: T -> Bool)Boolp holds for every element; true when empty
xs.sum(key: T -> K)Kthe total of the keys; the zero when empty
xs.min(key: T -> K)Option[K]the smallest key; None when empty
xs.max(key: T -> K)Option[K]the largest key; None when empty
xs.min()Option[T]the smallest element; None when empty (T must be Ord)
xs.max()Option[T]the largest element; None when empty (T must be Ord)
xs.average(key: T -> K)Option[Float]the mean of the keys (Option[Duration] for a Duration key); a Decimal key is refused (bynk.query.sum_needs_numeric); None when empty
xs.joinOn(other, left, right, into)List[V]equi-join; see Joins and grouping
xs.leftJoin(other, left, right, into)List[V]left outer join
xs.join(other, on, into)List[V]predicate join
xs.groupBy(key, into)List[V]one result per key, in first-seen key order
rs.sequenceAll()Result[List[T], List[E]]for a List[Result[T, E]]: every value, or every error
rs.sequenceTry()Result[List[T], E]for a List[Result[T, E]]: every value, or the first error
xs.foldEff(init: U, step: (U, T) -> Effect[U])Effect[U]fold with an effectful step
xs.forEach(f: T -> Effect[()])Effect[()]run f for each element, in order
xs.traverse(f: T -> Effect[U])Effect[List[U]]run f for each element, in order, and collect the results
xs.parForEach(f: T -> Effect[()])Effect[()]run f for every element concurrently
xs.parTraverse(f: T -> Effect[U])Effect[List[U]]run f for every element concurrently; the values come back in input order
xs.traverseAll(f: T -> Effect[Result[U, E]])Effect[List[Result[U, E]]]run f for each element in order, keeping every outcome
xs.parTraverseAll(f: T -> Effect[Result[U, E]])Effect[List[Result[U, E]]]the same, concurrently
xs.traverseTry(f: T -> Effect[Result[U, E]])Effect[Result[List[U], E]]run f for each element in order, stopping at the first Err
xs.parTraverseTry(f: T -> Effect[Result[U, E]])Effect[Result[List[U], E]]the same, concurrently

The effect methods form one grid of names:

returns ()returns valueseach step a Result, keep allstop at first Err
in orderforEachtraversetraverseAlltraverseTry
concurrentlyparForEachparTraverseparTraverseAllparTraverseTry

Before #3967 parTraverse returned (); that is now parForEach. A parTraverse whose step returns Effect[()] still type-checks, so it gets the warning bynk.list.par_traverse_unit, whose fix (bynk check --fix) renames the call. A concurrent call that faults waits for every step to settle, then raises the first fault in input order, as par does; results are in input order whatever order the steps finish in.

The methods returning an Effect can only be called where effects are allowed. A method not in this table is bynk.types.method_not_found. The rest of this section groups them and gives the rules.

Builders (return a List): map, filter, flatMap, sortBy, sortByDescending, sort, reverse, take, skip, distinct, distinctBy.

Collecting Results (pure; the receiver is a List[Result[T, E]]): sequenceAll() returns Ok of every value, or Err of the list of every error in input order; sequenceTry() returns Ok of every value, or the first Err. xs.map(validate).sequenceAll() reports every failing field of a form at once. The empty list is Ok([]). bynk.types.sequence_needs_result flags a list that is not of Results. The effectful counterparts are traverseAll and traverseTry.

fn checkAll(rs: List[Result[Int, String]]) -> Result[List[Int], List[String]] { rs.sequenceAll() }

Adding items (return a new List; the receiver is unchanged): prepend(x) puts x at the front, append(x) puts it at the end, and concat(other) joins other after the receiver. A fold that builds a list in order uses append (or concat), with no reverse afterwards:

fn labels(ns: List[Int]) -> List[String] {
let none: List[String] = []
ns.fold(none, (acc, n) => acc.append(n.toString()))
}
fn withTotal(ns: List[Int]) -> List[Int] {
ns.concat([ns.fold(0, (acc, n) => acc + n)])
}

labels([1, 2, 3]) is ["1", "2", "3"], and withTotal([1, 2]) is [1, 2, 3]. foldEff builds in order the same way, its step returning Effect.pure(acc.append(x)).

Terminals: count, any, all, first, firstOrElse, last, lastOrElse, isEmpty, contains, find, sum, min, max, average.

Ordering keys (sortBy/sortByDescending/min/max), on a List and on a lazy storage Query, are any Ord type (bynk.types.key_not_orderable otherwise). sortByDescending is sortBy largest key first: the exact reverse of the ascending order, so a Float NaN comes first (None last, a longer list first). It is stable: equal keys keep their input order, which reverse(xs.sortBy(k)) does not. It behaves the same for a concrete, derives Ord or type-parameter key. Numeric keys: sum takes Int, Float, Duration or Decimal keys; average takes Int, Float or Duration, and refuses Decimal (bynk.query.sum_needs_numeric: sum, then divide with a scale and rounding mode). average -> Float (Duration for a Duration key). The same keys apply on a lazy storage Query. Empty aggregates are total — first/min/max/average return Option, sum the zero. The keyless sort(), min() and max() order the elements themselves, so the element type must be Ord (bynk.types.not_orderable otherwise). contains compares by ==, so the element type must support equality (T: Eq on a type parameter, bynk.generics.missing_eq_bound otherwise). Every first-party bynk.list free function now has a method, and each is the deprecated predecessor of it (see Operators & built-ins and First-party bynk capabilities).

Map[K, V] is a built-in immutable map with Key keys. It keeps insertion order. Map.empty() takes its types from context.

MethodReturns
m.length()Intthe entry count
m.get(key: K)Option[V]the value at key; None when absent
m.insert(key: K, value: V)Map[K, V]a new map with key set to value; m is unchanged
m.keys()List[K]the keys
m.values()List[V]the values
m.remove(key: K)Map[K, V]without key; m is unchanged; a no-op when key is absent
m.contains(key: K)Boolwhether key has an entry
m.getOrElse(key: K, default: V)Vthe value at key, or default when absent
m.isEmpty()Boolwhether there are no entries
m.entries()List[MapEntry[K, V]]the entries, in insertion order
Map.of(entries: List[MapEntry[K, V]])Map[K, V]a later entry for a key replaces the value and keeps the first position
m.filter(p: (K, V) -> Bool)Map[K, V]the entries for which p holds; order kept
m.mapValues(f: V -> U)Map[K, U]each value through f; keys and order kept
m.fold(init: U, step: (U, K, V) -> U)Ustep applied from init across the entries, in insertion order

Every method that returns a map keeps insertion order, over plain and composite keys alike. entries() yields the same compiler-known MapEntry as a store Map’s .entries, which is not a boundary type, so a handler projects entries into a named type before returning them. A MapEntry has no literal form, so Map.of takes the entries of another map, for example Map.of(m.entries().filter(…)). The bynk.map commons is deprecated: values, contains and getOr are the methods m.values(), m.contains(key) and m.getOrElse(key, default), and each call warns with bynk.map.deprecated_function and a fix. A store … : Map[K, V] field is a different thing: an agent’s storage map, read through Query and the map key accessors.

Set[T] is a built-in immutable set, beside List and Map. It keeps insertion order, as Map does: toList() and the wire form list the elements in the order they were first added, and inserting an element that is already there keeps its place.

let tags = Set.of(["b", "a", "b"]) // {b, a}
let more = tags.insert("c").remove("a") // {b, c}; `tags` is unchanged
let none: Set[Int] = Set.empty()
  • Members are Key types: see Keys. Anything else is bynk.types.not_keyable, whether written (Set[Float]) or inferred (Set.of([f])).

  • Statics: Set.empty() takes its element type from context, as List.empty() does, and Set.of(xs: List[T]) drops repeats, keeping each element’s first position.

  • Kernel: length(), contains(x), insert(x), remove(x) and toList(). insert and remove return a new set.

  • Combinators are methods, all in insertion order:

    • union(other: Set[T]): a’s elements, then other’s new members.
    • intersect(other: Set[T]) and difference(other: Set[T]): in a’s order.
    • isSubsetOf(other: Set[T]): whether every element is in other.
    • isEmpty(): whether there are no elements.
    • filter(p: T -> Bool): the elements for which p holds.
    • map(f: T -> U): each element through f; U must be a Key, and elements that map to one value merge at the first position.
    • fold(init: U, step: (U, T) -> U): step applied from init across the elements.

    The bynk.set commons is deprecated: its functions are these methods, and each call warns with bynk.set.deprecated_function and a fix.

  • Equality is membership: Set.of([1, 2]) == Set.of([2, 1]).

  • On the wire a set is a JSON array in insertion order. Decoding one with a repeated element fails, since a Bynk sender never writes one.

A store members: Set[T] field is a different thing: the storage set of an agent, with effectful add/remove/contains/size. A Set[T] value is the immutable collection described here.

Connection[F] (v0.102) is a held resource — a typed handle to a long-lived WebSocket connection, where F is the type of frames the server can send. It is the one concrete instance of the closed Held kind. Held values are runtime-produced (there is no constructor — they arrive from a capability operation or a handler parameter the framework supplies) and governed by an ownership discipline (the linearity rules, §2.9): a held value has at most one owner, and must be disposed — stored, closed, or transferred — before its scope exits.

OperationTypeNotes
c.send(f)F -> Effect[()]write a frame; non-consuming (the binding stays owned)
c.close()Effect[()]end the connection; consuming (the binding is spent)

Held values are non-serialisable, non-boundary, and not value-comparable — they may not cross a context boundary, be compared with ==, or be stored except in Cell[Option[Connection]] / Map[K, Connection] (a Set/Log/Cache rejects them). Storing one (conns.put(u, c)) or closing it (c.close()) disposes it; using it afterward, or letting it escape a handler undisposed, is a compile error. The compiler reports an undisposed connection (bynk.held.leak), a use after disposal (bynk.held.use_after_consume), and branches that dispose inconsistently (bynk.held.branch_divergence).

The full protocol surface — the on open / on message / on close handlers, edge authentication, broadcast over a held Map, the TestConnection model, and the platform mapping — is on the WebSocket reference page; the worked chat-room is the guide Handle a WebSocket connection. This section summarises how a connection is produced.

A service … from websocket(in:, out:) produces connections. The upgrade authenticates at the edge — like an HTTP route, on open must name its actor with by (there is no anonymous upgrade; a browser WebSocket carries a Bearer token in the Sec-WebSocket-Protocol subprotocol, since it cannot set an Authorization header) — and the handler receives a fresh, owned Connection[out] it must dispose, the canonical disposal being transfer into an agent:

service ChatGateway from websocket(in: ClientFrame, out: ServerFrame) {
on open (roomId: RoomId) -> Effect[()] by user: Participant {
let _ <- connection.send(ServerFrame { text: "welcome" })
let _ <- Room(roomId).join(user.identity, connection)
()
}
}

The service holds exactly one on open; inbound frames then arrive at the agent that owns the connection through the explicit on message / on close handlers, and the agent fans frames out to many connections by holding them in a Map and broadcasting over it. On the bundle target the connection is a TestConnection — a capture-and-inspect channel that records every frame sent — so a WebSocket service is fully developable and testable with no Durable Object. On the Workers target the connection maps onto a Durable Object using the hibernatable-WebSocket API: a Connection stored in agent state survives hibernation and is restored on rehydration.

Four compiler-backed statics decode and encode JSON at a typed boundary:

FormTypePurpose
Json.encode(v)Stringserialise a checked value to a JSON string
Json.encodePlain(v)Stringencode writing an Option as the value or null, as a non-Bynk API sends it (see Plain JSON)
Json.decode[T](s)Result[T, DecodeError]parse a JSON string into T, validating structure (and any refinements)
Json.decodeSql[T](s)Result[T, DecodeError]decode for a D1 row or list of rows, which also reads 0/1 as a Bool (SQL databases)

Json.decode[T] takes an explicit type argument and validates the decoded value against T — including refined-type predicates — so untrusted JSON enters the program only as a fully-checked value. DecodeError is the error it returns (malformed JSON, or a structural/refinement mismatch). See the guide Decode untrusted JSON into a typed value.

Json.encode writes an Option[U] in Bynk’s tagged form, {"kind":"Some","value":v} or {"kind":"None"}. Json.encodePlain(v) writes what a json { options: plain } route writes (JSON for non-Bynk clients): Some(v) as v and None as null, at any depth.

commons comments
type NewComment = {
body: String,
reply_to: Option[Int],
}
fn tagged(c: NewComment) -> String {
Json.encode(c)
}
// {"body":"LGTM","reply_to":{"kind":"None"}}
fn plain(c: NewComment) -> String {
Json.encodePlain(c)
}
// {"body":"LGTM","reply_to":null}

Use it for the text a non-Bynk API reads or sends: an outbound Fetch.send body, or a test stubbing an external API at the wire. Json.decode reads the plain text back to the same value (the decoder accepts both forms). It changes Option only: sums, Result and Map keep their shapes.

Two refusals keep it honest. An Option whose payload can itself be null (Option[Option[T]], Option[()]) anywhere in the value’s type is bynk.json.nested_option_plain, because Some(None) and None would both write null. A value whose type mentions a type parameter is bynk.json.encode_plain_generic: a generic value encodes through its Codable witness, which writes the tagged form, so encode at a concrete type. Queue.sendValue and the other typed capability writes stay tagged, because a Bynk consumer reads them.

DecodeError is a record of three String fields, so a failed decode can be explained in Bynk. It was called JsonError before it became the error type of every decoder: the old spelling still compiles, as the same type, with a bynk.types.deprecated_json_error warning whose fix rewrites it (bynk fmt rewrites it too). Its fields let a failed decode be explained in Bynk:

FieldMeaning
kindwhat went wrong: Malformed (the text is not JSON), StructuralMismatch (the JSON has the wrong shape or a wrong-typed value), or RefinementViolation (a value broke a refined type’s predicate)
pathwhere, as a path from the root $: $ for the whole document, $.qty for a field, $.items[2].id for a list element’s field
messagea human-readable description, such as expected number, got string

A DecodeError has no string form, so "\(e)" is refused (bynk.types.interpolation_non_scalar); interpolate its fields instead: "\(e.kind) at \(e.path): \(e.message)" reads StructuralMismatch at $.a: expected number, got string. kind is a String, not a sum type, so compare it as text.

Json.encode writes an Option[U] in Bynk’s tagged form: {"kind": "Some", "value": …} or {"kind": "None"}. Json.decode accepts that form and also the forms other JSON producers use for an optional value:

JSON for an Option[U]Decodes to
the key is absent from its recordNone
nullNone
{"kind": "None"}, with no other keysNone
{"kind": "Some", "value": v}, with no other keysSome(v), v checked as U
any other value vSome(v), v checked as U

An HTTP route can opt its response bodies into the plain form instead (Some(v) as v, None as null); Json.encode and every other boundary keep the tagged form. See HTTP → JSON for non-Bynk clients.

The tagged forms are tried first, so whatever Json.encode writes decodes back to the same value, even for an Option[Option[T]]. The same decoder runs at every boundary, so an HTTP request body, a cross-context call and a stored agent field accept these forms too.

The tagged forms are recognised only when the object has exactly those keys. Every payload Bynk wrote decodes as before, but a hand-written tagged object with an extra key, such as {"kind": "Some", "value": "d", "note": "x"}, is read as a bare value, so it fails for an Option[String].

Yaml.decode[T](s) is Json.decode[T] over YAML text. There is no Yaml.encode.

FormTypePurpose
Yaml.decode[T](s)Result[T, DecodeError]parse a YAML document into T, validating structure (and any refinements)

The YAML is parsed to the same tree of null, booleans, numbers, strings, lists and objects that JSON.parse yields, and then checked by the identical typed decode, so T is any type Json.decode accepts, the record mapping, field defaults, Option-for-absent-key, refinements and $.path errors are the same, and T is inferred from an expected Result[T, DecodeError] just as it is for Json.decode. See the guide Read a YAML settings file into a typed value.

The subset. YAML 1.2, one document: block and flow mappings and sequences, plain, single-quoted and double-quoted scalars (multi-line included), literal | and folded > block scalars with chomping and indentation indicators, comments, and scalar mapping keys. A leading --- and a trailing ... are accepted.

Scalar resolution is the YAML 1.2 core schema, by shape, for plain scalars only:

WrittenIs
null, Null, NULL, ~, or nothingnull
true, True, TRUE, false, False, FALSEa boolean
12, -3, +7, 0o17, 0x1Fan integer
1.5, -.5, 1e3, 5.a float
anything elsea string

So on, off, yes, no, y and n are strings, as are 2001-12-14, 1_000 and 0b101. A quoted scalar is always a string. A mapping key is always text: 1: a has the key "1". An integer beyond 2^53 is read as JSON.parse would read it.

Refusals. Each is a DecodeError with its own kind, the $.path where it was found ($ before any key), and line L, column C in message. Nothing is decoded partially.

kindCause
Malformeda syntax error, including a tab used as indentation
UnsupportedAnchoran anchor, &name
UnsupportedAliasan alias, *name
UnsupportedMergeKeya merge key, << (a quoted "<<" is only a key)
UnsupportedTagany tag, !tag or !!tag, because resolution is by shape
MultipleDocumentsa second document in the stream
UnsupportedSyntaxa construct outside the subset: a complex key (? key), a directive (%YAML), a key written as a collection
UnsupportedValue.inf, -.inf or .nan: the decoded tree cannot hold a non-finite number
DuplicateKeythe same key twice in one mapping (the same rule as a duplicate Map key)
LimitExceededinput over 1,048,576 bytes of UTF-8, or collections nested more than 256 levels

Limits. The depth limit is the recursive-codec bound (§6), applied while parsing so that a deeply nested document is refused rather than unwound. The size limit is the HTTP body limit. Json.decode has no size limit of its own.

An error from the typed step after parsing (StructuralMismatch, RefinementViolation) names its field path exactly as it does for JSON.

Form.decode[T](s) and Form.encode(v) are the @form mapping as a codec, for a @raw handler, a webhook, a test, or an outbound request that sends a form.

FormTypePurpose
Form.decode[T](s)Result[T, DecodeError]read form text (a=1&b=2) into T, by the rules a @form route applies
Form.encode(v)Stringwrite v as the flat form text such a route reads

T is a record whose fields a form can carry (the same set as a @form body: String, Int, Bool, Decimal, an enum, or a refined or opaque type over one, optionally in an Option or a List); anything else is refused (bynk.types.form_uncodable). The reading is the router’s: repeated keys fill a List, an unfilled input is absent, a Bool reads on/off as well as true/false, and the record’s own codec then applies defaults and refinements. A failure is a DecodeError whose path is rooted at $ ($.email, and $.age.value for an Option field, as Json.decode writes it) where a @form route’s 400 would say body.email. T is inferred from an expected Result[T, DecodeError], as for Json.decode.

Form.encode writes each field under its name, a List as a repeated key, an Option as its value or nothing, and an enum as its variant’s name. Form.decode(Form.encode(v)) gives back v. There is no Multipart.decode: a File part has no useful text form.

Two ambient built-in functions raise a fault on purpose. Both take a String message and have the internal bottom type (Never), which is assignable to every type, so a call fits a match arm, an if branch or a function body of any type with no made-up default.

CallUseDiagnostics
unreachable(message)A case the author knows cannot happen.—
todo(message)Unfinished code that still type-checks.bynk.fault.todo (warning)
fn label(s: Status) -> String {
match s {
Open => "open",
Closed => "closed",
Archived => unreachable("archived orders are filtered upstream"),
}
}
fn refund(o: Order) -> Effect[Result[(), RefundError]] {
todo("refunds — #1234")
}

Evaluating either is a fault, like a division by zero or an invariant violation: the handler faults, an agent’s state does not commit, and the response is the existing fault response. The logged fault carries the kind (Unreachable or Todo), the message and the path:line:col of the call. A test observes one with expect <call> faults. todo compiles but warns, so bynk check --deny-warnings keeps unfinished code out of CI.

They are not keywords: a fn or binding of the same name shadows them. There is no general panic — use Result for any failure a caller could handle. Never cannot be written in source, and a lambda whose body is only a fault call gets its type from the expected function type.

type Id = Int

A named type is a distinct nominal type, not a transparent synonym: an Id is not an Int, and it is branded in the emitted TypeScript. It carries a .of constructor (like any refined type, it has no .unsafe — that is opaque-only; ADR 0182). While the type has no predicate, Id.of(n) cannot fail and returns Id directly; adding a where clause turns it into Result[Id, ValidationError], so every call site that can now fail becomes a type error until it handles the failure. (The rule is “no predicate and no implicit base check”: a Float named type stays fallible, since .of also rejects NaN and infinities.)

A record groups named, immutable fields:

type Order = {
id: String,
item: String,
}
  • Construct by naming every field that has no default: Order { id: "1", item: "book" }.
  • Access with dot notation: o.id.
  • Update with the spread form, which copies and overrides: Order { ...o, item: "pen" }.

Records emit a TypeScript interface with readonly fields. A record field may not directly be of the record’s own type (bynk.resolve.recursive_record_field).

A field is a key in the JSON a record decodes from and encodes to, and a third-party payload picks its own keys: GitHub’s use type, from and self. A reserved word can therefore name a field wherever the name is a label and not a binding:

type Account = { login: String, type: String }
fn isOrg(a: Account) -> Bool { a.type == "Organization" }
fn build() -> Account { Account { login: "bynk-lang", type: "Organization" } }
fn kind(a: Account) -> String {
match a { Account { type: t, .. } => t }
}
  • A field declaration, a construction initialiser, a record or named pattern field and a variant payload field take a reserved word when it is followed by :. A variant payload field still cannot be named kind, the wire tag (bynk.resolve.reserved_payload_field).
  • A member after ., a field access, a method call or a method declaration (fn Sorted.from(…), Sorted.from(xs)), takes a reserved word when it is on the same line as the .. A half-typed a. above a line that starts let is still an error at the let.
  • A parameter, a let or lambda binding and a bare reference still refuse a reserved word, so the shorthand forms are refused too: Account { type, .. } as a pattern and Account { type } as a construction are bynk.parse.keyword_field_shorthand. The fix for a pattern is type: type_; for a construction, write type: <value>.

The emitted TypeScript keeps the field name: a.type, { type: "Organization" }.

A field may declare a default, field: T = expr. A literal may leave that field out, and a body decoded without its key takes the default too:

type Mode = enum { Fast, Careful }
type Options = {
name: String,
retries: Int = 3,
mode: Mode = Mode.Careful,
timeout: Option[Duration] = None,
tags: Map[String, String] = Map.empty(),
}

Options { name: "nightly" } is Options { name: "nightly", retries: 3, mode: Careful, timeout: None, tags: Map.empty() }, and Options { name: "x", retries: 5 } keeps its own retries. A field without a default is still required.

  • What a default may be. A static value of the field’s type: a literal, a variant, Some/None/Ok/Err, a record or list literal, Map.empty(), Set.empty(), or T.unsafe(lit) for an opaque type. It can’t call a function or read a binding (bynk.types.bad_field_default).
  • Option fields are not optional by default. Write = None to make one so. On the wire an absent key already decodes as None; in a literal the field is required unless it says otherwise.
  • A spread wins. Options { ...o, name: "y" } takes every other field from o, never from a default.
  • On the wire. A body without a defaulted field’s key decodes to the default; a key that is present, null included, decodes as sent. The OpenAPI document lists a defaulted field as not required.
  • Generic records. A default must hold for every instantiation: items: List[T] = [] and next: Option[T] = None do, a field of type T can’t have one.
  • Fields that apply a generic. On a record field, the default is a value of the instantiated type: page: Paginated[String] = Paginated { items: ["first"] }, or outcome: Outcome[Int] = Pending("queued") for a generic sum. Inside a generic record it may not write a value of the record’s own parameter (warm: Paginated[T] = Paginated {} holds for every T; Paginated { items: [1] } doesn’t).
  • Variants don’t take defaults (bynk.types.field_default_on_variant). A variant is built like a call; hold optional values in a record instead.

Adding a field with a default doesn’t break existing literals, which is why the first-party options records (FetchOptions, QueueSend, KvGet, KvPut, R2Put) give every field one. A field added with a default to a type a service takes or returns is a compatible contract change: the callee ships first, and an older caller gets the default (Contract skew). Changing a default changes every literal and every decode that relies on it, so treat it as a behaviour change. See Add an option without breaking callers.

A record field, a sum variant, a variant’s payload field and a messages entry each take a doc on the line above them, as a --- text line or a --- block. Hover, completion and the documentation page show it. See Document fields and variants.

A record type may take type parameters — a name scoped to the declaration, optionally bounded (see Generics and bounds) — so one shape serves many element types. The common case is an API envelope:

type Paginated[T] = {
items: List[T],
cursor: Option[String],
}
type User = { id: Int, name: String }
fn first_page(users: List[User]) -> Paginated[User] {
Paginated { items: users, cursor: None }
}
fn items_of(page: Paginated[User]) -> List[User] {
page.items
}
  • Apply the type to concrete arguments wherever a type is expected: Paginated[User], Keyed[String, Int].
  • Construct as an ordinary record; the type arguments are inferred from the field values. When a field cannot pin them down (an empty items list), annotate the binding: let p: Paginated[User] = Paginated { items: [], cursor: None }.
  • Access fields with the argument substituted in: page.items has type List[User].

Only a record or sum body may be generic — a refined or opaque type cannot take type parameters (bynk.generics.generic_non_record). A generic type must be applied to exactly its declared number of arguments (bynk.generics.type_arg_count).

Generic records emit an erased TypeScript generic interface — type Paginated[T] becomes export interface Paginated<T> — exactly as a generic function erases to function f<A>(…).

Generic records and sums at the boundary (v0.174)

Section titled “Generic records and sums at the boundary (v0.174)”

A generic-record or generic-sum instantiation is serialisable — it may appear in a field of another record, a sum payload, a service or agent handler signature, agent state, or a Json.encode/Json.decode target — exactly when its type arguments are. The compiler generates a monomorphised codec per instantiation: a Paginated[User] boundary emits __serialise_Paginated_User / __deserialise_Paginated_User, specialised to the concrete arguments and delegating to their codecs (__serialise_List_User, __serialise_Option_String). The emitted TypeScript interface stays the erased Paginated<T>; only the codec is per-instantiation, matching how List/Map/Result already specialise.

fn save(page: Paginated[User]) -> String {
Json.encode(page) // __serialise_Paginated_User
}
fn load(s: String) -> Result[Paginated[User], DecodeError] {
Json.decode[Paginated[User]](s) // __deserialise_Paginated_User
}

A non-serialisable argument is still rejected, at the argument: a function, Query, Stream, or Connection type inside the instantiation (Paginated[Int -> Int]) draws that type’s own boundary error (bynk.types.function_at_boundary, …), and an uncodable Json target draws bynk.types.json_uncodable.

A recursive generic type — a record or sum that transitively contains itself, whether directly, through another type, or through an Option/List wrapper (type Node[T] = { value: T, next: Option[Node[T]] }) — declares and works inside a context: build it, match on it, fold it and pass it to generic functions like any other generic. It has no codec yet, so it is refused where a codec is required, with bynk.generics.recursive_generic_at_boundary: a service or agent handler signature, an agent store field or key, an event field, an actor identity type, a Json.encode/Json.decode target and a Codable witness. A record field, a sum payload and a capability signature are not such positions, so a type that merely contains a recursive generic is refused where it is used, and the note names the field path it is reached through (Holder.t). The refusal fires once per use, not once per self-reference.

Recursion must be uniform: a self-reference passes the declaration’s own type parameters through unchanged and in order (Node[T] inside Node[T], including through Option, List, Map and sum payloads), and a mutually recursive partner, of any arity, is applied only to the declaration’s own parameters or to types that mention none (Binding[A, String] inside Expr[A]). Polymorphic recursion (type Weird[T] = { next: Option[Weird[List[T]]] }, or Pair[B, A] inside Pair[A, B]) generates an unbounded set of instantiations and is refused at the declaration with bynk.generics.polymorphic_recursion. (A non-generic recursive type is unaffected: its single codec is self-referential and terminates on the data.) To cross a boundary today, use a concrete recursive type.

A generic type may carry instance methods. A method whose receiver is a generic type sees the type’s own parameters in scope alongside any it declares itself, so fn Box.map[U](self, f: A -> U) -> Box[U] reads A from the receiver Box[A] and infers U from the argument. It erases to a generic namespace-object method — map<A, U>(self: Box<A>, f: (a: A) => U): Box<U> — the type’s parameters threaded onto each method (the namespace object itself cannot carry them). The type arguments are inferred from the receiver and the argument types; an explicit list, x.map[String](f), names the method’s own parameters only (the receiver’s are already known) and pins them where inference has nothing to go on (fn Box.cast[U](self) -> Option[U] is called b.cast[String]()); the arity is checked as for any generic call (bynk.generics.type_arg_mismatch). A static method on a generic type (fn Box.of(value: A) -> Box[A]) is generic over the type’s parameters too, followed by its own; see Generics. A static whose signature never mentions one of the type’s parameters is rejected (bynk.generics.method_on_generic_type) — no call could determine it. A refined or opaque body cannot be generic (its base is a fixed primitive); only a record or sum body may be (bynk.generics.generic_non_record), and generic sums are described under Sum types.

A sum type is one of several variants; a variant may carry a payload. The pipe form is required whenever any variant carries a payload:

type Status =
| Pending
| Shipped(tracking: String)
| Cancelled(reason: String)

When every variant is payloadless, write the enum form — it is the canonical spelling for a payloadless sum, and these docs use it throughout:

type Suit = enum { Hearts, Diamonds, Clubs, Spades }

enum { A, B, C } is exactly sugar for | A | B | C; the two are the same type. Reach for the pipe form only when a variant needs a payload.

  • Construct by naming a variant: Pending, Shipped("1Z…").
  • Consume with match or is.
  • Document a variant, or a payload field, with a doc on the lines above it, as a record field is.

Sum types emit a discriminated union keyed on a tag field. As JSON, a variant is a flat object whose kind key names the variant ({"kind": "Shipped", "tracking": "1Z…"}), so a payload field cannot be named kind (bynk.resolve.reserved_payload_field). A payload field named tag is fine: it keeps that name on the wire.

Two sums in scope may declare the same variant name: two of your own, or two that a consumed unit exports (bynk.cloudflare’s SqlError has a Failed, and so may an enum of yours). A bare use of the name builds the sum the expected type names: an annotated let, a parameter, a return type, or the operation a stub overrides.

type DbError = | Constraint(message: String) | Failed(message: String)
type MailError = | RateLimited | Failed(message: String)
fn send() -> Result[Int, MailError] {
Err(Failed("down")) // MailError.Failed: the return type picks it
}

With no expected type naming one of them (let e = Failed("down")), the compiler does not pick one: the name is bynk.resolve.ambiguous_variant, and the message lists the qualified forms (DbError.Failed(...) or MailError.Failed(...)). A match arm or is pattern never needs qualifying, because it reads its scrutinee’s sum.

A sum used as an error type may declare embeddings — a trailing embeds <type> as <Variant> clause naming a single-payload variant that wraps a sub-error. The ? operator then converts that sub-error automatically, replacing the boilerplate .mapErr(Wrap) on every cross-context chain:

type OrderError =
| OutOfStock(sku: Sku)
| Payment(reason: PaymentError)
| Fulfilment(reason: ScheduleError)
embeds PaymentError as Payment, ScheduleError as Fulfilment

Each embeds E as V requires V to be a variant of the same sum with exactly one payload field of type E, and a given E may be embedded by only one variant (so the conversion is unambiguous). The conversion is one level: ? converts a Result[T, E] into Result[_, F] only when F declares E directly. Mapping a domain error to an HTTP status stays an explicit match in the handler — by design, not an embedding.

A sum body may carry [A, B] type parameters, exactly as a record body does. A parameter is an unconstrained, bound-free name resolved as a rigid variable inside the variant payloads:

type ApiResult[T] =
| Loaded(value: T)
| Failed(message: String)

A reference applies concrete arguments (ApiResult[User]). Construction infers the arguments argument-directed from the variant’s payload (Loaded(user) is ApiResult[User] because user : User); a variant whose payload cannot determine a parameter — a payload-less variant, or one that does not mention it (Failed) — leans on the binding’s expected type as the pressure valve (let r: ApiResult[User] = Failed("...")), and reports bynk.generics.uninferable_type_arg when neither grounds it. match substitutes the arguments into each arm’s payload binding (Loaded(v) binds v : User). Emission is erased TypeScript generics — one export type ApiResult<T> discriminated union, with each payload constructor a generic arrow (Loaded: <T>(value: T): ApiResult<T> => …).

A generic sum is declared, constructed and matched like any other, with the arguments substituted into each arm:

type Opt[A] =
| Nope
| Have(value: A)
type User = { id: Int, name: String }
fn name_of(found: Opt[User]) -> String {
match found {
Nope => "nobody"
Have(user) => user.name
}
}
fn find(users: List[User]) -> Opt[User] {
match users.first() {
Some(u) => Have(u)
None => Nope
}
}

Like a generic record, a generic-sum instantiation is serialisable exactly when its type arguments are, through a monomorphised codec per instantiation (__serialise_ApiResult_User / __deserialise_ApiResult_User); a recursive generic sum declares and works inside a context but has no codec yet, so it is refused where a codec is required, with bynk.generics.recursive_generic_at_boundary (see Generic records above). A generic sum may not carry an embeds clause (bynk.generics.generic_sum_embeds).

An opaque type is backed by another type but is nominally distinct:

type OrderId = opaque String
  • Construct only via OrderId.of(...) (checked, returns Result) or OrderId.unsafe(...) (unchecked); record syntax is rejected (bynk.resolve.opaque_record_construction).
  • Construction and inspection are confined to the defining module/context.
  • Opaque types are excluded from literal admission.
  • An opaque type is not Ord outside its defining unit unless it says derives Ord.

A Map key, a Set member and the key of a List’s distinct, distinctBy, groupBy and joins must be a Key type. A type is Key when it is:

  • String, Int, Bool, Instant, Duration, Bytes or Decimal, or a refined or opaque type over one of them;
  • Option[T] or List[T] with T a Key;
  • a record, sum or enum whose every field and payload is a Key, with no derives needed. A generic record or sum is a Key at an instantiation whose arguments are;
  • a type parameter declared K: Key (Generics).

A Float is never a Key, at any depth: NaN is not equal to itself, so a key that holds one could never be found again. Map, Set, functions and held resources are not keys either. Using one is bynk.types.not_keyable.

Two keys are the same key when they are ==, so Map[OrderId, Int] finds an entry with an equal OrderId however it was built, and keys() returns the keys as inserted, in insertion order. Key implies Eq. A Decimal key is the same key at any scale (1.2d and 1.20d are one key), and keys() returns the spelling that was inserted first.

commons demo.keys
type OrderId = {
region: String,
n: Int,
}
fn tally(ids: List[OrderId]) -> Int {
let seen: Set[OrderId] = Set.of(ids)
seen.length()
}

A store Map, Set or Cache, and an @indexed field, still take only String, Int or a refined or opaque type over them. A Query’s distinct, distinctBy, groupBy and join keys take any Key type, as a List’s do.

Ord is the set of types with a total order: what < <= > >=, the sortBy/min/max keys on a List, its keyless sort/min/max and a T: Ord bound accept. It is opt-in for your own types: end the declaration with derives Ord.

commons demo.ordering
type Priority = enum { Low, Medium, High } derives Ord
type Task = {
priority: Priority,
due: Instant,
title: String,
} derives Ord
type Maybe[T] =
| Missing
| Present(item: T)
derives Ord
fn urgent(a: Task, b: Task) -> Bool {
a.priority > b.priority
}

derives is a contextual word that only means something after a type body, so it stays a valid identifier elsewhere. derives Ord + … is the list form; Eq, Key and Codable are derived automatically, so naming one is bynk.types.derives_automatic (a fix removes it). Any other name is bynk.generics.unknown_constraint.

Which types are Ord. Int, Float, Decimal, String, Duration, Instant and Bytes; a refined type over one of them; Option[T] and List[T] where T is Ord; a record, sum, enum or opaque type that derives Ord; and a type parameter declared T: Ord. Bool, Result, Map, Set, functions and held resources are not. A generic type that derives Ord is Ord at an instantiation whose arguments are (Maybe[Int], not Maybe[Bool]). Every field and payload type of a type that derives Ord must be Ord, else bynk.types.derives_field_not_orderable names the field.

The order.

TypeOrder
Int, Duration, Instantnumeric
Decimalnumeric, ignoring scale (1.2d and 1.20d are equal)
Stringcode point, element by element (not locale); agrees with storage key order and SQLite’s BINARY collation
Bytesunsigned octets, lexicographic
Floattotal: NaN last and equal to itself, -0 equal to 0
Option[T]None first, then Some by payload
List[T]lexicographic, a proper prefix first
recordby field, in declaration order
sum, enumby variant declaration order, then by payload

The Float total order applies to the ordering kernels and Ord witnesses. The operators keep IEEE behaviour on a Float: NaN < x is false, and == is unchanged.

Reordering changes the order. A derives Ord type sorts by declaration order, so moving a field, or a variant, changes how its values sort. The wire contract hash ignores field and variant order, so the change does not appear as a contract change and bynk raises no diagnostic for it. Treat the declaration order of such a type as meaningful.

Not ordered by accident. A type without derives Ord is never ordered implicitly. Using < or a sort key on one is bynk.types.not_orderable, whose “add derives Ord” suggestion is never applied by bynk check --fix or Fix all, because opting in is a decision about what the order is.

A base type plus a predicate. See the refined-type reference.

A refined String where Matches("…") checks a whole string against a pattern. Six String methods use the same patterns to look inside one (the full set of String methods is in String):

let ok = sku.matchesRegex("[A-Z]{3}-[0-9]{4}") // the whole string
let has = text.containsRegex("(?i)error") // anywhere, ignoring case
let v = text.findRegex(r"v(\d+)\.(\d+)") // Some([Some("v2.14"), Some("2"), Some("14")])
let all = text.findAllRegex(r"\d+") // every match
let tidy = text.replaceRegex(r"\s+", " ") // every match; `$1`, `$<name>`, `$$`
let parts = csv.splitRegex(r"\s*,\s*") // captured groups are not kept

A regex is easiest to read as a raw string, r"…", where a backslash is just a backslash: r"\d+" and "\\d+" are the same pattern, and the compiler checks them identically.

  • The pattern must be a string literal (of any form: ordinary, raw or multi-line). It is checked when the program compiles, as a Matches pattern is: its syntax, and that it cannot take catastrophic time on a crafted input (ReDoS). A pattern built at run time would escape that check, so it is refused (bynk.types.regex_not_literal).
  • Captures come back as a list: element 0 is the whole match, then each group, None for a group that did not take part.
  • Flags go at the start of the pattern: (?i) ignores case, (?m) lets ^/$ match at line breaks, (?s) lets . match a newline.
  • Semantics are JavaScript’s RegExp, without the u flag, as Matches uses.
  • replaceRegex reads $1, $<name>, $& and $$ in the replacement, unlike replace, which inserts its text literally.

match branches on every variant of a sum/Result/Option, binding payloads:

match s {
Pending => "…"
Shipped(tracking: t) => t
Cancelled(reason: r) => r
}

A match must be exhaustive (bynk.types.non_exhaustive_match); a match is an expression whose arms must join to a common type — their least upper bound, so a refined type and its base agree at the base (bynk.types.match_arm_mismatch).

Every arm must also be reachable (bynk.types.unreachable_arm): an arm is an error when each value its pattern matches is already matched by an earlier arm. Each of these is rejected at the marked arm:

match o {
Some(_) => 1
Some(Red) => 2 // `Some(_)` already matches every `Some`
None => 3
}
match c {
Red => 1
Green => 2
Blue => 3
_ => 4 // the variants above are already exhaustive
}
match o {
Some(Red | Green) => 1
Some(Blue) => 2
Some(Green) => 3 // the first arm's or-pattern already matches it
None => 4
}

A narrower arm may precede a wider one (Some(Red) then Some(_)), and a guarded arm never counts as covering, because its guard may fail. So an unguarded arm with the same pattern can always follow it.

Both checks are one rule (patterns track, slice 3, #2665): an arm is reachable when it matches some value the unguarded arms before it do not, and a match is exhaustive when nothing is left over. It applies at any depth, so a payload with several fields, a record, or a nested pattern needs no wildcard once its arms cover every case:

match pair {
Pair(true, _) => "left"
Pair(false, true) => "right"
Pair(false, false) => "neither"
}
match order {
Order { status: Paid, .. } => 1
Order { status: Pending, .. } => 2
Order { status: Cancelled, .. } => 3
Order { total, .. } => total // bynk.types.unreachable_arm
}

A list is covered by length: [] and [x, ..rest] together cover every list, and [_] and [_, _] alone leave [_, _, ..] uncovered (see List patterns). Redundancy is found across several earlier arms, not only one at a time. A guarded arm, and a refined pattern (_ where …), cover nothing, because the guard or predicate may fail. String literals never complete their type, so a String match ends in _ or a name; an Int match is complete when its literals and range patterns leave no integer out, which only ranges with an open end can do.

A missing case is reported as a pattern you can paste as an arm: variant Pair(false, false) of Pair is not covered, or Order { status: Cancelled, .. } is not covered, where _ stands for a field the missing values leave open. The editor’s add missing arms fix inserts every reported pattern. At most eight are reported at once, with a count of the rest. A match too tangled to decide within the compiler’s step budget is reported as non-exhaustive, with a note asking for a _ arm; it is never accepted unproved.

A List is matched by its length and elements with a list pattern (patterns track, slice 4, #2680):

match items {
[] => "empty"
[only] => only.sku
[first, _, ..] => first.sku
}
match xs {
[] => 0
[x, ..rest] => x + sum(rest)
}
PatternMatches
[]the empty list
[p₁, …, pₙ]exactly n elements, element i against pᵢ
[p₁, …, pₙ, ..]n or more elements; the rest is not bound
[p₁, …, pₙ, ..rest]n or more; rest is a List[T] of the remaining elements

n may be 0: [..] matches any list and [..rest] binds the whole list.

  • Each element is any pattern, and list patterns nest (Some([x, ..]), [[a, ..], ..]). They work in match, in or-pattern alternatives, after is (no parentheses: the pattern closes at ]) and in let … else.
  • The .. is the last element, and there is at most one (bynk.parse.list_rest_not_last); patterns for the end of a list, such as [.., last], are not available. ..rest names the rest, and .._ is not a form, because a bare .. already binds nothing. A .. followed by an integer ([..9]) is not a rest marker but a range pattern element.
  • The value must be a List[T]; a Set, a Map, a record or any other type is bynk.types.list_pattern_on_non_list. Each element is checked at T.
  • Exhaustiveness is by length. [] and [x, ..rest] cover every list, with no _ arm. A missing length is reported as a pattern, [], [_] or [_, _, ..], with an element pattern where the missing lists need one ([None, ..]). An arm the earlier ones cover is bynk.types.unreachable_arm ([x, ..] after [_, ..]). See Exhaustiveness and reachability.
  • Or-pattern alternatives bind the same names at the same types, so [x] | [x, ..] is legal and [x] | [] is not.
  • Binding ..rest copies the remaining elements, which costs time in proportion to the list’s length (O(length − n)) on each match. A recursive [x, ..rest] => f(rest) is therefore quadratic overall. The kernel folds (fold, map, filter) are the recommended way to visit every element. .. with no name, and [..rest] (which binds the list itself), copy nothing.

In a let, a list pattern needs an else (let [head, ..] = jobs else { 0 }), since a list can be shorter than the pattern. [..] and [..rest] cannot fail, so an else on one is bynk.types.unreachable_arm; write let rest = xs. See Match on a list’s shape.

An Int is matched by the band it falls in with a range pattern (patterns track, slice 5, #2699; the same production via schema(...) takes, events slice 4b, #990):

match age {
..-1 => "invalid"
0..12 => "child"
13..17 => "teen"
18.. => "adult"
}
PatternMatches
lo..hievery Int n with lo <= n <= hi
lo..every Int n with n >= lo
..hievery Int n with n <= hi
  • Both bounds are inclusive, like InRange(lo, hi). Each is an Int literal, optionally negative (-5..-1, ..-1), with digit separators as in any literal. A bound beyond the safe-integer range is the usual Int literal error. lo..lo is legal and means the literal. A bare .. is never a range: it is the rest marker of a list or record pattern.
  • A range is a pattern wherever an Int literal is: in a match arm, nested in variant, record and list patterns, in or-patterns (0..9 | 90..99) and in let … else. It binds nothing.
  • Only Int. The scrutinee, or the field or element the range sits in, must be an Int or a refinement of one; anything else is bynk.types.range_pattern_on_non_int. Float (NaN, representation) and String ranges are deliberate non-goals. A refined Int is matched as an Int: Age = Int where InRange(0, 150) still needs the whole of Int covered.
  • lo > hi is bynk.types.empty_range_pattern, whose fix swaps the bounds.
  • Exhaustiveness is by interval. The integers are the safe integers, and a column is split at every endpoint its patterns use, so ..-1 and 0.. cover every Int with no _ arm. A match of literals alone is not split, and stays incomplete without a _. A missing interval is reported as a pattern you can paste as an arm: 13..17, 101.., or a single value (100) when the gap is one number. An arm the earlier ones wholly cover is bynk.types.unreachable_arm; one they only partly cover is legal.
  • After is, a range directly after the keyword is bynk.types.is_range_pattern, as a literal is: is tests a type, not a value. Use a match arm, a guard or InRange.
  • A match with a range lowers to the if chain, with x >= lo && x <= hi (one side only for an open range); a match of literals alone keeps its switch.

See Match on a range of numbers.

A record is matched by its fields with a record pattern, TypeName { f1, f2: pattern, .. } (patterns track, slice 1, #2641):

match order {
Order { status: Paid, total, .. } if total > 100 => "large paid order"
Order { status: Paid, .. } => "paid"
_ => "other"
}
if o is (Order { status: Cancelled, .. }) { "cancelled" } else { "live" }
  • The type name is required. A bare field total binds a local total; status: Paid matches the field against a sub-pattern, which can be any pattern, a nested record pattern included. Record patterns nest anywhere a pattern can, as in Some(Order { total, .. }).
  • The trailing .. is required (bynk.parse.record_pattern_without_rest). A record pattern is always open: the fields it does not list are ignored, so adding a field to a record never breaks a pattern. The editor offers a one-click fix that inserts , ...
  • After is, a record pattern is parenthesised (bynk.parse.record_pattern_in_is_unparenthesised), because there the { would also open the if’s block. The editor offers a fix that adds the parentheses.
  • The type must be a record (bynk.types.record_pattern_on_non_record), every listed field must exist (bynk.types.unknown_field) and appear once (bynk.types.duplicate_pattern_field). A generic record’s type arguments are taken from the matched value and are never written.
  • A record pattern reads fields as .field does, so it is refused on another context’s exports opaque type (bynk.context.opaque_inspection).
  • Exhaustiveness is precise. Arms cover a record between them, so a match on Order { status: Paid, .. }, Order { status: Pending, .. } and Order { status: Cancelled, .. } needs no _ arm. See Exhaustiveness and reachability.

A record pattern also destructures in a let (#2654):

let Item { sku, qty, .. } = item
let Order { total, customer: Customer { email, .. }, .. } <- load(id)
let Order { status: Paid, total, .. } = order else { 0 }

The else may be left out when the pattern cannot fail (every field a name, _ or a nested pattern of the same kind); a pattern with a literal or variant field needs it (bynk.parse.let_pattern_without_else, which names the field). The names are in scope for the rest of the block. An else on a pattern that cannot fail is bynk.types.unreachable_arm, and the editor offers to remove it. See Destructure a record with let.

A lambda parameter may be an irrefutable record pattern too (#2712):

let skus = items.map((Item { sku, .. }) => sku)
let total = items.fold(0, (sum, Item { qty, price, .. }) => sum + qty * price)
let vips = orders.filter((Order { customer: Customer { vip, .. }, .. }) => vip)

It takes the place of a name, mixes freely with name parameters, and binds its names in the lambda body. The pattern must be irrefutable (bynk.parse.lambda_pattern_refutable names the field that can fail), must be a record pattern (bynk.parse.lambda_pattern_not_record) and takes no annotation (bynk.parse.lambda_pattern_annotation; the editor offers to remove it). A generic record takes its type arguments from the expected function type. Function, method and handler parameters stay plain names.