Sakura Lang

Standard library

Every module that ships with Sakura, what each function takes and returns, and the current limits.

The standard library ("std") is the set of modules that ship with Sakura: collections, text, JSON, files, HTTP, SQL, model calls, crypto and more. Use this page to look up what a module offers and what each function takes and returns.

A quick example

Common types such as List and String need no import. Other modules are imported by path, such as std/url here:

import std/url.{Url}

fn distinct_words(text: String) -> List<String> {
  List.unique(List.sort(String.split(text, " ")))
}

fn host_of(link: String) -> Option<String> {
  match Url.parse(link) {
    Ok(u) => u.host,
    Err(_) => None,
  }
}

test "distinct words, sorted" {
  expect_eq(distinct_words("to be or not to be"), ["be", "not", "or", "to"])
}

test "a URL's host" {
  expect_eq(host_of("https://Example.com/docs"), Some("example.com"))
  expect_eq(host_of("not a url"), None)
}

For examples of whole programs, see the cookbook, the capabilities tour, the contracts tour and the cassette guide. To search std offline, by name or by a type such as fn(List<A>) -> Int, use sakura doc.

How to read a signature

The signatures below are declarations, not programs you can run.

  • fn len(b: Bytes) -> Int takes a Bytes value and returns an Int.
  • ! {Http, Fail<HttpError>} after the result lists the function's effects: what it may do besides compute a value, such as send HTTP requests or fail with a typed error (Fail<HttpError>). Your function has to declare these effects too, or handle them.
  • requires … is a precondition. Calling the function with arguments that break it is a bug in the caller, reported at run time as the defect D020.
  • type declares a data type, error an error type, and effect an effect with its operations. A Handler<E> is a value that implements the effect E; install one with with, as in with Http.scripted(…) { … }, for example to answer HTTP requests from a script in a test.
  • // @resource marks a value, such as an open file, that must stay inside the callback that gave it to you; returning it is V6003. // @external marks a function the runtime implements.

Current limits

Not available yet

  • Sql.postgres is not implemented and has no release assigned. SQLite and the in-memory SQL database cover the current examples.
  • Static verification (sakura verify) covers a restricted subset of programs; see the roadmap.

Available

  • Offline test helpers (Http.recording, Llm.replay, Llm.recording, Test.fixtures), Untrusted.validate, Html.from and streaming HTTP (Http.stream, Http.read_chunk, Body, Incoming) are implemented.

Numbers

  • An Int on the JavaScript backend is exact within ±(2^53−1); on WebAssembly it is a signed 64-bit integer. Both are CLI targets; native is experimental.

Where to find things

  • Task.par_map lives in std/task, not List.
  • Env.host() takes no scope argument; use Env.only to narrow what a program may read.
  • For dense integer IDs, prefer List, as the DeltaBlue benchmark does; use Map for sparse keys. Updating a collection returns a new value, so assign the result back. The source index has complexity and behavior notes.

Untrusted input in templates

  • An Untrusted<String> (text from outside the program) placed in sql"…" becomes a bound parameter, in html"…" escaped text, and in url"…" percent-encoded through UrlPart.from.

The web API differences at the end of this page say how std's versions of the browser, Node and Bun APIs differ from the originals.

Prelude

These names are in scope in every module without an import:

KindNames
Compiler-known typesUnit Bool Int Float String Bytes Never List Map Set Range Handler Secret Untrusted
Std typesOption Result Duration Instant Uuid Json Level Violation (Violation is what validate returns)
ConstructorsSome None Ok Err (other variants are used qualified: Level.Warn, Json.String(s))
EffectsFail (compiler-known) Console Clock Random Env Log Task Test
Functionsshow expect expect_eq expect_fail expect_fails_with expect_defect expect_output expect_snapshot (the expect functions need Test, which only test/property bodies have; elsewhere they are V3001)
Tagssql html url (shell is reserved by the prelude; no std/shell exists yet)

Not in the prelude, import them: import std/retry.{Policy, retry}, import std/task.{Timeout, timeout}, import std/gen (gen.int(0, 9)), import std/graph.{Graph, NodeId}, and every other std module.

Home modules: T.f(…) and x.f(…) with x: T call f in the module that declares T; for compiler-known types it is std/<lowercase name> (List → std/list). An effect's home module is the one declaring it, and Eff.f(…) calls a home-module function when f is not an operation (Console.captured(), Clock.fixed(t), Random.seeded(1)).

Signatures

std/agent

type Agent<T, e> = { request: Request<T>, tools: List<Tool<e>>, max_steps: Int, stop: fn(Partial<T>) -> Bool }
fn run<T: Schema, e>(a: Agent<T, e>) -> T ! {Budget, Llm, Fail<LlmError | ToolError> | e} requires a.max_steps > 0

std/blob

type Blob = { bytes: Bytes, media_type: String }
type FileData = { blob: Blob, name: String, last_modified: Instant }
fn of(bytes: Bytes, media_type: String) -> Blob
fn size(b: Blob) -> Int
fn slice(b: Blob, start: Int, end: Int, media_type: String) -> Blob
fn text(b: Blob) -> Result<String, Utf8Error>
fn source<e>(b: Blob, chunk: Int) -> Source<Bytes, e> requires chunk > 0

std/budget

type Limits = { tokens: Option<Int>, usd: Option<Float>, calls: Option<Int> }
type Cost = { tokens: Int, usd: Float, calls: Int }
type Reservation = { estimate: Cost }
type BudgetKind = Tokens | Usd | Calls
error BudgetExceeded(kind: BudgetKind)
effect Budget {
  fn reserve(est: Cost) -> Reservation ! {Fail<BudgetExceeded>}
  fn settle(r: Reservation, actual: Cost) -> Unit
}
fn limits(l: Limits) -> Handler<Budget>
fn unlimited() -> Handler<Budget>
fn zero() -> Cost

std/bytes

fn len(b: Bytes) -> Int    // @external, @total
fn get(b: Bytes, i: Int) -> Option<Int>    // @external, @total
fn from_list(xs: List<Int>) -> Bytes requires List.all(xs, fn(x) { x >= 0 && x <= 255 })    // @external
fn slice(b: Bytes, start: Int, end: Int) -> Bytes    // @external
fn concat(parts: List<Bytes>) -> Bytes    // @external
type Alphabet = Standard | Url
error Base64Error(offset: Int, reason: String)
fn to_base64(b: Bytes, alphabet: Alphabet, padded: Bool) -> String
fn from_base64(text: String, alphabet: Alphabet) -> Result<Bytes, Base64Error>
fn from_base64_lenient(text: String) -> Result<Bytes, Base64Error>

std/channel

type Sender<T>    // @resource
type Receiver<T>    // @resource
type SendError = Full | Closed
fn with_channel<T, R, e>(capacity: Int, body: fn(Sender<T>, Receiver<T>) -> R ! e) -> R ! {Task | e} requires capacity > 0
fn send<T>(tx: Sender<T>, v: T) -> Result<Unit, SendError> ! {Task}
fn try_send<T>(tx: Sender<T>, v: T) -> Result<Unit, SendError> ! {Task}
fn recv<T>(rx: Receiver<T>) -> Option<T> ! {Task}
fn close<T>(tx: Sender<T>) -> Unit ! {Task}

std/cli

effect Cli {
  fn args() -> List<String>
  fn exit(code: Int) -> Never requires code >= 0 && code <= 255
}
error CliError(message: String)
fn host() -> Handler<Cli>
fn of(args: List<String>) -> Handler<Cli>
fn parse<T: Schema>(args: List<String>) -> T ! {Fail<CliError>}    // @external

std/clock

effect Clock {
  fn now() -> Instant
  fn monotonic() -> Duration
  fn sleep(d: Duration) -> Unit
  fn monotonic_micros() -> Int
}
fn host() -> Handler<Clock>    // @external
fn fixed(at: Instant) -> Handler<Clock>
fn virtual() -> Handler<Clock>

std/compress

type Format = Gzip | Deflate | DeflateRaw
type CompressionReason = Malformed(Int) | OutputLimit | Truncated
error CompressionError(reason: CompressionReason)
fn compress(b: Bytes, format: Format, level: Int) -> Bytes requires level >= 0 && level <= 9
fn decompress(b: Bytes, format: Format, max_out: Int) -> Result<Bytes, CompressionError> requires max_out >= 0
fn compress_source<T, e>(src: Source<Bytes, e>, format: Format, level: Int, body: fn(Source<Bytes, e>) -> T ! e) -> T ! e requires level >= 0 && level <= 9
fn decompress_source<T, e>(src: Source<Bytes, e>, format: Format, max_out: Int, body: fn(Source<Bytes, {Fail<CompressionError> | e}>) -> T ! {Fail<CompressionError> | e}) -> T ! {Fail<CompressionError> | e} requires max_out >= 0

std/console

effect Console {
  fn print(line: String) -> Unit
  fn read_line() -> Option<String>
  fn eprint(line: String) -> Unit
}
fn host() -> Handler<Console>    // @external
fn captured() -> Handler<Console, {Test}>
fn scripted(lines: List<String>) -> Handler<Console, {Test}>
fn alert(message: String) -> Unit ! {Console}
fn confirm(message: String) -> Bool ! {Console}
fn prompt(message: String, default: Option<String>) -> Option<String> ! {Console}

std/core

fn show<A: Show>(a: A) -> String    // @external
type Violation = { type_name: String, clause: String, value_summary: String }
type Trust

std/crypto

type Digest = Sha256 | Sha384 | Sha512
type Curve = P256 | P384 | P521
type AesLength = Aes128 | Aes256
type Algorithm = Hmac(Digest) | Hkdf(Digest) | Pbkdf2(Digest) | AesGcm(AesLength) | AesCbc(AesLength) | AesCtr(AesLength) | AesKw(AesLength) | Ecdsa(Curve) | Ecdh(Curve) | Ed25519 | X25519 | RsassaPkcs1(Digest) | RsaPss(Digest) | RsaOaep(Digest)
type Usage = Sign | Verify | DeriveBits | Encrypt | Decrypt
type KeyFormat = Raw | Pkcs8 | Spki | Jwk
type KeyKind = SecretKey | PublicKey | PrivateKey
type KeyReason = NotExtractable | NoUsages | NotAllowed(Usage) | Empty | Format(KeyFormat) | Malformed | Unavailable(String)
error KeyError(reason: KeyReason)
type CryptoReason = Length(Int) | Iterations(Int) | Info(Int) | Nonce(Int) | Tag | ZeroSecret | Padding | Unsupported(String)
error CryptoError(reason: CryptoReason)
opaque type CryptoKey = { algorithm: Algorithm, kind: KeyKind, usages: List<Usage>, extractable: Bool, material: Secret<Bytes> }
type KeyPair = { public: CryptoKey, private: CryptoKey }
type HkdfParams = { salt: Bytes, info: Bytes }
type Pbkdf2Params = { salt: Bytes, iterations: Int }
type DeriveParams = HkdfWith(HkdfParams) | Pbkdf2With(Pbkdf2Params) | EcdhWith(CryptoKey)
fn algorithm(key: CryptoKey) -> Algorithm
fn kind(key: CryptoKey) -> KeyKind
fn usages(key: CryptoKey) -> List<Usage>
fn extractable(key: CryptoKey) -> Bool
fn allows(alg: Algorithm, usage: Usage) -> Bool    // @total
fn permits(key: CryptoKey, usage: Usage) -> Bool    // @total
fn digest(alg: Digest, data: Bytes) -> Bytes
fn import_key(format: KeyFormat, alg: Algorithm, usages: List<Usage>, extractable: Bool, material: Secret<Bytes>) -> Result<CryptoKey, KeyError>
fn export_key(key: CryptoKey, format: KeyFormat) -> Result<Bytes, KeyError>
fn generate_key(alg: Algorithm, usages: List<Usage>, extractable: Bool) -> CryptoKey ! {Random} requires (is_hmac(alg) || is_aes(alg)) && usages_error(alg, SecretKey, usages) == None
fn generate_key_pair(alg: Algorithm, usages: List<Usage>, extractable: Bool) -> KeyPair ! {Random} requires curve_of(alg) != None && List.all(usages, fn(u) { allows(alg, u) }) && List.any(usages, fn(u) { u != Verify })
fn hmac(key: CryptoKey, data: Bytes) -> Bytes requires is_hmac(key.algorithm) && permits(key, Sign)
fn sign(key: CryptoKey, data: Bytes) -> Bytes ! {Random} requires signs(key.algorithm) && permits(key, Sign)
fn verify(key: CryptoKey, signature: Bytes, data: Bytes) -> Bool requires signs(key.algorithm) && permits(key, Verify)
fn encrypt(key: CryptoKey, nonce: Bytes, aad: Bytes, plaintext: Bytes) -> Result<Bytes, CryptoError> requires encrypts(key.algorithm) && permits(key, Encrypt) && (Bytes.len(aad) == 0 || takes_aad(key.algorithm))
fn decrypt(key: CryptoKey, nonce: Bytes, aad: Bytes, ciphertext: Bytes) -> Result<Bytes, CryptoError> requires encrypts(key.algorithm) && permits(key, Decrypt) && (Bytes.len(aad) == 0 || takes_aad(key.algorithm))
fn derive_bits(key: CryptoKey, params: DeriveParams, bits: Int) -> Result<Bytes, CryptoError> requires permits(key, DeriveBits) && fits(key, params)

std/decimal

type DecimalRepr = { whole: Int, frac: List<Int> }
type Decimal = DecimalRepr where is_canonical(it)
fn is_canonical(d: DecimalRepr) -> Bool    // @total
error DecimalError(input: String)
fn from_int(n: Int) -> Decimal
fn zero() -> Decimal
fn parse(text: String) -> Result<Decimal, DecimalError>
fn to_string(d: Decimal) -> String
fn add(a: Decimal, b: Decimal) -> Decimal
fn sub(a: Decimal, b: Decimal) -> Decimal
fn neg(a: Decimal) -> Decimal
fn mul(a: Decimal, b: Decimal) -> Decimal
fn div_checked(a: Decimal, b: Decimal, places: Int) -> Option<Decimal> requires places >= 0
fn round(d: Decimal, places: Int) -> Decimal requires places >= 0

std/duration

type Duration = Duration(Int)
fn millis(n: Int) -> Duration
fn seconds(n: Int) -> Duration
fn minutes(n: Int) -> Duration
fn to_millis(d: Duration) -> Int

std/encoding

type Encoding = Utf8 | Utf16Le | Utf16Be | Windows1252
type Errors = Fatal | Replace
type Bom = Strip | Keep
type EncodingReason = Unsupported(String) | Malformed(Int)
error EncodingError(reason: EncodingReason)
opaque type Decoder = { encoding: Encoding, errors: Errors, pending: Bytes, offset: Int, started: Bool }
fn parse(label: String) -> Result<Encoding, EncodingError>
fn decode(b: Bytes, enc: Encoding, errors: Errors) -> Result<String, EncodingError>
fn decode_with(b: Bytes, enc: Encoding, errors: Errors, bom: Bom) -> Result<String, EncodingError>
fn new(enc: Encoding, errors: Errors) -> Decoder
fn push(d: Decoder, chunk: Bytes) -> Result<(Decoder, String), EncodingError>
fn finish(d: Decoder) -> Result<String, EncodingError>
fn decode_source<e>(src: Source<Bytes, e>, enc: Encoding, errors: Errors) -> Source<String, {Fail<EncodingError> | e}>
fn encode_source<e>(src: Source<String, e>, enc: Encoding) -> Source<Bytes, e> requires encodable(enc)
fn encode(s: String, enc: Encoding) -> Bytes requires encodable(enc)
fn encodable(enc: Encoding) -> Bool    // @total

std/env

effect Env {
  fn get(key: String) -> Option<String>
  fn secret(key: String) -> Option<Secret<String>>
}
fn host() -> Handler<Env>
fn of(vars: Map<String, String>) -> Handler<Env>
fn only(keys: List<String>) -> Handler<Env, {Env}>

std/float

fn round(f: Float) -> Int    // @external
fn to_int_checked(f: Float) -> Option<Int>    // @external
fn sqrt(f: Float) -> Float    // @external
fn format(f: Float, decimals: Int) -> String requires decimals >= 0    // @external
fn is_nan(f: Float) -> Bool

std/form

type Part = Text(String) | File(FileData)
type Form = { entries: List<(String, Part)> }
type FormLimits = { max_parts: Int, max_bytes: Int, max_field_bytes: Int }
type FormLimit = MaxParts | MaxBytes | MaxFieldBytes
type FormReason = Limit(FormLimit) | ContentType | Malformed(Int)
error FormError(reason: FormReason)
fn encode_urlencoded(f: Form) -> String
fn parse_urlencoded(text: String) -> Form
fn encode_multipart(f: Form, boundary: String) -> Bytes requires is_boundary(boundary)
fn boundary() -> String ! {Random}
fn is_boundary(s: String) -> Bool    // @total
fn parse_multipart(body: Bytes, content_type: String, limits: FormLimits) -> Result<Form, FormError>

std/fs

type Dir
type Entry = { name: String, is_dir: Bool }
type Mode = Read | Write | Append
opaque type File = { id: Int, path: Path, mode: Mode }    // @resource
error FsError(path: String, reason: String)
effect Fs {
  fn root() -> Dir
  fn read(path: Path) -> Bytes ! {Fail<FsError>}
  fn read_text(path: Path) -> Untrusted<String> ! {Fail<FsError>}
  fn write(path: Path, data: Bytes) -> Unit ! {Fail<FsError>}
  fn list(dir: Path) -> List<Entry> ! {Fail<FsError>}
  fn exists(path: Path) -> Bool
  fn with_file<T, e>(path: Path, mode: Mode, body: fn(File) -> T ! e) -> T ! {Fail<FsError> | e}
  fn read_chunk(file: File, max: Int) -> Bytes ! {Fail<FsError>} requires max > 0
  fn write_chunk(file: File, data: Bytes) -> Unit ! {Fail<FsError>}
}
fn host() -> Handler<Fs>
fn rooted(dir: Dir) -> Handler<Fs>
fn subdir(d: Dir, name: String) -> Dir ! {Fail<FsError>}
fn memory(files: List<(Path, Bytes)>) -> Handler<Fs>
type MemoryEntry = Contents(Bytes) | Directory
fn memory_tree(entries: List<(Path, MemoryEntry)>) -> Handler<Fs>
fn read_all(file: File) -> Bytes ! {Fs, Fail<FsError>}
fn read_up_to(path: Path, limit: Int) -> Bytes ! {Fs, Fail<FsError>} requires limit >= 0
fn file_source(file: File, chunk: Int) -> Source<Bytes, {Fs, Fail<FsError>}> requires chunk > 0
fn file_sink(file: File) -> Sink<Bytes, {Fs, Fail<FsError>}>

std/gen

type Gen<A> = { sample: fn(Int) -> A ! {Random} }
fn int(lo: Int, hi: Int) -> Gen<Int> requires lo <= hi
fn bool() -> Gen<Bool>
fn one_of<A>(choices: List<A>) -> Gen<A> requires List.len(choices) > 0
fn list<A>(item: Gen<A>, max_len: Int) -> Gen<List<A>> requires max_len >= 0
fn string(max_len: Int) -> Gen<String> requires max_len >= 0
fn map<A, B>(g: Gen<A>, f: fn(A) -> B) -> Gen<B>
fn flat_map<A, B>(g: Gen<A>, f: fn(A) -> Gen<B>) -> Gen<B>
fn pair<A, B>(a: Gen<A>, b: Gen<B>) -> Gen<(A, B)>
fn for_all<A: Show, e>(g: Gen<A>, runs: Int, prop: fn(A) -> Unit ! {Test | e}) -> Unit ! {Random, Test | e}

std/graph

type NodeId = NodeId(Int)
type Graph<N> = { nodes: Map<Int, N>, edges: Map<Int, List<NodeId>>, next: Int }
fn empty<N>() -> Graph<N>
fn insert<N>(g: Graph<N>, n: N) -> (Graph<N>, NodeId)
fn get<N>(g: Graph<N>, id: NodeId) -> Option<N>    // @total
fn connect<N>(g: Graph<N>, a: NodeId, b: NodeId) -> Graph<N> requires get(g, a).is_some() && get(g, b).is_some()
fn neighbors<N>(g: Graph<N>, id: NodeId) -> List<NodeId>
fn len<N>(g: Graph<N>) -> Int

std/headers

type HeaderReason = InvalidName | InvalidValue
error HeaderError(name: String, reason: HeaderReason)
opaque type Headers = Headers(List<(String, String)>)
fn of(list: List<(String, String)>) -> Result<Headers, HeaderError>
fn get(h: Headers, name: String) -> Option<String>
fn get_set_cookie(h: Headers) -> List<String>
fn get_all(h: Headers, name: String) -> List<String>
fn has(h: Headers, name: String) -> Bool
fn append(h: Headers, name: String, value: String) -> Result<Headers, HeaderError>
fn set(h: Headers, name: String, value: String) -> Result<Headers, HeaderError>
fn remove(h: Headers, name: String) -> Headers
fn entries(h: Headers) -> List<(String, String)>
fn to_list(h: Headers) -> List<(String, String)>

std/html

opaque type Html = Html(String)
fn text(s: String) -> Html
fn untrusted(u: Untrusted<String>) -> Html
fn raw(markup: String, reason: Trust) -> Html
fn from<T: Show>(v: T) -> Html
fn concat(parts: List<Html>) -> Html
fn to_string(h: Html) -> String
fn template(parts: List<String>, args: List<Html>) -> Html

std/http

type Matcher = Any | Path(String) | Method(Method)
error RateLimited(retry_after: Option<Duration>)
type Body    // @resource
type Incoming = { status: Status, headers: List<(String, String)>, body: Body }
effect Http {
  fn send(req: Request) -> Response ! {Fail<HttpError>}
  fn stream<T, e>(req: Request, body: fn(Incoming) -> T ! e) -> T ! {Fail<HttpError> | e}
  fn read_chunk(body: Body, max: Int) -> Bytes ! {Fail<HttpError>} requires max > 0
}
fn body_source(body: Body, chunk: Int) -> Source<Bytes, {Http, Fail<HttpError>}> requires chunk > 0
fn get(url: Url) -> Response ! {Http, Fail<HttpError | RateLimited>}
fn post_json<T: Schema>(url: Url, body: T) -> Response ! {Http, Fail<HttpError | RateLimited>}
fn bearer(req: Request, token: Secret<String>) -> Request
fn host() -> Handler<Http>
fn scoped(hosts: List<String>) -> Handler<Http, {Http}>
fn recording(path: Path) -> Handler<Http, {Fs, Http}>
opaque type Cassette = { path: Path, id: Int }
fn cassette(path: Path) -> Cassette
fn open(c: Cassette) -> Cassette ! {Fs, Fail<HttpError>}
fn replaying(c: Cassette) -> Handler<Http, {Fs, Http}>
fn scripted(script: List<(Matcher, Response)>) -> Handler<Http>
fn sequence(script: List<(Matcher, Response)>) -> Handler<Http>

std/instant

type Instant = Instant(Int)
error TimeError(input: String)
fn from_unix_millis(ms: Int) -> Instant
fn to_unix_millis(i: Instant) -> Int
fn add(i: Instant, d: Duration) -> Instant
fn diff(a: Instant, b: Instant) -> Duration
fn format_iso(i: Instant) -> String
fn parse(text: String) -> Result<Instant, TimeError>

std/int

fn to_float(i: Int) -> Float    // @external
fn to_string(i: Int) -> String    // @external
fn checked_add(a: Int, b: Int) -> Option<Int>    // @external
fn wrapping_add(a: Int, b: Int) -> Int    // @external
fn abs(i: Int) -> Int    // @total
fn min(a: Int, b: Int) -> Int    // @total
fn max(a: Int, b: Int) -> Int    // @total
fn clamp(i: Int, lo: Int, hi: Int) -> Int requires lo <= hi
fn pow(base: Int, exp: Int) -> Int requires exp >= 0

std/json

type Json = Null | Bool(Bool) | Number(Float) | String(String) | Array(List<Json>) | Object(Map<String, Json>)
error DecodeError(path: String, message: String)
fn encode<T: Schema>(value: T) -> String    // @external
fn decode<T: Schema>(text: String) -> Result<T, DecodeError>    // @external
fn parse(text: String) -> Result<Json, DecodeError>    // @external
fn schema<T: Schema>(witness: Option<T>) -> Json    // @external
fn render(j: Json, indent: Option<Int>) -> String
fn get(j: Json, key: String) -> Option<Json>
fn get_string(j: Json, key: String) -> Option<String>

std/list

fn len<A>(xs: List<A>) -> Int    // @external, @total
fn get<A>(xs: List<A>, i: Int) -> Option<A>    // @external, @total
fn push<A>(xs: List<A>, x: A) -> List<A>    // @external
fn set<A>(xs: List<A>, i: Int, x: A) -> List<A> requires 0 <= i && i < len(xs)
fn slice<A>(xs: List<A>, start: Int, end: Int) -> List<A>    // @external
fn empty<A>() -> List<A>
fn concat<A>(a: List<A>, b: List<A>) -> List<A>
fn map<A, B, e>(xs: List<A>, f: fn(A) -> B ! e) -> List<B> ! e
fn filter<A, e>(xs: List<A>, f: fn(A) -> Bool ! e) -> List<A> ! e
fn filter_map<A, B, e>(xs: List<A>, f: fn(A) -> Option<B> ! e) -> List<B> ! e
fn flat_map<A, B, e>(xs: List<A>, f: fn(A) -> List<B> ! e) -> List<B> ! e
fn fold<A, B, e>(xs: List<A>, init: B, f: fn(B, A) -> B ! e) -> B ! e
fn find<A, e>(xs: List<A>, f: fn(A) -> Bool ! e) -> Option<A> ! e
fn all<A, e>(xs: List<A>, f: fn(A) -> Bool ! e) -> Bool ! e    // @total
fn any<A, e>(xs: List<A>, f: fn(A) -> Bool ! e) -> Bool ! e    // @total
fn sort<A: Ord>(xs: List<A>) -> List<A>
fn sort_by<A, K: Ord>(xs: List<A>, key: fn(A) -> K) -> List<A>
fn zip<A, B>(a: List<A>, b: List<B>) -> List<(A, B)>
fn enumerate<A>(xs: List<A>) -> List<(Int, A)>
fn reverse<A>(xs: List<A>) -> List<A>
fn join(xs: List<String>, sep: String) -> String
fn sum(xs: List<Int>) -> Int
fn first<A>(xs: List<A>) -> Option<A>    // @total
fn last<A>(xs: List<A>) -> Option<A>    // @total
fn contains<A: Eq>(xs: List<A>, x: A) -> Bool    // @total
fn unique<A: Hash>(xs: List<A>) -> List<A>
fn range(start: Int, end: Int) -> List<Int>

std/llm

type Model = Model(String)
type Request<T> = { system: String, user: Prompt, model: Model, max_tokens: Int, temperature: Float }
error Refused
error InvalidOutput(violations: List<Violation>)
error Truncated
error ProviderError(status: Int, reason: String)
type LlmError = Refused | InvalidOutput | Truncated | RateLimited | Timeout | ProviderError | BudgetExceeded
type ToolSpec = { name: String, description: String, schema: Json }
type ToolCall = { id: String, name: String, input: Json }
type ToolResult = { id: String, output: Json }
type Turn = Asked(List<ToolCall>) | Answered(List<ToolResult>)
type Step<T> = Answer(T) | Use(List<ToolCall>)
type Partial<T> = { text: String, step: Int, calls: List<ToolCall> }
effect Llm {
  fn generate<T: Schema>(req: Request<T>) -> T ! {Fail<LlmError>}
  fn generate_text(req: Request<String>) -> Untrusted<String> ! {Fail<LlmError>}
  fn stream<T: Schema, e>(req: Request<T>, on_partial: fn(Partial<T>) -> Unit ! e) -> T ! {Fail<LlmError> | e}
  fn step<T: Schema>(req: Request<T>, tools: List<ToolSpec>, transcript: List<Turn>) -> Step<T> ! {Fail<LlmError>}
}
fn request<T: Schema>(system: String, user: Prompt) -> Request<T>
fn of(name: String) -> Model
fn default() -> Model
fn anthropic(key: Secret<String>, model: Model) -> Handler<Llm, {Budget, Http}>
fn anthropic_at(base: Url, key: Secret<String>, model: Model) -> Handler<Llm, {Budget, Http}>
fn recording(path: Path, provider: Handler<Llm, {Budget, Http}>) -> Handler<Llm, {Fs, Http}>
fn replay(path: Path) -> Handler<Llm, {Fs}>
fn scripted(responses: List<String>) -> Handler<Llm>

std/log

type Level = Debug | Info | Warn | Error
effect Log {
  fn event(level: Level, message: String, fields: List<(String, Json)>) -> Unit
}
fn stderr() -> Handler<Log>    // @external
fn host() -> Handler<Log>
fn json() -> Handler<Log>    // @external
fn captured() -> Handler<Log, {Test}>

std/map

fn empty<K: Hash, V>() -> Map<K, V>    // @external
fn get<K: Hash, V>(m: Map<K, V>, k: K) -> Option<V>    // @external, @total
fn insert<K: Hash, V>(m: Map<K, V>, k: K, v: V) -> Map<K, V>    // @external
fn remove<K: Hash, V>(m: Map<K, V>, k: K) -> Map<K, V>    // @external
fn len<K: Hash, V>(m: Map<K, V>) -> Int    // @external, @total
fn entries<K: Hash, V>(m: Map<K, V>) -> List<(K, V)>    // @external
fn of<K: Hash, V>(pairs: List<(K, V)>) -> Map<K, V>
fn contains<K: Hash, V>(m: Map<K, V>, k: K) -> Bool    // @total
fn update<K: Hash, V, e>(m: Map<K, V>, k: K, f: fn(Option<V>) -> V ! e) -> Map<K, V> ! e
fn keys<K: Hash, V>(m: Map<K, V>) -> List<K>
fn values<K: Hash, V>(m: Map<K, V>) -> List<V>

std/option

type Option<A> = None | Some(A)
fn map<A, B, e>(o: Option<A>, f: fn(A) -> B ! e) -> Option<B> ! e
fn unwrap_or<A>(o: Option<A>, default: A) -> A
fn or_fail<A, E>(o: Option<A>, err: E) -> A ! {Fail<E>}
fn expect<A>(o: Option<A>, msg: String) -> A    // @external
fn is_some<A>(o: Option<A>) -> Bool    // @total

std/path

type Path = String where is_relative(it)
fn is_relative(s: String) -> Bool    // @total
fn of(s: String) -> Path requires is_relative(s)
fn join(p: Path, rest: String) -> Path requires is_relative(rest)
fn to_string(p: Path) -> String

std/prompt

type PromptPart = Text(String) | Untrusted(Untrusted<String>) | Image(Bytes)
opaque type Prompt = Prompt(List<PromptPart>)
fn of(parts: List<PromptPart>) -> Prompt
fn text(s: String) -> Prompt
fn parts(p: Prompt) -> List<PromptPart>

std/random

effect Random {
  fn int(lo: Int, hi: Int) -> Int requires lo <= hi
  fn float() -> Float
  fn bytes(n: Int) -> Bytes requires n >= 0
  fn uuid() -> Uuid
}
fn host() -> Handler<Random>    // @external
fn seeded(seed: Int) -> Handler<Random>

std/request

type Method = Get | Head | Post | Put | Patch | Delete | Options | Trace
type Payload = Empty | Text(String) | Bytes(Bytes)
type Redirect = Follow | Manual | Error
type Request = { method: Method, url: Url, headers: List<(String, String)>, body: Payload, redirect: Redirect, secret_headers: List<(String, Secret<String>)>, params: List<(String, String)> }
error BadRequest(detail: String)
fn of(method: Method, url: Url) -> Request
fn post(path: String, body: String) -> Request
fn post_json<T: Schema>(url: Url, body: T) -> Request
fn with_payload(req: Request, body: Payload) -> Request
fn with_header(req: Request, name: String, value: String) -> Request
fn with_headers(req: Request, h: Headers) -> Request
fn bytes(req: Request, limit: Int) -> Bytes ! {Fail<BadRequest>}
fn text(req: Request, limit: Int) -> String ! {Fail<BadRequest>}
fn json<T: Schema>(req: Request, limit: Int) -> T ! {Fail<BadRequest>}
fn param(req: Request, name: String) -> Option<String>
fn header(req: Request, name: String) -> Option<String>

std/response

type Status = Int where it >= 100 && it <= 599
type Response = { status: Status, headers: List<(String, String)>, body: Payload }
error HttpError(status: Option<Status>, reason: String)
fn status(code: Int, body: String) -> Response requires code >= 100 && code <= 599
fn status_json<T: Schema>(code: Int, value: T) -> Response requires code >= 100 && code <= 599
fn ok_json<T: Schema>(value: T) -> Response
fn html(h: Html) -> Response
fn json<T: Schema>(r: Response, limit: Int) -> T ! {Fail<DecodeError | HttpError>}
fn text(r: Response, limit: Int) -> Untrusted<String> ! {Fail<HttpError>}
fn bytes(r: Response, limit: Int) -> Bytes ! {Fail<HttpError>}

std/result

type Result<A, E> = Ok(A) | Err(E)
fn map<A, B, E, e>(r: Result<A, E>, f: fn(A) -> B ! e) -> Result<B, E> ! e
fn map_err<A, E, F>(r: Result<A, E>, f: fn(E) -> F) -> Result<A, F>
fn unwrap_or<A, E>(r: Result<A, E>, default: A) -> A
fn raise<A, E>(r: Result<A, E>) -> A ! {Fail<E>}
fn is_ok<A, E>(r: Result<A, E>) -> Bool    // @total
fn is_err<A, E>(r: Result<A, E>) -> Bool    // @total
fn ok<A, E>(r: Result<A, E>) -> Option<A>    // @total
fn err<A, E>(r: Result<A, E>) -> Option<E>    // @total

std/retry

type Policy<E> = { retry_on: fn(E) -> Bool, max_attempts: Int, backoff: Duration, jitter: Bool, deadline: Option<Duration> }
fn policy<E>(retry_on: fn(E) -> Bool, max_attempts: Int) -> Policy<E> requires max_attempts >= 1
fn retry<T, E, e>(p: Policy<E>, action: fn() -> T ! {Fail<E> | e}) -> T ! {Clock, Random, Fail<E> | e}

std/router

opaque type Router<e> = { routes: List<Route<e>> }
fn new<e>() -> Router<e>
fn route<e>(r: Router<e>, method: Method, pattern: String, h: fn(Request) -> Response ! e) -> Router<e> requires UrlPattern.compile(pattern).is_ok()
fn get<e>(r: Router<e>, pattern: String, h: fn(Request) -> Response ! e) -> Router<e> requires UrlPattern.compile(pattern).is_ok()
fn post<e>(r: Router<e>, pattern: String, h: fn(Request) -> Response ! e) -> Router<e> requires UrlPattern.compile(pattern).is_ok()
fn put<e>(r: Router<e>, pattern: String, h: fn(Request) -> Response ! e) -> Router<e> requires UrlPattern.compile(pattern).is_ok()
fn delete<e>(r: Router<e>, pattern: String, h: fn(Request) -> Response ! e) -> Router<e> requires UrlPattern.compile(pattern).is_ok()
fn handle<e>(r: Router<e>, req: Request) -> Response ! e

std/searchparams

opaque type SearchParams = SearchParams(List<(String, String)>)
fn parse(query: String) -> SearchParams
fn get(sp: SearchParams, name: String) -> Option<String>
fn get_all(sp: SearchParams, name: String) -> List<String>
fn has(sp: SearchParams, name: String) -> Bool
fn append(sp: SearchParams, name: String, value: String) -> SearchParams
fn set(sp: SearchParams, name: String, value: String) -> SearchParams
fn remove(sp: SearchParams, name: String) -> SearchParams
fn sort(sp: SearchParams) -> SearchParams
fn entries(sp: SearchParams) -> List<(String, String)>
fn to_string(sp: SearchParams) -> String

std/secret

fn of<T>(value: T) -> Secret<T>    // @external
fn expose<T>(s: Secret<T>, reason: Trust) -> T
fn map<T, U>(s: Secret<T>, f: fn(T) -> U, reason: Trust) -> Secret<U>

std/serve

type Address = { host: String, port: Int }
error ServeError(reason: String)
effect Serve {
  fn serve<e>(handle: fn(Request) -> Response ! e, addr: Address) -> Never ! {Fail<ServeError> | e}
}
fn listen<e>(router: Router<e>, addr: Address) -> Never ! {Serve, Fail<ServeError> | e}
fn of(host: String, port: Int) -> Address requires port >= 0 && port <= 65_535
fn host() -> Handler<Serve>
fn scripted(requests: List<Request>) -> Handler<Serve, {Test}>

std/set

fn empty<A: Hash>() -> Set<A>    // @external
fn insert<A: Hash>(s: Set<A>, x: A) -> Set<A>    // @external
fn contains<A: Hash>(s: Set<A>, x: A) -> Bool    // @external, @total
fn len<A: Hash>(s: Set<A>) -> Int    // @external, @total
fn to_list<A: Hash>(s: Set<A>) -> List<A>    // @external
fn of<A: Hash>(xs: List<A>) -> Set<A>

std/sql

type SqlValue = Null | Int(Int) | Float(Float) | Text(String) | Blob(Bytes)
fn from<T: Schema>(value: T) -> SqlValue
opaque type Query<R> = { text: String, params: List<SqlValue> }
error SqlError(message: String)
effect Sql {
  fn query<R: Schema>(q: Query<R>) -> List<R> ! {Fail<SqlError>}
  fn execute(q: Query<Unit>) -> Int ! {Fail<SqlError>}
  fn transaction<T, e>(body: fn() -> T ! {Sql | e}) -> T ! {Fail<SqlError> | e}
}
fn template<R>(parts: List<String>, args: List<SqlValue>) -> Query<R>
fn migrate(statements: List<Query<Unit>>) -> Unit ! {Sql, Fail<SqlError>}
fn sqlite(path: Path) -> Handler<Sql, {Fs}>    // @external
fn memory() -> Handler<Sql>    // @external

std/stream

type Step<T, e> = Done | Next(T, Source<T, e>)
type Source<T, e> = { pull: fn() -> Step<T, e> ! e }
type Sink<T, e> = { write: fn(T) -> Sink<T, e> ! e, close: fn() -> Unit ! e }
type StreamReason = MaxItems | MaxLine
error StreamError(reason: StreamReason)
fn empty<T, e>() -> Source<T, e>
fn from_list<T, e>(xs: List<T>) -> Source<T, e>
fn map<A, B, e>(src: Source<A, e>, f: fn(A) -> B ! e) -> Source<B, e>
fn filter<T, e>(src: Source<T, e>, keep: fn(T) -> Bool ! e) -> Source<T, e>
fn take<T, e>(src: Source<T, e>, n: Int) -> Source<T, e> requires n >= 0
fn fold<T, A, e>(src: Source<T, e>, init: A, f: fn(A, T) -> A ! e) -> A ! e
fn each<T, e>(src: Source<T, e>, f: fn(T) -> Unit ! e) -> Unit ! e
fn to_list<T, e>(src: Source<T, e>, max_items: Int) -> List<T> ! {Fail<StreamError> | e} requires max_items >= 0
fn chunks<e>(src: Source<Bytes, e>, size: Int) -> Source<Bytes, e> requires size > 0
fn lines<e>(src: Source<String, e>, max_line: Int) -> Source<String, {Fail<StreamError> | e}>
fn pipe<T, e>(src: Source<T, e>, sink: Sink<T, e>) -> Unit ! e
fn buffer<T, R, e>(src: Source<T, e>, capacity: Int, body: fn(Source<T, {Task | e}>) -> R ! {Task | e}) -> R ! {Task | e} requires capacity > 0
fn tee<T, R, e>(src: Source<T, e>, max_lag: Int, body: fn(Source<T, {Task | e}>, Source<T, {Task | e}>) -> R ! {Task | e}) -> R ! {Task | e} requires max_lag > 0

std/string

error Utf8Error(offset: Int)
fn len(s: String) -> Int    // @external, @total
fn chars(s: String) -> List<String>    // @external
fn graphemes(s: String) -> List<String>    // @external
fn split(s: String, sep: String) -> List<String>    // @external
fn trim(s: String) -> String    // @external
fn starts_with(s: String, prefix: String) -> Bool    // @external, @total
fn ends_with(s: String, suffix: String) -> Bool    // @external, @total
fn contains(s: String, needle: String) -> Bool    // @external, @total
fn replace(s: String, from: String, to: String) -> String    // @external
fn to_lower(s: String) -> String    // @external
fn to_upper(s: String) -> String    // @external
fn parse_int(s: String) -> Option<Int>    // @external
fn parse_float(s: String) -> Option<Float>    // @external
fn to_bytes(s: String) -> Bytes    // @external
fn from_bytes(b: Bytes) -> Result<String, Utf8Error>    // @external
fn slice(s: String, start: Int, end: Int) -> String    // @external
fn repeat(s: String, n: Int) -> String requires n >= 0
fn pad_left(s: String, width: Int, fill: String) -> String requires len(fill) > 0

std/task

type Scope
type Fiber<T>
effect Task {
  fn scope<T, e>(body: fn(Scope) -> T ! e) -> T ! e
  fn spawn<T, e>(s: Scope, body: fn() -> T ! e) -> Fiber<T> ! e
  fn join<T>(f: Fiber<T>) -> T
  fn all<T, e>(bodies: List<fn() -> T ! e>) -> List<T> ! e
  fn race<T, e>(bodies: List<fn() -> T ! e>) -> T ! e
  fn yield_now() -> Unit
  fn cancel<T>(f: Fiber<T>) -> Unit
  fn cancelled(s: Scope) -> Bool
}
fn host() -> Handler<Task>    // @external
fn deterministic(seed: Int) -> Handler<Task>    // @external
error Timeout(limit: Duration)
fn timeout<T, e>(limit: Duration, action: fn() -> T ! e) -> T ! {Clock, Task, Fail<Timeout> | e}
fn every<e>(period: Duration, body: fn(Int) -> Bool ! e) -> Unit ! {Clock, Task | e}
fn par_map<A, B, e>(xs: List<A>, f: fn(A) -> B ! e) -> List<B> ! {Task | e}

std/test

effect Test {
  fn record_failure(message: String) -> Unit
  fn failures() -> Int
  fn output(line: String) -> Unit
  fn output_lines() -> List<String>
  fn snapshot(name: String, rendered: String) -> Unit
  fn fixtures() -> Dir
}
fn expect(cond: Bool) -> Unit ! {Test}
fn expect_eq<A: Eq + Show>(actual: A, expected: A) -> Unit ! {Test}
fn expect_fail<T, E: Eq + Show, e>(body: fn() -> T ! {Fail<E> | e}, err: E) -> Unit ! {Test | e}
fn expect_fails_with<T, E: Show, e>(body: fn() -> T ! {Fail<E> | e}, pred: fn(E) -> Bool) -> Unit ! {Test | e}
fn expect_defect<T, e>(body: fn() -> T ! e) -> Unit ! {Test | e}    // @external
fn expect_output(lines: List<String>) -> Unit ! {Test}
fn expect_snapshot<A: Show>(name: String, value: A) -> Unit ! {Test}

std/tool

opaque type Tool<e> = { spec: ToolSpec, run: fn(Json) -> Json ! {Fail<ToolError> | e} }
error ToolError(tool: String, tag: String, payload: Json)
fn from<A: Schema, R: Schema, E: Schema + Show, e>(name: String, description: String, f: fn(A) -> R ! {Fail<E> | e}) -> Tool<e>
fn name<e>(t: Tool<e>) -> String
fn spec<e>(t: Tool<e>) -> ToolSpec
fn call<e>(t: Tool<e>, input: Json) -> Json ! {Fail<ToolError> | e}

std/unit

fn ignore<A>(a: A) -> Unit

std/untrusted

fn of<T>(value: T) -> Untrusted<T>    // @external
fn validate<T, V>(u: Untrusted<T>) -> Result<V, Violation>    // @external
fn trust<T>(u: Untrusted<T>, reason: Trust) -> T
fn check<T>(u: Untrusted<T>, clause: String, pred: fn(T) -> Bool) -> Result<T, Violation>
fn len(u: Untrusted<String>) -> Int

std/url

type Url = String where is_valid(it)
fn is_valid(s: String) -> Bool    // @total
fn host(u: Url) -> Option<String>
fn path(u: Url) -> String
fn query_param(u: Url, name: String) -> Option<String>
fn template(parts: List<String>, args: List<UrlPart>) -> Url
fn encode_component(s: String) -> String
type UrlReason = Idna | InvalidScheme | InvalidHost | InvalidPort | Relative | OpaquePath
error UrlError(reason: UrlReason)
type UrlParts = { scheme: String, username: String, password: Option<Secret<String>>, host: Option<String>, port: Option<Int>, path: String, query: Option<String>, fragment: Option<String> }
fn parse(s: String) -> Result<UrlParts, UrlError>
fn resolve(base: UrlParts, relative: String) -> Result<UrlParts, UrlError>
fn to_string(p: UrlParts) -> String
fn to_url(p: UrlParts) -> Url requires is_valid(to_string(p))
fn origin(p: UrlParts) -> String
fn with_scheme(p: UrlParts, scheme: String) -> Result<UrlParts, UrlError>
fn with_host(p: UrlParts, host: String) -> Result<UrlParts, UrlError>
fn with_port(p: UrlParts, port: Option<Int>) -> Result<UrlParts, UrlError>
fn with_path(p: UrlParts, path: String) -> Result<UrlParts, UrlError>
fn with_query(p: UrlParts, query: Option<String>) -> UrlParts
fn with_fragment(p: UrlParts, fragment: Option<String>) -> UrlParts
fn with_credentials(p: UrlParts, username: String, password: Option<Secret<String>>) -> Result<UrlParts, UrlError>    // @trust
fn search(p: UrlParts) -> SearchParams
fn with_search(p: UrlParts, sp: SearchParams) -> UrlParts

std/urlpart

opaque type UrlPart = UrlPart(String)
fn from<T: Show>(v: T) -> UrlPart
fn to_string(p: UrlPart) -> String

std/urlpattern

type PatternReason = Unsupported(String) | Duplicate(String) | Limit
error PatternError(reason: PatternReason)
opaque type UrlPattern = { origin: Option<Origin>, parts: List<Part> }
type UrlMatch = { groups: List<(String, String)> }
fn compile(pattern: String) -> Result<UrlPattern, PatternError>
fn exec(p: UrlPattern, url: Url) -> Option<UrlMatch>

std/uuid

type Uuid = String where is_canonical(it)
error UuidError(input: String)
fn to_string(u: Uuid) -> String
fn parse(text: String) -> Result<Uuid, UuidError>
fn from_canonical(text: String) -> Uuid requires is_canonical(text)
fn is_canonical(text: String) -> Bool    // @total

std/websocket

type Message = Text(String) | Binary(Bytes)
type CloseInfo = { code: Int, reason: String, clean: Bool }
type Received = Data(Message) | Closed(CloseInfo)
type SocketReason = Connect(String) | MessageTooLarge | NotOpen | Failed(String) | Accept(String)
error SocketError(reason: SocketReason)
type Options = { subprotocols: List<String>, headers: List<(String, String)>, max_message: Int }
fn options() -> Options
type Upgrade = { subprotocol: Option<String>, origins: List<String>, headers: List<(String, String)>, max_message: Int }
fn upgrade() -> Upgrade
type Handshake = { key: String, subprotocols: List<String>, origin: Option<String> }
opaque type Socket = { id: Int, protocol: String, max_message: Int }    // @resource
fn protocol(sock: Socket) -> String
effect WebSocket {
  fn connect<T, e>(url: String, options: Options, body: fn(Socket) -> T ! e) -> T ! {Fail<SocketError> | e} requires options.max_message > 0
  fn send(sock: Socket, message: Message) -> Unit ! {Fail<SocketError>}
  fn receive(sock: Socket) -> Received ! {Fail<SocketError>}
  fn close(sock: Socket, code: Int, reason: String) -> Unit ! {Fail<SocketError>} requires closable(code, reason)
  fn accept<e>(req: Request, options: Upgrade, body: fn(Socket) -> Unit ! e) -> Response ! {Fail<SocketError> | e} requires options.max_message > 0
  fn subscribe(sock: Socket, topic: String) -> Unit ! {Fail<SocketError>} requires String.len(topic) <= 256
  fn unsubscribe(sock: Socket, topic: String) -> Unit ! {Fail<SocketError>} requires String.len(topic) <= 256
  fn publish(topic: String, message: Message, except: Option<Socket>) -> Int ! {Fail<SocketError>} requires String.len(topic) <= 256
}
fn handshake(req: Request) -> Result<Handshake, String>
fn upgrade_request(path: String, subprotocols: List<String>) -> Request
fn closable(code: Int, reason: String) -> Bool    // @total
fn messages(sock: Socket) -> Source<Message, {WebSocket, Fail<SocketError>}>
fn host() -> Handler<WebSocket>
type ScriptStep = Reply(Message, Message) | Push(Message) | Close(Int, String)
fn scripted(script: List<ScriptStep>) -> Handler<WebSocket>

std/worker (experimental)

type Permissions = { fs_read: List<String>, fs_write: List<String>, net: List<String>, env: List<String> }
opaque type Grants = { table: Permissions }
fn none() -> Grants
fn of(table: Permissions) -> Grants
type WorkerReason = GrantExceeded | Limit | Defect(String) | Codec
error WorkerError(reason: WorkerReason)
type Received<T> = Message(T) | Finished | Failed(WorkerError)
opaque type Port<S, R> = { id: Int, sends: Bool, tx: Option<Sender<String>>, rx: Option<Receiver<String>> }    // @resource
type WorkerHandle<I, O> = Port<I, O>
type Inbox<I> = Port<Never, I>
type Outbox<O> = Port<O, Never>
opaque type Topic<T> = { name: String }
effect Worker {
  fn start<I, O, R, e>(entry: fn(Inbox<I>, Outbox<O>) -> Unit ! e, named: List<fn(Inbox<I>, Outbox<O>) -> Unit ! e>, grants: Grants, body: fn(WorkerHandle<I, O>) -> R ! e) -> Result<R, WorkerError> ! e
  fn post<S, R>(p: Port<S, R>, text: String) -> Result<Unit, SendError>
  fn take<S, R>(p: Port<S, R>) -> Received<String>
  fn publish_text(name: String, text: String) -> Result<Unit, SendError>
  fn subscribe_text<R, e>(name: String, capacity: Int, body: fn(Inbox<String>) -> R ! e) -> R ! e
  fn close<S, R>(p: Port<S, R>) -> Unit
}
fn spawn<I: Schema, O: Schema, R, e>(entry: fn(Inbox<I>, Outbox<O>) -> Unit ! {Worker | e}, grants: Grants, body: fn(WorkerHandle<I, O>) -> R ! {Worker | e}) -> Result<R, WorkerError> ! {Worker | e}
fn send<S: Schema, R>(p: Port<S, R>, m: S) -> Result<Unit, SendError> ! {Worker}
fn recv<S, R: Schema>(p: Port<S, R>) -> Received<R> ! {Worker}
fn topic<T: Schema>(name: String) -> Topic<T> requires String.len(name) <= 256
fn publish<T: Schema>(t: Topic<T>, m: T) -> Result<Unit, SendError> ! {Worker}
fn subscribe<T: Schema, R, e>(t: Topic<T>, capacity: Int, body: fn(Inbox<T>) -> R ! {Worker | e}) -> R ! {Worker | e} requires capacity > 0
fn inline() -> Handler<Worker, {Task}>
fn host() -> Handler<Worker>

Web API differences

std offers the web platform's APIs, the ones browsers, Node and Bun provide, as typed Sakura values. This section maps each one to its Sakura name and says where the behavior differs. The full design is RFC 0002.

Bytes and text

  • Uint8Array is Bytes, which is immutable, so an in-place write is Bytes.from_list(List.set(...)).
  • TextEncoder.encodeInto has no counterpart, because there is no caller-owned buffer.
  • btoa takes bytes, so text goes through String.to_bytes first.
  • Encoding.encode writes UTF-8 and UTF-16 only, since Windows-1252 cannot encode every string.

URLs

  • URL is Url.parse and Url.resolve, which give a UrlParts value, and URLSearchParams is SearchParams.
  • The setters are with_* functions that return a new value, so there is no live url.searchParams: read Url.search and write Url.with_search.
  • A host that needs IDNA (non-ASCII, or an xn-- label) is UrlError(Idna) until punycode lands.
  • The password is a Secret, which to_string leaves out.
  • Url stays the prefix check that url"…" and Request.url use.

Crypto

  • crypto.subtle is std/crypto, synchronous and pure.
  • importKey takes the material as Secret<Bytes>, and a CryptoKey is never Show.
  • verify is reserved as a bare name, so call it crypto.verify(key, tag, data) or key.verify(tag, data).
  • A key without the operation's usage is the defect D020, not an error value.
  • A key's type is crypto.kind(key), a KeyKind (SecretKey, PublicKey or PrivateKey), because type is a Sakura keyword.
  • Web Crypto's generateKey returns a key or a CryptoKeyPair depending on the algorithm. Sakura's generate_key makes only HMAC and AES-GCM keys, and generate_key_pair returns a KeyPair { public, private }, because a function has one result type.
  • An AES-GCM nonce (Web Crypto's iv) is exactly 12 bytes, from Random.bytes(12). Any other length is CryptoError(Nonce(n)) on every backend, because 96 bits is the bound the lowest host supports and a longer nonce is a different construction with a weaker bound.
  • An RSA-OAEP seed must be unpredictable as well as fresh (Random.bytes(n), never a counter): a seed an attacker can guess lets them confirm a guessed plaintext by sealing it themselves.
  • ECDSA is P-256 with SHA-256 only (JOSE ES256) and takes no hash parameter, because the curve fixes the hash.
  • ECDSA signatures are r || s (64 bytes) but are not the same bytes on every backend (OpenSSL's random nonce through node:crypto on JS and WASM, RFC 6979 on native, and neither is promised), so compare them with verify, never by value.
  • On --target wasm every primitive runs in the Node host through hosted imports, which a WASI command does not have.
  • The sign_webhook recipe verifies an HMAC signature.

Headers, blobs and forms

  • Headers is a validated value over the List<(String, String)> that Request.headers and Response.headers keep: Headers.of to read, to_list to write back.
  • get on set-cookie is None, since cookies are never joined; read get_set_cookie.
  • Credentials stay in Request.secret_headers.
  • Blob and File are the values Blob and FileData, which name no file on disk.
  • Blob.text is strict UTF-8 (Utf8Error) where the web substitutes U+FFFD.
  • Blob.stream() is Blob.source(b, chunk).
  • FormData is Form, and Response.formData() is Form.parse_multipart with a required FormLimits.

URL patterns

  • URLPattern is UrlPattern, a subset with no regular expressions, so a pattern matches alike on every target: whole-segment :name groups, * for one segment and ** for any number, on a path or behind a literal scheme, host and port.
  • The standard's * is .* and crosses /. Sakura's * is exactly one segment and ** is any number, because ** already covers a tree and a route author does not expect /files/* to match one.
  • The standard is exact about a trailing slash. UrlPattern ignores empty segments on both sides, so /users/7/ matches /users/:id, because that is the contract Router routes already had.
  • Regexp groups, {…} groups, modifiers and a group inside a segment are PatternError(Unsupported).
  • A pattern has at most 4,096 bytes and 64 groups.
  • exec returns the groups only, in pattern order, unnamed ones as "0", "1", ….
  • Router routes are these patterns, and a route pattern UrlPattern.compile rejects is the defect D020.

Streams

  • ReadableStream is std/stream's Source<T, e>, a value whose pull returns Done or Next(item, rest), and WritableStream is Sink<T, e>.
  • The web's readers, writers, controllers and locks have no counterpart. A web stream is locked so that consumers aliasing it do not interleave; a Sakura source is a value that one instance pulls on one thread.
  • A pure source (Source.from_list, Blob.source) reads the same items each time it is pulled.
  • Http.body_source, Fs.file_source and Fs.file_sink are views over a body or file, valid only inside the callback that opened it (V6003).
  • A transform is a function from source to source. TextDecoderStream and TextEncoderStream are Encoding.decode_source and encode_source.
  • to_list and lines take a required bound and fail StreamError past it.
  • ReadableStream.tee is Source.tee and CountQueuingStrategy is Source.buffer, both over std/channel.
  • ByteLengthQueuingStrategy has no counterpart: Source.chunks(src, size) before buffer bounds bytes, because chunks re-cuts bytes to exactly size and buffer counts items.
  • BYOB readers and byte controllers are not provided, because Sakura has no caller-owned buffer to read into.

WebSockets

  • WebSocket is the effect of std/websocket.
  • The Bun.serve upgrade is WebSocket.accept(req, options, body) inside a Serve handler, on the client's Socket and operations, after the pure WebSocket.handshake(req). server.upgrade's data and the open/message/close/drain callbacks are not provided, because the body is a function of the socket and every event is a value receive returns.
  • Bun's topics are subscribe, unsubscribe and publish(topic, message, except), instance-local, and a publisher never waits: a subscriber whose send buffer holds max_message bytes misses the message.
  • origins refuses every browser origin it does not name, unlike Bun, because a browser sends the victim's cookies with the upgrade.
  • idleTimeout, sendPings and perMessageDeflate are not mirrored: an idle policy is Task.timeout around receive, and no extension is negotiated.
  • SAKURA_MAX_SOCKETS (1,024) bounds the open sockets of both roles.
  • onopen, onmessage, onclose and addEventListener are not provided. open is WebSocket.connect's callback, and message and close are the values receive returns (Data(Text(s)), Data(Binary(b)), Closed(CloseInfo), the close returned again by every later receive), because Sakura has no event listeners and a returned value is matched exhaustively. Data wraps the Message because one module cannot declare Text and Binary twice.
  • bufferedAmount and readyState are not provided, since send waits while the buffer is full and receive reports the close.
  • permessage-deflate and every other extension are refused in the handshake, so WebSocket.extensions has no counterpart, because an inflated frame would be a decompression surface outside the max_message bound.
  • Credentials have no secret_headers field yet: Options.headers are plain strings, so a Secret reaches one only through Secret.expose, because a secret-carrying handshake import waits for the owner's sign-off.
  • max_message (16 MiB by default) bounds both directions and the receive queue. The connection stops reading while 64 received messages, or more than max_message bytes of them, wait, and a ping is answered only while the send buffer needs no drain, so a ping flood cannot grow it.
  • net covers ws (port 80) and wss (443). The opening handshake follows no redirect.
  • Native executables run WebSocket from v1.0.0-beta.6 (experimental with the target).
  • The websocket_server and websocket_client recipes show both roles.

Channels

  • MessageChannel and MessagePort are std/channel's with_channel(capacity, body), whose body receives a Sender and a Receiver. Both are resources, so neither leaves the callback.
  • send waits while capacity items are queued, try_send fails Full instead, and recv waits while empty and is None once closed and drained.
  • There is no onmessage listener, postMessage transfer list or structuredClone, because a message is a value that recv returns and values are copied by assignment.
  • with is a keyword, so the RFC's Channel.with is with_channel.
  • BroadcastChannel is Worker.topic (experimental, below).
  • CountQueuingStrategy is Source.buffer(src, capacity, body) and ReadableStream.tee is Source.tee(src, max_lag, body), both over a channel with a producer task.
  • The source a buffer, tee or decompress_source body receives reads Done once that callback returns, so keep it inside the callback. V6003 does not catch this, because the source holds no resource type.
  • A byte bound is chunks before buffer, so ByteLengthQueuingStrategy has no counterpart.
  • A program in which every task waits ends with the defect D090.

Workers (experimental)

Workers are experimental and outside the 1.0 contract.

  • Worker (new Worker) is std/worker's Worker.spawn(entry, grants, body), where entry is a function declared @worker that runs as a second instance of the program with its own heap and root handlers.
  • postMessage is send, and onmessage and ErrorEvent are the Message and Failed values recv returns. Messages cross through the Schema codec, so there is no structuredClone or transfer list, and a Secret cannot cross.
  • ShadowRealm is a worker with Grants.none(). Grants are a subset of the parent's [permissions], checked at spawn.
  • BroadcastChannel is Worker.topic with publish and subscribe.
  • terminate() is the end of spawn's callback. Worker.close(p) ends one direction, as MessagePort.close does.
  • At most 16 workers are live per instance.
  • Worker.inline() runs a worker as a fiber for tests on every target. Live workers and topics run on every target: as threads on JavaScript and on WebAssembly under Node, and as OS threads on native.
  • A stopped native worker keeps its thread until its next wait. A pure loop can keep spawn from returning, and granted Fs writes can continue until that wait.
  • Worker grant paths must match the manifest's exact strings: "./data" and "data" do not match.
  • A native worker whose entry leaves to the runtime an effect native does not serve (Llm, Serve, WebSocket, and Http through v1.0.0-beta.3) is refused at its start, and its parent reads Failed(WorkerError(Defect("exit 75"))).

Compression

  • CompressionStream and DecompressionStream are std/compress's compress_source and decompress_source, callback-shaped like the other views; compress and decompress work on whole Bytes.
  • The formats are the web's three: Gzip, Deflate and DeflateRaw.
  • Decompression takes a required max_out and fails CompressionError(OutputLimit) past it, so a small input cannot expand without bound. Malformed input is Malformed(offset) and a cut-off stream Truncated.
  • Trailing data and a second gzip member are refused, as in DecompressionStream.
  • Compressed bytes may differ between backends, but each backend decompresses the others' output.
  • The stream_lines recipe reads a gzipped log.

For contributors

The compiler embeds this standard library. Each module's source is checked, and its tests run, by sakura test --std. This page is generated from compiler/std/INDEX.md by bun scripts/generate-stdlib.mjs, run from website/.

Edit on GitHub

Last updated

On this page