veko-lang.org
Download Free EPUB 3.0

Part V · Complete Tooling, CLI & Standard Library Reference

Appendix B.4

Standard Library Reference: Reactor, Web, Zero-FFI SQLite & DBs, Scope, OTel, Flamegraphs, Desktop UI/Wayland/X11 & FFI

Complete AST-verified API reference for 32 networking, web, Zero-FFI SQLite & indexed KV, structured concurrency, OTel, profiling, UI/Wayland/X11, and FFI modules

Connected systems, databases, profiling & desktop UI stack: reactor, conc/scope, otel, profile/flamegraph, net/*, web, html, db/{sqlite,kv,query,postgres,redis,sidecar}, durable/*, tui, ui/{canvas,font,layout,widgets,wayland,x11}, ui, and opt-in ffi.

Module (use [...])Source FileCapabilitiesTypesFunctions
codec/http3lib/codec/http3.vkZero host capabilities120
conc/scopelib/conc/scope.vkZero host capabilities14
db/kvlib/db/kv.vk..fs216
db/postgreslib/db/postgres.vk..net, ..clocks734
db/querylib/db/query.vkZero host capabilities18
db/redislib/db/redis.vk..net, ..clocks421
db/sidecarlib/db/sidecar.vk..clocks, ..fs, ..exec27
db/sqlitelib/db/sqlite.vk..fs523
durable/objectlib/durable/object.vk..clocks521
durable/workflowlib/durable/workflow.vk..clocks322
durablelib/durable.vkZero host capabilities08
ffilib/ffi.vk..env, ..fs, ..ffi215
htmllib/html.vkZero host capabilities142
net/clientlib/net/client.vk..clocks, ..net416
net/dnslib/net/dns.vk..net, ..fs212
net/http2lib/net/http2.vkZero host capabilities315
net/http3lib/net/http3.vk..net, ..clocks224
net/iplib/net/ip.vkZero host capabilities28
net/tls13lib/net/tls13.vk..fs, ..net, ..clocks021
net/websocketlib/net/websocket.vkZero host capabilities214
otellib/otel.vkZero host capabilities311
profile/flamegraphlib/profile/flamegraph.vkZero host capabilities24
reactorlib/reactor.vk..net, ..clocks434
tuilib/tui.vkZero host capabilities336
ui/canvaslib/ui/canvas.vkZero host capabilities231
ui/fontlib/ui/font.vkZero host capabilities08
ui/layoutlib/ui/layout.vkZero host capabilities413
ui/waylandlib/ui/wayland.vkZero host capabilities220
ui/widgetslib/ui/widgets.vkZero host capabilities1482
ui/x11lib/ui/x11.vkZero host capabilities38
uilib/ui.vk..ui240
weblib/web.vk..fs, ..net, ..clocks862

Module codec/http3

Exported Structs & Interfaces

  • H3Frame: H3Frame = struct { ftype i64, payload bytes } — Decoded HTTP/3 frame (ftype + payload).

Exported Functions

SymbolSignatureDescription
stream-controlstream-control = fn [] i64HTTP/3 unidirectional stream types (RFC 9114 Section 6.2).
stream-pushstream-push = fn [] i64Exported codec/http3/stream-push operation.
stream-qpack-encoderstream-qpack-encoder = fn [] i64Exported codec/http3/stream-qpack-encoder operation.
stream-qpack-decoderstream-qpack-decoder = fn [] i64Exported codec/http3/stream-qpack-decoder operation.
frame-dataframe-data = fn [] i64HTTP/3 frame types (RFC 9114 Section 7.2).
frame-headersframe-headers = fn [] i64Exported codec/http3/frame-headers operation.
frame-cancel-pushframe-cancel-push = fn [] i64Exported codec/http3/frame-cancel-push operation.
frame-settingsframe-settings = fn [] i64Exported codec/http3/frame-settings operation.
frame-push-promiseframe-push-promise = fn [] i64Exported codec/http3/frame-push-promise operation.
frame-goawayframe-goaway = fn [] i64Exported codec/http3/frame-goaway operation.
frame-max-push-idframe-max-push-id = fn [] i64Exported codec/http3/frame-max-push-id operation.
push-varintpush-varint = fn [mut out bytes, v i64] anyAppends a 62-bit non-negative QUIC/HTTP/3 variable-length integer onto out.
encode-varintencode-varint = fn [v i64] bytesEncodes v into a standalone variable-length integer bytes slice.
decode-varintdecode-varint = fn [b bytes, pos i64] anyDecodes one QUIC/HTTP/3 variable-length integer at pos, returning { val, next }.
encode-frameencode-frame = fn [f H3Frame] bytesEncodes an HTTP/3 H3Frame (varint(type) || varint(length) || payload).
decode-frame-atdecode-frame-at = fn [wire bytes, pos i64] anyDecodes a single HTTP/3 H3Frame at pos, returning { frame, next }.
encode-settings-frameencode-settings-frame = fn [settings map[i64]] bytesEncodes HTTP/3 SETTINGS (map[i64] ID -> value) into a SETTINGS frame (0x04).
decode-settings-payloaddecode-settings-payload = fn [payload bytes] map[i64]Decodes an HTTP/3 SETTINGS payload into map[i64].
qpack-encodeqpack-encode = fn [headers block[h2/Header]] bytesEncodes headers (block[h2/Header]) into a stateless RFC 9204 QPACK field section (RIC = 0, Delta Base = 0).
qpack-decodeqpack-decode = fn [field_bytes bytes] block[h2/Header]Decodes an RFC 9204 QPACK field section (Required Insert Count == 0 static + literal + Huffman) into block[h2/Header].

Verified Doctest (codec/http3/encode-varint)

VEKO
use [h3 = codec/http3]
b1 = h3/encode-varint 37
b2 = h3/encode-varint 15293
b4 = h3/encode-varint 494878333
d1 = h3/decode-varint b1 0
d2 = h3/decode-varint b2 0
d4 = h3/decode-varint b4 0
if d1.val != 37 or d2.val != 15293 or d4.val != 494878333 [ err 'varint' ] else [ .ok ]

Module conc/scope

Exported Structs & Interfaces

  • Scope: Scope = struct { tasks block } — Structured group of spawned task handles.

Exported Functions

SymbolSignatureDescription
newnew = fn [] ScopeCreates a new empty structured concurrency Scope.
addadd = fn [mut s Scope, task_handle any]Registers a spawned task handle (spawn [ ... ]) with s.
await-allawait-all = fn [mut s Scope] blockAwaits all tasks in s in registration order, draining every handle even if an earlier task errored, and returns the ordered block of results (or the first err encountered).
await-settledawait-settled = fn [mut s Scope] mapAwaits all tasks in s and returns { ok = block, errors = block } without short-circuiting.

Verified Doctest (conc/scope/new)

VEKO
use [sc = conc/scope]
mut grp = sc/new
sc/add mut grp (spawn [ 10 + 11 ])
sc/add mut grp (spawn [ 20 + 1 ])
res = sc/await-all mut grp
if (len res) != 2 or res[0] != 21 or res[1] != 21 [ err 'scope await-all' ] else [ .ok ]

Module db/kv

Exported Structs & Interfaces

  • KvStore: KvStore = struct { path str, fd i64, write_off i64, entries map[bytes], durable bool, wal_records i64 } — Open handle to an embedded crash-safe KV store.
  • BatchOp: BatchOp = struct { op enum, key str, val bytes = ... } — Single batch mutation (op = .put or .del).

Exported Functions

SymbolSignatureDescription
openopen = fn [path str] KvStoreOpens or creates a durable (fsync-on-write) crash-safe KV store at path.
open-fastopen-fast = fn [path str] KvStoreOpens or creates a KV store with deferred fsync (call kv/sync to flush durability).
syncsync = fn [db KvStore] enumFlushes all buffered WAL writes to stable storage via os/fsync.
closeclose = fn [mut db KvStore] enumCloses the underlying file descriptor.
put-bytesput-bytes = fn [mut db KvStore, key str, val bytes] enumStores raw bytes under key with CRC-32 WAL framing.
get-bytesget-bytes = fn [db KvStore, key str] bytesRetrieves raw bytes for key, or returns err if absent (combine with /or).
put-valput-val = fn [mut db KvStore, key str, val any] enumStores any Veko value (i64, str, bytes, block, map, etc.) encoded via codec/vbin.
get-valget-val = fn [db KvStore, key str] anyRetrieves and decodes a codec/vbin value stored under key.
deletedelete = fn [mut db KvStore, key str] enumDeletes key by appending a tombstone WAL record.
has?has? = fn [db KvStore, key str] boolReturns true if key currently exists in db.
keyskeys = fn [db KvStore] block[str]Returns all live keys in deterministic sorted order.
scan-prefixscan-prefix = fn [db KvStore, prefix str] block[str]Returns all live keys starting with prefix in deterministic sorted order.
batchbatch = fn [mut db KvStore, ops block[BatchOp]] enumAtomically commits a batch of BatchOp puts/deletes in a single WAL write + fsync.
put-sealedput-sealed = fn [mut db KvStore, key str, enc_key32 bytes, plaintext bytes] enumEncrypts plaintext with AES-256-GCM (crypto/seal, binding key as AAD) and stores the sealed envelope.
with-open-sealedwith-open-sealed = fn [db KvStore, key str, enc_key32 bytes, use_fn fn[bytes->any]] anyUnseals an encrypted entry under enc_key32, passes plaintext to use_fn, and zeroizes it on exit.
compactcompact = fn [mut db KvStore] enumCompacts the WAL by rewriting only live keys into a temporary file, syncing, atomically renaming, and reopening.

Verified Doctest (db/kv/open)

VEKO
use [kv = db/kv]
p = str/join [(os/temp-dir) '/veko_kv_doctest_1.vkkv'] ''
_ = os/remove/or p [.ok]
mut db = kv/open p
_ = kv/put-val mut db 'user:1' { name = 'Ada', score = 99 }
_ = kv/close mut db
mut db2 = kv/open p
u = kv/get-val db2 'user:1'
_ = kv/close mut db2
_ = os/remove/or p [.ok]
if u.name != 'Ada' or u.score != 99 [ err 'kv reopen' ] else [ .ok ]

Module db/postgres

Exported Structs & Interfaces

  • PgMsg: PgMsg = struct { tag i64, body bytes } — Raw PostgreSQL v3 backend message (tag ASCII byte + body payload).
  • PgConn: PgConn = struct { stream io/Stream, server_params map[str], backend_pid i64, backend_key i64, tx_status i64, transport_kind enum = ... } — Connected PostgreSQL session state over an io/Stream.
  • PgConfig: PgConfig = struct { host str = ..., port i64 = ..., user str = ..., password str = ..., database str = ..., ssl_mode enum = ..., tls_opts map = ..., connect_timeout dur = ..., io_timeout dur = ... } — Connection & TLS 1.3 configuration for connect and new-pool.
  • PgPool: PgPool = struct { cfg PgConfig, max_conns i64, acquire_timeout dur = ..., max_idle_ns i64 = ..., health_check_ns i64 = ..., sem_ch any, idle_ch any } — Thread-safe channel-backed PostgreSQL connection pool (stores closure-free transport slots across spawn workers).
  • PgResult: PgResult = struct { columns block[str], rows block[block], command_tag str } — Query result containing column names, row data (str or .null), and command completion tag.
  • ScramServerFirst: ScramServerFirst = struct { nonce str, salt bytes, iters i64, raw str } — Parsed SCRAM-SHA-256 server-first challenge fields.
  • ScramProof: ScramProof = struct { client_final str, expected_server bytes } — Computed SCRAM-SHA-256 client-final proof + expected server signature.

Exported Functions

SymbolSignatureDescription
encode-startupencode-startup = fn [user str, database str] bytesEncodes a PostgreSQL v3.0 StartupMessage (len(u32) || 196608(u32) || k\0v\0... || \0).
encode-msgencode-msg = fn [tag i64, payload bytes] bytesEncodes a typed PostgreSQL frontend message (tag(u8) || len(u32) || payload).
encode-queryencode-query = fn [sql str] bytesEncodes a Simple Query ('Q') message.
encode-passwordencode-password = fn [password str] bytesEncodes a PasswordMessage ('p') for cleartext auth.
encode-sasl-initialencode-sasl-initial = fn [mech str, client_first bytes] bytesEncodes a SASLInitialResponse ('p') selecting mech (e.g. 'SCRAM-SHA-256').
encode-sasl-responseencode-sasl-response = fn [client_final bytes] bytesEncodes a SASLResponse ('p') carrying client-final bytes.
encode-terminateencode-terminate = fn [] bytesEncodes a Terminate ('X') message.
read-msgread-msg = fn [mut stream io/Stream] PgMsgReads one PostgreSQL backend message (tag(1B) || len(4B) || body) from stream.
decode-row-descriptiondecode-row-description = fn [body bytes] block[str]Decodes a RowDescription ('T') payload into a block of column names.
decode-data-rowdecode-data-row = fn [body bytes] blockDecodes a DataRow ('D') payload into a block of strings (or .null for SQL NULL).
decode-error-fieldsdecode-error-fields = fn [body bytes] map[str]Decodes an ErrorResponse ('E') or NoticeResponse ('N') payload into a field map.
scram-client-firstscram-client-first = fn [user str, client_nonce str] strFormats the SCRAM-SHA-256 client-first message ('n,,n=<user>,r=<nonce>').
scram-parse-server-firstscram-parse-server-first = fn [msg str] ScramServerFirstParses a SCRAM-SHA-256 server-first message ('r=<nonce>,s=<b64salt>,i=<iters>').
scram-compute-proofscram-compute-proof = fn [password str, client_first str, sf ScramServerFirst] ScramProofComputes the RFC 7677 SCRAM-SHA-256 client-final message and expected server signature.
scram-verify-server-finalscram-verify-server-final = fn [server_final str, expected_server bytes] boolVerifies the server-final SCRAM-SHA-256 message ('v=<b64sig>') in constant time.
md5-password-hashmd5-password-hash = fn [user str, password str, salt4 bytes] strComputes PostgreSQL's md5 password authenticator ('md5' + hex(md5(hex(md5(password + user)) + salt4))).
encode-ssl-requestencode-ssl-request = fn [] bytesEncodes PostgreSQL's 8-byte SSLRequest startup packet (len=8 || 80877103).
connect-streamconnect-stream = fn [mut stream io/Stream, user str, password str, database str] PgConnPerforms the PostgreSQL v3.0 startup and authentication handshake over stream.
queryquery = fn [mut conn PgConn, sql str] PgResultExecutes a Simple Query ('Q') on conn and collects all returned rows until ReadyForQuery.
closeclose = fn [mut conn PgConn] enumSends a Terminate ('X') message and closes the underlying io/Stream.
connectconnect = fn [cfg PgConfig] PgConnConnects to PostgreSQL over TCP with optional SSLRequest -> TLS 1.3 upgrade (ssl_mode in .disable, .prefer, .require).
encode-parseencode-parse = fn [stmt_name str, sql str] bytesEncodes a Parse ('P') frontend message for $1, $2, ... parameterized SQL.
encode-bindencode-bind = fn [portal_name str, stmt_name str, params block] bytesEncodes a Bind ('B') frontend message binding params (str, i64, f64, bool, bytes, or .null).
encode-describe-portalencode-describe-portal = fn [portal_name str] bytesEncodes a Describe ('D') message for portal portal_name.
encode-executeencode-execute = fn [portal_name str, max_rows i64] bytesEncodes an Execute ('E') message (max_rows = 0 for all rows).
encode-syncencode-sync = fn [] bytesEncodes a Sync ('S') message ending an Extended Query pipeline.
query-paramsquery-params = fn [mut conn PgConn, sql str, params block] PgResultExecutes a SQL-injection-safe parameterized query ($1, $2, ...) using the Extended Query Protocol (Parse+Bind+Describe+Execute+Sync).
prepareprepare = fn [mut conn PgConn, stmt_name str, sql str] enumPrepares a named server-side statement stmt_name for sql.
query-preparedquery-prepared = fn [mut conn PgConn, stmt_name str, params block] PgResultExecutes a previously prepared statement stmt_name with params.
rows-to-mapsrows-to-maps = fn [res PgResult] block[map]Converts a PgResult into a block of maps keyed by res.columns.
with-txwith-tx = fn [mut conn PgConn, work_fn any] anyRuns (work_fn mut conn) inside a BEGIN / COMMIT / ROLLBACK transaction (automatically using SAVEPOINT when nested!).
new-poolnew-pool = fn [cfg PgConfig, /max max_conns i64] PgPoolCreates a thread-safe PgPool bounded to max_conns concurrent connections (safe to share across spawn workers).
with-connwith-conn = fn [pool PgPool, work_fn any] anyBorrows a healthy PgConn from pool (validating health & rolling back dirty transactions), runs (work_fn mut conn), and returns it.
close-poolclose-pool = fn [pool PgPool] i64Drains and closes all idle connections in pool.

Verified Doctest (db/postgres/encode-startup)

VEKO
use [pg = db/postgres]
m = pg/encode-startup 'veko' 'appdb'
if (bytes/get-u32-be m 0) != (len m) or (bytes/get-u32-be m 4) != 196608 [ err 'pg startup' ] else [ .ok ]

Module db/query

Exported Structs & Interfaces

  • Table: Table = struct { name str, pk_field str, indexed_fields block[str] } — Schema descriptor for a secondary-indexed KV table.

Exported Functions

SymbolSignatureDescription
define-tabledefine-table = fn [name str, pk_field str, indexed_fields block[str]] TableDefines a logical Table over a kv/KvStore with primary-key field pk_field and indexed_fields.
put-rowput-row = fn [mut db kv/KvStore, tbl Table, row map] enumInserts or updates row (a map containing tbl.pk_field), atomically updating all secondary indexes.
get-rowget-row = fn [db kv/KvStore, tbl Table, pk str] anyFetches a single row by primary key pk, or returns err if not found (combine with /or).
delete-rowdelete-row = fn [mut db kv/KvStore, tbl Table, pk str] enumDeletes pk from tbl along with all of its secondary index entries atomically.
scan-allscan-all = fn [db kv/KvStore, tbl Table] blockScans all rows in tbl in deterministic primary-key order.
where-eqwhere-eq = fn [db kv/KvStore, tbl Table, field str, value any] blockQueries all rows where row[field] == value (uses secondary index when field is indexed, or fallback scan).
query-filterquery-filter = fn [db kv/KvStore, tbl Table, pred any, max_rows i64] blockFilters rows in tbl matching pred (fn [row] bool) with optional /limit max_rows.
count-rowscount-rows = fn [db kv/KvStore, tbl Table] i64Counts total live rows in tbl.

Verified Doctest (db/query/define-table)

VEKO
use [kv = db/kv, q = db/query]
p = str/join [(os/temp-dir) '/veko_db_query_doctest.vkkv'] ''
_ = os/remove/or p [.ok]
mut db = kv/open-fast p
users = q/define-table 'users' 'id' ['role' 'region']
_ = q/put-row mut db users { id = 'u1', name = 'Ada', role = 'admin', region = 'ca-west' }
_ = q/put-row mut db users { id = 'u2', name = 'Lin', role = 'dev',   region = 'ca-west' }
_ = q/put-row mut db users { id = 'u3', name = 'Kai', role = 'admin', region = 'eu-north' }
admins = q/where-eq db users 'role' 'admin'
_ = kv/close mut db
_ = os/remove/or p [.ok]
if (len admins) != 2 or admins[0].name != 'Ada' or admins[1].name != 'Kai' [ err 'where-eq' ] else [ .ok ]

Module db/redis

Exported Structs & Interfaces

  • DecodedResp: DecodedResp = struct { value any, consumed i64 } — Decoded RESP value along with the number of bytes consumed from the wire buffer.
  • RedisClient: RedisClient = struct { stream io/Stream, rx_buf bytes, transport_kind enum = ... } — Connected Redis client wrapping an io/Stream and read buffer.
  • RedisConfig: RedisConfig = struct { host str = ..., port i64 = ..., username str = ..., password str = ..., db i64 = ..., tls bool = ..., tls_opts map = ..., resp3 bool = ..., connect_timeout dur = ..., io_timeout dur = ... } — Connection, TLS 1.3, ACL authentication, and RESP3 negotiation options for connect and new-pool.
  • RedisPool: RedisPool = struct { cfg RedisConfig, max_conns i64, acquire_timeout dur = ..., max_idle_ns i64 = ..., health_check_ns i64 = ..., sem_ch any, idle_ch any } — Thread-safe channel-backed Redis connection pool (safe to share across spawn workers).

Exported Functions

SymbolSignatureDescription
encode-commandencode-command = fn [args block] bytesEncodes a Redis command (block of strings) as a RESP array of bulk strings (*N\r\n$L\r\n...).
encode-valueencode-value = fn [v any] bytesEncodes a Veko value into RESP3 wire bytes (useful for both clients and mock/embedded RESP3 servers).
decode-bytesdecode-bytes = fn [raw bytes] DecodedRespDecodes one RESP3 / RESP2 value from raw bytes.
from-streamfrom-stream = fn [stream io/Stream] RedisClientWraps an io/Stream (TCP, TLS 1.3, or memory) in a RedisClient.
cmdcmd = fn [mut cli RedisClient, args block] anySends a single Redis command and returns the decoded RESP3/RESP2 reply (rejecting .secret leakage).
pingping = fn [mut cli RedisClient] anySends PING (returns 'PONG').
getget = fn [mut cli RedisClient, key str] anySends GET key (returns string or .null).
setset = fn [mut cli RedisClient, key str, val str] anySends SET key val.
deldel = fn [mut cli RedisClient, key str] anySends DEL key.
hsethset = fn [mut cli RedisClient, key str, field str, val str] anySends HSET key field val.
hgethget = fn [mut cli RedisClient, key str, field str] anySends HGET key field.
pipelinepipeline = fn [mut cli RedisClient, cmds block[block]] blockPipelines multiple commands in a single write and reads all replies in order.
closeclose = fn [mut cli RedisClient] enumCloses the underlying io/Stream.
set-exset-ex = fn [mut cli RedisClient, key str, val str, ttl_sec i64] anySends SET key val EX ttl_sec.
incrincr = fn [mut cli RedisClient, key str] anySends INCR key (returns incremented i64).
expireexpire = fn [mut cli RedisClient, key str, ttl_sec i64] anySends EXPIRE key ttl_sec.
connectconnect = fn [cfg RedisConfig] RedisClientConnects to Redis over TCP or TLS 1.3 (cfg.tls == true), performing optional ACL AUTH, HELLO 3, and SELECT db.
with-txwith-tx = fn [mut cli RedisClient, work_fn any] anyExecutes (work_fn mut cli) inside a MULTI / EXEC transaction (sending DISCARD if work_fn returns err).
new-poolnew-pool = fn [cfg RedisConfig, /max max_conns i64] RedisPoolCreates a thread-safe RedisPool bounded to max_conns concurrent connections (safe across spawn workers).
with-connwith-conn = fn [pool RedisPool, work_fn any] anyBorrows a healthy RedisClient from pool (probing PING -> 'PONG' & auto-reconnecting on stale sockets), runs (work_fn mut cli), and returns it.
close-poolclose-pool = fn [pool RedisPool] i64Drains and closes all idle connections in pool.

Verified Doctest (db/redis/encode-command)

VEKO
use [redis = db/redis]
wire = redis/encode-command ['SET' 'k1' 'hello']
if (bytes/to-str wire) != '*3\r\n$3\r\nSET\r\n$2\r\nk1\r\n$5\r\nhello\r\n' [ err 'resp enc' ] else [ .ok ]

Module db/sidecar

Exported Structs & Interfaces

  • SidecarReq: SidecarReq = struct { id i64, method str, params map } — Framed sidecar RPC request message.
  • SidecarResp: SidecarResp = struct { id i64, ok bool, result any, error_msg str } — Framed sidecar RPC response message.

Exported Functions

SymbolSignatureDescription
encode-frameencode-frame = fn [payload_val any] bytesEncodes any Veko value into a 'VKSC' CRC-32-verified binary RPC frame.
decode-framedecode-frame = fn [wire bytes] anyDecodes and verifies a 'VKSC' CRC-32-framed codec/vbin payload.
encode-reqencode-req = fn [req SidecarReq] bytesEncodes a SidecarReq into a 'VKSC' frame.
decode-reqdecode-req = fn [wire bytes] SidecarReqDecodes a 'VKSC' frame into a SidecarReq.
encode-respencode-resp = fn [resp SidecarResp] bytesEncodes a SidecarResp into a 'VKSC' frame.
decode-respdecode-resp = fn [wire bytes] SidecarRespDecodes a 'VKSC' frame into a SidecarResp.
call-execcall-exec = fn [bin_path str, req SidecarReq] SidecarRespInvokes an .exec-gated sidecar executable passing request/response frame file paths.

Verified Doctest (db/sidecar/encode-frame)

VEKO
use [sc = db/sidecar]
req = sc/SidecarReq { id = 7, method = 'sql.query', params = { sql = 'SELECT 1' } }
wire = sc/encode-req req
dec = sc/decode-req wire
if dec.id != 7 or dec.method != 'sql.query' [ err 'sidecar roundtrip' ] else [ .ok ]

Module db/sqlite

Exported Structs & Interfaces

  • ColumnDef: ColumnDef = struct { name str, col_type str = ..., is_pk bool = ..., is_int_pk bool = ..., is_unique bool = ..., is_indexed bool = ..., not_null bool = ..., has_default bool = ..., default_val any = ... } — Column schema definition in a SQLite table.
  • IndexDef: IndexDef = struct { name str, table str, column str, is_unique bool = ..., sql str = ... } — Index metadata stored in sqlite_schema and backed by an index B-tree (0x0a / 0x02).
  • TableStore: TableStore = struct { name str, columns block[ColumnDef], sql str, next_id i64 = ..., row_ids block = ..., rows map = ..., idx_cache map = ... } — In-memory representation of a loaded/mutable SQLite table (rowid -> row map + ordered rowids).
  • TableSpec: TableSpec = struct { name str, pk_col str = ..., columns block[ColumnDef] } — Declarative homoiconic ORM model returned by define-table.
  • SqliteDb: SqliteDb = struct { path str = ..., page_size i64 = ..., change_counter i64 = ..., schema_cookie i64 = ..., user_version i64 = ..., table_order block = ..., tables map = ..., index_order block = ..., indexes map = ..., in_tx bool = ..., tx_snapshot bytes = ..., raw_img bytes = ..., table_roots map = ..., index_roots map = ..., btree_dirty bool = ... } — Handle to an open pure-Veko SQLite 3 database (file-backed or :memory:).

Exported Functions

SymbolSignatureDescription
put-varintput-varint = fn [mut buf bytes, v i64]Exported db/sqlite/put-varint operation.
read-varintread-varint = fn [buf bytes, off i64] mapExported db/sqlite/read-varint operation.
seek-table-rowidseek-table-rowid = fn [db_bytes bytes, page_size i64, usable_size i64, root_pg i64, target_rid i64] any$O(\log N)$ binary-search lookup of a single target_rid directly across 0x05 interior & 0x0d leaf table B-tree pages.
seek-index-btreeseek-index-btree = fn [db_bytes bytes, page_size i64, usable_size i64, pg_num i64, op str, target_val any, mut out_rids block]$O(\log N + K)$ binary-search seek across 0x02 interior and 0x0a leaf SQLite index B-tree pages (=, <, <=, >, >=).
to-bytesto-bytes = fn [db SqliteDb] bytesExported db/sqlite/to-bytes operation.
from-bytesfrom-bytes = fn [raw bytes] SqliteDbDecodes a standard binary SQLite 3 image (raw) into an in-memory SqliteDb.
encode-rollback-journalencode-rollback-journal = fn [orig_existed bool, page_size i64, orig_img bytes, new_img bytes] bytesBuilds a CRC-32-verified hot rollback journal (VKJRNL01) capturing all dirty/truncated original pages.
verify-rollback-journalverify-rollback-journal = fn [jraw bytes] mapValidates a VKJRNL01 hot rollback journal image and returns { orig_existed, page_size, orig_size, records } or err.
recover-journalrecover-journal = fn [db_path str] enumReplays and cleans up any hot rollback journal (<db_path>-journal) left by an interrupted commit.
openopen = fn [path str] SqliteDbOpens an existing .sqlite / .db file from disk (automatically recovering <path>-journal if present), creates a new file-backed database if it doesn't exist yet, or creates an in-memory database when path == ':memory:'.
savesave = fn [mut db SqliteDb] enumAtomically flushes db to disk using a CRC-32 hot rollback journal (<path>-journal) + os/pwrite + os/fsync.
closeclose = fn [mut db SqliteDb] enumSaves (if file-backed) and closes db.
tablestables = fn [db SqliteDb] block[str]Lists all user table names in db.
indexesindexes = fn [db SqliteDb] block[str]Lists all user index names in db.
execexec = fn [mut db SqliteDb, sql str, params block] anyExecutes a DDL, transaction, or DML SQL statement (CREATE TABLE, CREATE [UNIQUE] INDEX, ALTER TABLE ADD COLUMN, DROP TABLE, INSERT, UPDATE, DELETE, BEGIN, COMMIT, ROLLBACK). Returns affected row count (or last inserted rowid on single-row INSERT).
query-sqlquery-sql = fn [db SqliteDb, sql str, params block] blockExecutes a parameterized SELECT query (? placeholders, optional INNER JOIN / LEFT JOIN) and returns a block of row maps.
define-tabledefine-table = fn [table_name str, spec_blk block] TableSpecDefines a declarative ORM TableSpec from a homoiconic (quote [...]) schema block: define-table 'users' (quote [id i64 .pk, email str .unique, role str = 'member', score i64 = 0])
migratemigrate = fn [mut db SqliteDb, spec TableSpec] enumCreates or auto-migrates spec on db (CREATE TABLE IF NOT EXISTS, ALTER TABLE ADD COLUMN for new fields, and CREATE [UNIQUE] INDEX IF NOT EXISTS).
insertinsert = fn [mut db SqliteDb, spec TableSpec, record any] i64Inserts a record map / struct into spec and returns the inserted rowid (i64).
find-by-idfind-by-id = fn [db SqliteDb, spec TableSpec, id any] mapLooks up a single record by primary key (err if not found, ready for /or).
update-by-idupdate-by-id = fn [mut db SqliteDb, spec TableSpec, id any, patch map] i64Updates fields in patch on the record matching id, returning updated row count.
delete-by-iddelete-by-id = fn [mut db SqliteDb, spec TableSpec, id any] i64Deletes the record matching id, returning deleted row count.
qq = fn [db SqliteDb, dsl block] blockExecutes a homoiconic Veko query dialect block against db: sqlite/q db (quote [select [u.email o.total] from users u join orders o on [u.id == o.user_id] where [o.total >= 50] order-by [o.total .desc] limit 10])

Verified Doctest (db/sqlite/exec)

VEKO
use [sq = db/sqlite]
mut db = sq/open ':memory:'
_ = sq/exec mut db 'CREATE TABLE nodes (id INTEGER PRIMARY KEY, host TEXT UNIQUE, port INTEGER DEFAULT 443)' []
id1 = sq/exec mut db 'INSERT INTO nodes (host, port) VALUES (?, ?)' ['edge.veko-lang.org' 8443]
_ = sq/exec mut db 'ALTER TABLE nodes ADD COLUMN region TEXT DEFAULT \'ca-central\'' []
raw = sq/to-bytes db
db2 = sq/from-bytes raw
rows = sq/query-sql db2 'SELECT host, port, region FROM nodes WHERE id = ?' [id1]
if (len rows) != 1 or rows[0].port != 8443 or rows[0].region != 'ca-central' [ err 'sqlite roundtrip failed' ] else [ .ok ]

Module durable/object

Exported Structs & Interfaces

  • ObjectRef: ObjectRef = struct { ns str, id str, version i64 = ..., alarm_ns i64 = ... } — Reference to a persistent named Durable Object inside a db/kv store.
  • AlarmEvent: AlarmEvent = struct { ns str, id str, fire_at_ns i64, tag str } — One due durable alarm returned by poll-due-alarms.
  • InboxMsg: InboxMsg = struct { seq i64, sent_ns i64, kind str, payload any, attempts i64 = ... } — One queued durable inbox message returned by drain-inbox / process-inbox.
  • InboxOpts: InboxOpts = struct { max_attempts i64 = ..., base_backoff dur = ..., max_backoff dur = ..., batch_limit i64 = ... } — Retry, visibility backoff, and batch limits for process-inbox.
  • DeadLetterMsg: DeadLetterMsg = struct { ns str, id str, seq i64, kind str, payload any, attempts i64, last_error str, failed_ns i64 } — Persistent Dead-Letter Queue (DLQ) record created when an inbox message exhausts max_attempts.

Exported Functions

SymbolSignatureDescription
open-objectopen-object = fn [mut db kv/KvStore, ns str, id str] ObjectRefOpens or creates a Durable Object identified by (ns, id) in db.
getget = fn [db kv/KvStore, obj ObjectRef, field str] anyReads a single durable state field from obj (returns err if absent; combine with /or).
get-orget-or = fn [db kv/KvStore, obj ObjectRef, field str, fallback any] anyReads a single durable state field from obj, returning fallback when absent.
put-fieldput-field = fn [mut db kv/KvStore, mut obj ObjectRef, field str, val any] enumAtomically writes one field and increments the object's version in a single db/kv batch.
put-fieldsput-fields = fn [mut db kv/KvStore, mut obj ObjectRef, fields map] enumAtomically writes every key/value pair in fields and bumps the object's version in one WAL batch.
delete-fielddelete-field = fn [mut db kv/KvStore, mut obj ObjectRef, field str] enumAtomically deletes a state field and bumps the object's version.
statestate = fn [db kv/KvStore, obj ObjectRef] mapLoads all current state fields of obj as a map.
mutatemutate = fn [mut db kv/KvStore, mut obj ObjectRef, handler any] anyExecutes a transactional actor turn (handler cur_state): - If handler returns err, zero writes are committed (full atomic rollback). - Otherwise handler returns { state = updated_map, result = value }, whose changed/deleted keys and incremented version are committed atomically in a single db/kv batch.
mutate-casmutate-cas = fn [mut db kv/KvStore, mut obj ObjectRef, expected_version i64, handler any] anyOptimistic Compare-And-Swap (CAS) transactional mutation: verifies on-disk version == expected_version before committing.
set-alarm-atset-alarm-at = fn [mut db kv/KvStore, mut obj ObjectRef, fire_at_ns i64, tag str] enumSchedules a persistent alarm for obj firing at absolute Unix timestamp fire_at_ns.
set-alarmset-alarm = fn [mut db kv/KvStore, mut obj ObjectRef, delay dur, tag str] i64Schedules a persistent alarm firing after delay from now (time/unix).
clear-alarmclear-alarm = fn [mut db kv/KvStore, mut obj ObjectRef] enumCancels any pending durable alarm on obj.
poll-due-alarmspoll-due-alarms = fn [mut db kv/KvStore, ns str] block[AlarmEvent]Scans namespace ns for alarms with fire_at_ns <= time/unix, atomically clears them, and returns them.
enqueueenqueue = fn [mut db kv/KvStore, mut obj ObjectRef, kind str, payload any] i64Enqueues a durable FIFO message into obj's mailbox and returns its monotonic sequence number.
enqueue-batchenqueue-batch = fn [mut db kv/KvStore, mut obj ObjectRef, messages block] i64Enqueues a block of { kind, payload } messages into obj's mailbox in a single db/kv WAL batch.
drain-inboxdrain-inbox = fn [mut db kv/KvStore, mut obj ObjectRef] block[InboxMsg]Atomically drains and returns all pending FIFO messages in obj's mailbox.
process-inboxprocess-inbox = fn [mut db kv/KvStore, mut obj ObjectRef, opts InboxOpts, handler any] mapTransactionally processes visible inbox messages via (handler state msg) with exponential visibility backoff and automatic Dead-Letter Queue (do_dlq/<ns>/<id>/<seq>) routing on exhausted max_attempts, committing all state changes + ACKs + retries + DLQ moves in a single atomic db/kv WAL batch.
list-dead-letterslist-dead-letters = fn [db kv/KvStore, obj ObjectRef] block[DeadLetterMsg]Lists all Dead-Letter Queue (DeadLetterMsg) records for obj.
requeue-dead-letterrequeue-dead-letter = fn [mut db kv/KvStore, mut obj ObjectRef, seq i64] boolAtomically moves dead-lettered message seq back into obj's live inbox with attempts = 0.
list-idslist-ids = fn [db kv/KvStore, ns str] block[str]Lists all Durable Object IDs currently stored under namespace ns.
destroydestroy = fn [mut db kv/KvStore, obj ObjectRef] enumAtomically deletes all state, metadata, alarms, and queued messages belonging to obj.

Verified Doctest (durable/object/open-object)

VEKO
use [kv = db/kv, dobj = durable/object]
p = str/join [(os/temp-dir) '/veko_do_doctest_1.vkkv'] ''
_ = os/remove/or p [.ok]
mut db = kv/open-fast p
mut obj = dobj/open-object mut db 'cart' 'user-42'
_ = dobj/put-field mut db mut obj 'total' 199
_ = kv/close mut db
mut db2 = kv/open-fast p
obj2 = dobj/open-object mut db2 'cart' 'user-42'
tot = dobj/get db2 obj2 'total'
_ = kv/close mut db2
_ = os/remove/or p [.ok]
if tot != 199 or obj2.version != 1 [ err 'durable object persistence failed' ] else [ .ok ]

Module durable/workflow

Exported Structs & Interfaces

  • WorkflowRun: WorkflowRun = struct { id str, name str, status enum = ..., step_count i64 = ..., wait_event str = ..., wake_at_ns i64 = ... } — Active handle to a durable workflow execution instance.
  • RetryPolicy: RetryPolicy = struct { max_attempts i64 = ..., base_delay dur = ..., max_delay dur = ..., route_to_dlq bool = ... } — Exponential backoff + Dead-Letter Queue policy for step-retry-policy.
  • StepSpec: StepSpec = struct { name str, work any } — Named step descriptor for single-fsync batched execution (step-batch).

Exported Functions

SymbolSignatureDescription
startstart = fn [mut db kv/KvStore, id str, name str, input any] WorkflowRunStarts a new durable workflow run id, or idempotently resumes an existing run after a crash/restart.
get-statusget-status = fn [db kv/KvStore, id str] mapReturns the full persisted metadata map for workflow id.
step-done?step-done? = fn [db kv/KvStore, wf WorkflowRun, step_name str] boolReturns true if step_name has already been checkpointed as completed in db.
step-resultstep-result = fn [db kv/KvStore, wf WorkflowRun, step_name str] anyReturns the persisted checkpoint result for a completed step_name, or err if not done.
stepstep = fn [mut db kv/KvStore, mut wf WorkflowRun, step_name str, work_fn any] anyExecutes a durable, replay-safe memoized step step_name: - On replay (if step_name already completed in db), immediately returns its persisted value without invoking work_fn. - Otherwise calls (work_fn), atomically checkpoints its result to db/kv, and returns it.
step-with-retrystep-with-retry = fn [mut db kv/KvStore, mut wf WorkflowRun, step_name str, max_attempts i64, backoff dur, work_fn any] anyExecutes a durable step with up to max_attempts retries and backoff delay between failures. Completed steps are memoized in db/kv and never re-run on replay.
sleep-untilsleep-until = fn [mut db kv/KvStore, mut wf WorkflowRun, step_name str, delay dur] boolDurable sleep checkpoint: persists a wake-up timestamp on first invocation and returns false until time/unix >= wake_at_ns, after which it checkpoints done = true and returns true.
wait-eventwait-event = fn [mut db kv/KvStore, mut wf WorkflowRun, event_name str] mapWaits for an external signal event_name: - If already delivered via send-event, returns { ready = true, payload = ... }. - Otherwise persists status = 'waiting' and returns { ready = false, payload = .null }.
send-eventsend-event = fn [mut db kv/KvStore, id str, event_name str, payload any] enumDurably delivers an external event event_name with payload to workflow id.
record-compensationrecord-compensation = fn [mut db kv/KvStore, mut wf WorkflowRun, comp_name str, data any] enumRegisters a durable LIFO saga compensation entry (comp_name, data) on wf.
run-compensationsrun-compensations = fn [mut db kv/KvStore, mut wf WorkflowRun, comp_fn any] i64Executes all registered compensations in LIFO order by invoking (comp_fn name data), clears them atomically, marks the workflow .compensated, and returns the count executed.
completecomplete = fn [mut db kv/KvStore, mut wf WorkflowRun, output any] enumAtomically marks wf as .completed and persists output.
failfail = fn [mut db kv/KvStore, mut wf WorkflowRun, reason str] enumAtomically marks wf as .failed and persists reason.
historyhistory = fn [db kv/KvStore, id str] blockReturns the chronological durable execution log entries for workflow id.
list-runslist-runs = fn [db kv/KvStore] block[str]Lists all workflow run IDs stored in db.
step-retry-policystep-retry-policy = fn [mut db kv/KvStore, mut wf WorkflowRun, step_name str, policy RetryPolicy, work_fn any] anyExecutes a durable step with exponential backoff (RetryPolicy) and automatic Dead-Letter Queue (wf_dlq/<id>) routing on exhaustion.
list-dead-letterslist-dead-letters = fn [db kv/KvStore] block[map]Lists all dead-lettered workflow records stored under wf_dlq/*.
requeue-dead-letterrequeue-dead-letter = fn [mut db kv/KvStore, id str] WorkflowRunAtomically clears the failed step's attempt counter and moves workflow id out of the Dead-Letter Queue so replay resumes at the failed step.
step-batchstep-batch = fn [mut db kv/KvStore, mut wf WorkflowRun, specs block[StepSpec]] blockExecutes a batch of StepSpecs, skipping already-memoized steps on replay and checkpointing all newly completed steps in ONE db/kv WAL batch (fsync).
wait-event-timeoutwait-event-timeout = fn [mut db kv/KvStore, mut wf WorkflowRun, event_name str, timeout dur] mapWaits for external signal event_name up to timeout ({ ready = bool, timed_out = bool, payload = any }).
poll-runnablepoll-runnable = fn [db kv/KvStore] block[str]Scans db for workflows ready to execute (status == 'running' or waiting timers/deadlines with wake_at_ns <= time/unix).
claim-runclaim-run = fn [mut db kv/KvStore, id str, worker_id str, lease_dur dur] boolAtomically acquires or renews a distributed worker execution lease (worker_id, lease_dur) on workflow id.

Verified Doctest (durable/workflow/start)

VEKO
use [kv = db/kv, wf = durable/workflow]
p = str/join [(os/temp-dir) '/veko_wf_doctest_1.vkkv'] ''
_ = os/remove/or p [.ok]
mut db = kv/open-fast p
mut run = wf/start mut db 'order-1' 'checkout' { total = 49 }
v1 = wf/step mut db mut run 'charge' fn [] [ 'tx-100' ]
// Re-open and replay: completed step returns persisted 'tx-100' without running closure!
_ = kv/close mut db
mut db2 = kv/open-fast p
mut run2 = wf/start mut db2 'order-1' 'checkout' { total = 49 }
v2 = wf/step mut db2 mut run2 'charge' fn [] [ 'tx-999-must-not-run' ]
_ = wf/complete mut db2 mut run2 v2
_ = kv/close mut db2
_ = os/remove/or p [.ok]
if v1 != 'tx-100' or v2 != 'tx-100' or run2.status != .completed [ err 'replay violated idempotency' ] else [ .ok ]

Module durable

Exported Functions

SymbolSignatureDescription
open-storeopen-store = fn [path str] kv/KvStoreOpens a durable fsync-backed db/kv backing store for Durable Objects and Workflows.
open-store-fastopen-store-fast = fn [path str] kv/KvStoreOpens a high-throughput WAL-backed db/kv store (for tests and ephemeral workloads).
close-storeclose-store = fn [mut db kv/KvStore] enumCloses a db/kv backing store cleanly.
objectobject = fn [mut db kv/KvStore, ns str, id str] dobj/ObjectRefOpens or creates a Durable Object (ns, id).
workflowworkflow = fn [mut db kv/KvStore, id str, name str, input any] dwf/WorkflowRunStarts or idempotently resumes a Durable Workflow run id.
poll-workflowspoll-workflows = fn [db kv/KvStore] block[str]Scans db for runnable or timer-due Durable Workflows.
claim-workflowclaim-workflow = fn [mut db kv/KvStore, id str, worker_id str, lease_dur dur] boolClaims a distributed worker lease on workflow id.
workflow-dead-lettersworkflow-dead-letters = fn [db kv/KvStore] block[map]Lists all Dead-Letter Queue workflow entries in db.

Module ffi

Exported Structs & Interfaces

  • Library: Library = struct { handle i64, path str } — Handle to a dynamically loaded foreign shared library.
  • Symbol: Symbol = struct { addr i64, name str } — Handle to a resolved foreign C symbol pointer.

Exported Functions

SymbolSignatureDescription
candidate-pathscandidate-paths = fn [name str, veko_lib_env str, is_win bool] block[str]Splits VEKO_LIB on ; (Windows) or : (POSIX) and returns candidate shared-library paths before falling back to name for standard OS dynamic loader resolution.
resolve-lib-pathresolve-lib-path = fn [name str] strResolves name against VEKO_LIB directories on disk when present, otherwise returns name.
open-libopen-lib = fn [path str] LibraryOpens a foreign shared library (LoadLibraryA on Windows, dlopen on Linux/macOS), searching VEKO_LIB directories first when configured. Requires opt-in .ffi capability.
resolveresolve = fn [lib Library, name str] SymbolResolves a C symbol inside lib (GetProcAddress on Windows, dlsym on Linux/macOS).
call-ccall-c = fn [s Symbol, args block] i64Invokes a foreign C function s with up to 6 integer/string/bytes/bool arguments using the platform's static AOT C-ABI trampoline and returns its i64 result register.
close-libclose-lib = fn [lib Library]Closes a loaded foreign library (FreeLibrary / dlclose).
pack-i32pack-i32 = fn [mut buf bytes, v i64]Appends a 32-bit little-endian integer into buf.
pack-u32pack-u32 = fn [mut buf bytes, v i64]Appends an unsigned 32-bit little-endian integer into buf.
pack-i64pack-i64 = fn [mut buf bytes, v i64]Appends a 64-bit little-endian integer into buf.
pack-cstrpack-cstr = fn [mut buf bytes, s str]Appends a NUL-terminated UTF-8 C string into buf.
pad-alignpad-align = fn [mut buf bytes, align i64]Appends pad zero bytes to align a C struct field to align bytes.
unpack-u32unpack-u32 = fn [buf bytes, off i64] i64Reads an unsigned 32-bit little-endian integer at byte offset off.
unpack-i32unpack-i32 = fn [buf bytes, off i64] i64Reads a signed 32-bit little-endian integer at byte offset off.
unpack-i64unpack-i64 = fn [buf bytes, off i64] i64Reads a 64-bit little-endian integer at byte offset off.
unpack-cstrunpack-cstr = fn [buf bytes, off i64] strReads a NUL-terminated C string starting at off.

Verified Doctest (ffi/candidate-paths)

VEKO
use [ffi]
cands = ffi/candidate-paths 'custom_ext' '/opt/veko/lib:/usr/local/lib' false

Module html

Exported Structs & Interfaces

  • Node: Node = struct { kind enum, tag str = ..., attrs map = ..., children block = ..., content str = ... } — Typed HTML DOM node (.el, .text, .raw, .frag, .comment, .doctype).

Exported Functions

SymbolSignatureDescription
escapeescape = fn [s str] strEscapes HTML text content (&, <, >, ", ') to prevent XSS.
elel = fn [tag any, attrs map, children block] NodeCreates an HTML element node (accepts either .div enum or 'div' string tag).
texttext = fn [s str] NodeCreates an auto-escaped text node.
rawraw = fn [trusted_html str] NodeCreates a trusted unescaped raw HTML/SVG node (never pass untrusted user input!).
fragfrag = fn [children block] NodeCreates a document fragment grouping multiple children without a wrapper element.
commentcomment = fn [s str] NodeCreates an HTML comment node (<!-- ... -->).
doctypedoctype = fn [] NodeCreates an HTML5 <!DOCTYPE html> preamble node.
divdiv = fn [attrs map, children block] NodeErgonomic HTML5 element helpers for typed pure-Veko components.
spanspan = fn [attrs map, children block] NodeExported html/span operation.
pp = fn [attrs map, children block] NodeExported html/p operation.
aa = fn [attrs map, children block] NodeExported html/a operation.
h1h1 = fn [attrs map, children block] NodeExported html/h1 operation.
h2h2 = fn [attrs map, children block] NodeExported html/h2 operation.
h3h3 = fn [attrs map, children block] NodeExported html/h3 operation.
ulul = fn [attrs map, children block] NodeExported html/ul operation.
olol = fn [attrs map, children block] NodeExported html/ol operation.
lili = fn [attrs map, children block] NodeExported html/li operation.
sectionsection = fn [attrs map, children block] NodeExported html/section operation.
articlearticle = fn [attrs map, children block] NodeExported html/article operation.
headerheader = fn [attrs map, children block] NodeExported html/header operation.
footerfooter = fn [attrs map, children block] NodeExported html/footer operation.
navnav = fn [attrs map, children block] NodeExported html/nav operation.
main-elmain-el = fn [attrs map, children block] NodeExported html/main-el operation.
formform = fn [attrs map, children block] NodeExported html/form operation.
labellabel = fn [attrs map, children block] NodeExported html/label operation.
buttonbutton = fn [attrs map, children block] NodeExported html/button operation.
tabletable = fn [attrs map, children block] NodeExported html/table operation.
theadthead = fn [attrs map, children block] NodeExported html/thead operation.
tbodytbody = fn [attrs map, children block] NodeExported html/tbody operation.
trtr = fn [attrs map, children block] NodeExported html/tr operation.
thth = fn [attrs map, children block] NodeExported html/th operation.
tdtd = fn [attrs map, children block] NodeExported html/td operation.
inputinput = fn [attrs map] NodeExported html/input operation.
imgimg = fn [attrs map] NodeExported html/img operation.
brbr = fn [] NodeExported html/br operation.
hrhr = fn [] NodeExported html/hr operation.
meta-tagmeta-tag = fn [attrs map] NodeExported html/meta-tag operation.
link-csslink-css = fn [href str] NodeExported html/link-css operation.
style-elstyle-el = fn [css str] NodeExported html/style-el operation.
scriptscript = fn [attrs map, js str] NodeExported html/script operation.
documentdocument = fn [title str, head_extra block, body_children block] NodeBuilds a complete HTML5 <!DOCTYPE html> document with <meta charset="utf-8">, viewport, <title>, optional head_extra nodes, and body_children.
renderrender = fn [node any] strRenders any typed html/Node, Hiccup block ([.div { class = 'x' } ['hi']]), or nested component tree into an HTML string.

Verified Doctest (html/escape)

VEKO
use [html]
if (html/escape '<script>alert("x")</script>') != '&lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;' [
  err 'escape'
] else [ .ok ]

Module net/client

Exported Structs & Interfaces

  • RequestOpts: RequestOpts = struct { headers map[str] = ..., timeout dur = ..., max_redirects i64 = ..., roots_pem str = ..., extra_roots_pem str = ..., ca_file str = ..., pins_sha256 block = ..., pqc bool = ... } — Request options with ergonomic defaults.
  • HttpResponse: HttpResponse = struct { status i64, reason str, headers map[str], body bytes, final_url str } — Structured HTTP response returned by request, get, post, and post-json.
  • AsyncRequest: AsyncRequest = struct { method str = ..., url str, headers map[str] = ..., body bytes = ..., timeout dur = ... } — Descriptor for one concurrent non-blocking HTTP/1.1 request in request-batch.
  • Pool: Pool = struct { idle map, max_idle i64 = ..., reused i64 = ... } — Reusable HTTP/1.1 keep-alive connection pool keyed by scheme://host:port.

Exported Functions

SymbolSignatureDescription
bearer-headerbearer-header = fn [token str] map[str]Returns a header map with Authorization: Bearer <token>.
basic-headerbasic-header = fn [user str, password str] map[str]Returns a header map with RFC 7617 Authorization: Basic <base64(user:pass)>.
headerheader = fn [resp HttpResponse, name str, default_val str] strLooks up a response header case-insensitively (returns default_val if absent).
text-bodytext-body = fn [resp HttpResponse] strReturns the response body decoded as a UTF-8 string.
json-bodyjson-body = fn [resp HttpResponse] anyDecodes the response body as JSON.
requestrequest = fn [method str, target_url str, body bytes, opts RequestOpts] HttpResponseExecutes an HTTP/HTTPS request with redirect handling (301/302/303/307/308).
getget = fn [target_url str, opts RequestOpts] HttpResponsePerforms an HTTP/HTTPS GET request.
headhead = fn [target_url str, opts RequestOpts] HttpResponsePerforms an HTTP/HTTPS HEAD request (returns headers with empty body, preserving Content-Length).
postpost = fn [target_url str, body bytes, opts RequestOpts] HttpResponsePerforms an HTTP/HTTPS POST request with raw body bytes.
post-jsonpost-json = fn [target_url str, payload any, opts RequestOpts] HttpResponseJSON-encodes payload and sends an HTTP/HTTPS POST with Content-Type: application/json.
request-batchrequest-batch = fn [reqs block[AsyncRequest]] blockExecutes a batch of HTTP/1.1 AsyncRequests concurrently on a single OS readiness reactor (epoll / kqueue / IOCP+WSAPoll / WASI net-poll) using non-blocking sockets. Returns a block in matching input order where each entry is an HttpResponse or err.
get-manyget-many = fn [urls block[str], opts RequestOpts] blockPerforms concurrent non-blocking HTTP GET requests for all urls on a single reactor thread.
new-poolnew-pool = fn [cap i64] PoolCreates a new empty HTTP/1.1 connection Pool.
pool-requestpool-request = fn [mut pool Pool, method str, target_url str, body bytes, opts RequestOpts] HttpResponseExecutes a pooled HTTP/1.1 request reusing or establishing a persistent keep-alive stream.
pool-getpool-get = fn [mut pool Pool, target_url str, opts RequestOpts] HttpResponsePerforms a pooled HTTP GET request.
close-poolclose-pool = fn [mut pool Pool]Closes all idle keep-alive sockets in pool.

Verified Doctest (net/client/basic-header)

VEKO
use [hc = net/client]
h = hc/basic-header 'alice' 'secret'
if (map/get h 'Authorization') != 'Basic YWxpY2U6c2VjcmV0' [ err 'basic auth' ] else [ .ok ]

Module net/dns

Exported Structs & Interfaces

  • Record: Record = struct { name str, rtype i64, ttl i64, value str, rdata bytes } — Decoded DNS resource record.
  • Response: Response = struct { id i64, rcode i64, answers block } — Decoded DNS response message.

Exported Functions

SymbolSignatureDescription
TYPE-ATYPE-A = fn [] i64DNS record type constants (RFC 1035 / RFC 3596 / RFC 2782).
TYPE-NSTYPE-NS = fn [] i64Exported net/dns/TYPE-NS operation.
TYPE-CNAMETYPE-CNAME = fn [] i64Exported net/dns/TYPE-CNAME operation.
TYPE-TXTTYPE-TXT = fn [] i64Exported net/dns/TYPE-TXT operation.
TYPE-AAAATYPE-AAAA = fn [] i64Exported net/dns/TYPE-AAAA operation.
TYPE-SRVTYPE-SRV = fn [] i64Exported net/dns/TYPE-SRV operation.
encode-queryencode-query = fn [tx_id i64, domain str, qtype i64] bytesEncodes an RFC 1035 standard recursive DNS query packet for domain and qtype (e.g. dns/TYPE-A).
decode-responsedecode-response = fn [msg bytes] ResponseDecodes an RFC 1035 DNS response packet msg into a Response containing parsed Record answers.
parse-hostsparse-hosts = fn [text str] map[block]Parses /etc/hosts formatted text into a map[block] mapping lowercased hostnames to IP lists.
parse-resolv-confparse-resolv-conf = fn [text str] blockParses /etc/resolv.conf text and returns a block of IPv4 nameserver addresses.
query-udpquery-udp = fn [nameserver str, port i64, domain str, qtype i64, timeout dur] ResponseSends a single UDP DNS query for domain (qtype) to nameserver:port with timeout and decodes the Response.
resolve-hostresolve-host = fn [host str] blockResolves host to IPv4 addresses via numeric check, /etc/hosts, OS net/resolve, or /etc/resolv.conf UDP DNS.

Verified Doctest (net/dns/encode-query)

VEKO
use [dns = net/dns]
pkt = dns/encode-query 0x1234 'example.com' (dns/TYPE-A)
if (len pkt) < 25 or (bytes/get-u16-be pkt 0) != 0x1234 [ err 'dns encode-query' ] else [ .ok ]

Module net/http2

Exported Structs & Interfaces

  • Message: Message = struct { stream_id i64, status i64 = ..., method str = ..., path str = ..., headers map[str] = ..., body bytes, has_stream bool = ..., stream any = ... } — HTTP/2 request/response message exchanged over an H2Conn stream.
  • H2ServerOpts: H2ServerOpts = struct { max_requests i64 = ..., max_concurrent_streams i64 = ..., max_frame_size i64 = ..., max_header_bytes i64 = ..., max_continuation_cnt i64 = ..., max_hpack_table_size i64 = ..., max_body_bytes i64 = ..., max_rst_budget i64 = ..., max_ctrl_budget i64 = ... } — Server limits & DoS/flood mitigations for serve-conn-opts.
  • H2Conn: H2Conn = struct { stream io/Stream, next_stream_id i64 = ..., is_server bool = ... } — Active HTTP/2 connection wrapping an io/Stream (plain TCP, TLS 1.3 ALPN 'h2', or io/mem-stream).

Exported Functions

SymbolSignatureDescription
write-framewrite-frame = fn [mut conn H2Conn, f h2/Frame] i64Writes a single codec/http2 Frame onto conn.
read-frame-maxread-frame-max = fn [mut conn H2Conn, max_frame_size i64] h2/FrameReads the next codec/http2 Frame from conn enforcing max_frame_size.
read-frameread-frame = fn [mut conn H2Conn] h2/FrameReads the next codec/http2 Frame from conn (default 16 MiB wire max).
encode-rst-streamencode-rst-stream = fn [err_code i64] bytesEncodes a 4-byte RST_STREAM payload (error_code u32 BE).
encode-goawayencode-goaway = fn [last_sid i64, err_code i64] bytesEncodes an 8-byte GOAWAY payload (last_stream_id u31 BE || error_code u32 BE).
send-goawaysend-goaway = fn [mut conn H2Conn, last_sid i64, err_code i64] i64Sends a GOAWAY frame on stream 0.
send-rst-streamsend-rst-stream = fn [mut conn H2Conn, stream_id i64, err_code i64] i64Sends a RST_STREAM frame on stream_id.
client-openclient-open = fn [mut s io/Stream] H2ConnInitializes an HTTP/2 client connection over s: sends the RFC 9113 preface and initial SETTINGS frame.
server-acceptserver-accept = fn [mut s io/Stream] H2ConnInitializes an HTTP/2 server connection over s: verifies the client preface and sends server SETTINGS + ACK.
requestrequest = fn [mut conn H2Conn, method str, path str, authority str, headers map[str], body bytes] MessageSends an HTTP/2 request (HEADERS + optional DATA) and reads the server's Message response.
read-requestread-request = fn [mut conn H2Conn] MessageReads the next complete HTTP/2 request Message on a server H2Conn.
write-responsewrite-response = fn [mut conn H2Conn, stream_id i64, status i64, headers map[str], body bytes] i64Writes an HTTP/2 server response (HEADERS + optional DATA with END_STREAM) on stream_id.
encode-window-updateencode-window-update = fn [inc i64] bytesExported net/http2/encode-window-update operation.
serve-conn-optsserve-conn-opts = fn [mut s io/Stream, handler any, opts H2ServerOpts] i64Serves an RFC 9113 HTTP/2 connection over s with explicit H2ServerOpts DoS & flood limits (concurrent stream cap, CONTINUATION flood guard, HPACK table cap, and CVE-2023-44487 Rapid Reset GOAWAY).
serve-connserve-conn = fn [mut s io/Stream, handler any, max_requests i64] i64Serves an RFC 9113 HTTP/2 connection over s using default H2ServerOpts. handler is fn [req Message] Message. Pass max_requests <= 0 for unlimited streams on the connection.

Verified Doctest (net/http2/request)

VEKO
use [io, h2 = net/http2, ch2 = codec/http2]
mut wire = io/mem-stream (bytes/with-cap 0)
mut cc = h2/client-open mut wire
hblk = ch2/hpack-encode [(ch2/Header { name = ':method', value = 'GET' }) (ch2/Header { name = ':path', value = '/ping' })]
_ = h2/write-frame mut cc (ch2/Frame { ftype = 1, flags = 5, stream_id = 1, payload = hblk })
mut rx = io/mem-stream (io/read-all mut cc.stream)
mut sc = h2/server-accept mut rx
req = h2/read-request mut sc
if req.method != 'GET' or req.path != '/ping' or req.stream_id != 1 [ err 'net/http2' ] else [ .ok ]

Module net/http3

Exported Structs & Interfaces

  • Message: Message = struct { stream_id i64, status i64 = ..., method str = ..., path str = ..., headers map[str] = ..., body bytes } — HTTP/3 request/response message exchanged over a QUIC stream.
  • ReassemblyBuf: ReassemblyBuf = struct { data bytes, ranges block, fin_known bool = ..., final_size i64 = ... } — Tracks out-of-order byte intervals without corrupting unreceived prefixes with zero bytes.

Exported Functions

SymbolSignatureDescription
derive-quic-keysderive-quic-keys = fn [secret bytes, cs i64] mapExported net/http3/derive-quic-keys operation.
derive-initial-keysderive-initial-keys = fn [client_dcid bytes] mapDerives Initial client & server QUIC v1 keysets from the client's Initial Destination Connection ID (dcid).
seal-long-packetseal-long-packet = fn [ptype i64, dcid bytes, scid bytes, pn i64, ks map, raw_frames bytes, pad_to i64] bytesSeals a Long Header QUIC v1 packet (ptype: 0 = Initial, 2 = Handshake) with 2-byte packet number.
seal-short-packetseal-short-packet = fn [dcid bytes, pn i64, ks map, raw_frames bytes] bytesSeals a Short Header (1-RTT) QUIC v1 packet with 2-byte packet number.
reconstruct-pnreconstruct-pn = fn [largest_pn i64, truncated_pn i64, pn_nbits i64] i64RFC 9000 Appendix A.3 packet number reconstruction from wire-truncated truncated_pn (pn_nbits in 8, 16, 24, 32).
open-long-packet-pnopen-long-packet-pn = fn [dgram bytes, off i64, ks map, largest_pn i64] anyParses & unprotects one Long Header packet at off inside UDP dgram, reconstructing full 62-bit PN from largest_pn.
open-long-packetopen-long-packet = fn [dgram bytes, off i64, ks map] anyParses & unprotects one Long Header packet at off inside UDP dgram.
open-short-packet-pnopen-short-packet-pn = fn [dgram bytes, off i64, local_cid_len i64, ks map, largest_pn i64] anyParses & unprotects a Short Header (1-RTT) packet from off to the end of dgram, reconstructing PN from largest_pn.
open-short-packetopen-short-packet = fn [dgram bytes, off i64, local_cid_len i64, ks map] anyParses & unprotects a Short Header (1-RTT) packet from off to the end of dgram.
build-transport-paramsbuild-transport-params = fn [orig_dcid bytes, init_scid bytes, is_server bool] bytesExported net/http3/build-transport-params operation.
record-rx-pnrecord-rx-pn = fn [ranges block, pn i64] blockMerges received packet number pn into sorted ascending disjoint [lo, hi] inclusive intervals (retaining latest 16 ranges).
encode-ack-rangesencode-ack-ranges = fn [ranges block] bytesEncodes an RFC 9000 §19.3 ACK frame from ascending disjoint [lo, hi] inclusive PN intervals.
encode-ack-frameencode-ack-frame = fn [largest_pn i64] bytesExported net/http3/encode-ack-frame operation.
encode-crypto-frameencode-crypto-frame = fn [offset i64, data bytes] bytesExported net/http3/encode-crypto-frame operation.
encode-stream-frameencode-stream-frame = fn [stream_id i64, offset i64, data bytes, fin bool] bytesExported net/http3/encode-stream-frame operation.
parse-quic-framesparse-quic-frames = fn [buf bytes] anyParses all QUIC frames inside a decrypted packet payload into a block of frame maps.
encode-h3-response-streamencode-h3-response-stream = fn [resp Message] bytesEncodes HTTP/3 response headers + body into a contiguous HTTP/3 stream byte buffer (HEADERS + optional DATA).
decode-h3-request-streamdecode-h3-request-stream = fn [stream_id i64, wire bytes] anyDecodes an HTTP/3 request stream buffer (HEADERS + optional DATA frames) into a Message.
new-reasmnew-reasm = fn [] ReassemblyBufCreates an empty ReassemblyBuf.
reasm-insertreasm-insert = fn [mut rb ReassemblyBuf, offset i64, chunk bytes, is_fin bool, max_bytes i64] boolInserts chunk at offset into rb (rejecting offsets exceeding max_bytes), merging contiguous [lo, hi] intervals.
reasm-contiguous-lenreasm-contiguous-len = fn [rb ReassemblyBuf] i64Returns the contiguous number of bytes received starting strictly at offset 0.
reasm-complete?reasm-complete? = fn [rb ReassemblyBuf] boolReturns true iff FIN has arrived and all bytes [0..final_size] are contiguously present.
serve-udpserve-udp = fn [sock i64, get_ident_fn any, handler any, max_requests i64] i64Serves HTTP/3 over QUIC v1 on bound UDP socket sock (net/udp-bind) with contiguous interval reassembly, multi-packet PQC Initial handshakes, RFC 9000 PN reconstruction, multi-range ACKs, cwnd, and 25ms PTO retransmission.
requestrequest = fn [host str, port i64, method str, path str, headers map[str], body bytes] anyPerforms a complete pure-Veko HTTP/3 over QUIC v1 request (Initial ClientHello -> Handshake Finished -> 1-RTT QPACK HEADERS/DATA -> Message response). Supports WAN DNS resolution, '0.0.0.0' socket binding, out-of-order ReassemblyBuf, RFC 9000 PN reconstruction, multi-range ACKs, and 25ms PTO retransmission.

Verified Doctest (net/http3/derive-initial-keys)

VEKO
use [h3 = net/http3, hex = codec/hex]
dcid = hex/decode '8394c8f03e515708'
init = h3/derive-initial-keys dcid
if (hex/encode init.client.key) != '1f369613dd76d5467730efcbe3b1a22d' or (len init.client.key) != 16 [
  err 'quic initial key len'
] else [ .ok ]

Module net/ip

Exported Structs & Interfaces

  • IpAddr: IpAddr = struct { version i64, octets bytes } — Parsed IPv4 (version = 4, 4 octets) or IPv6 (version = 6, 16 octets) address.
  • Cidr: Cidr = struct { addr IpAddr, prefix_len i64 } — Parsed CIDR network prefix (addr/prefix_len, e.g. 10.0.0.0/8 or fc00::/7).

Exported Functions

SymbolSignatureDescription
parseparse = fn [s str] IpAddrParses an IPv4 or IPv6 address string into an IpAddr.
formatformat = fn [a IpAddr] strFormats an IpAddr into its canonical string representation (RFC 5952 compression for IPv6).
v4?v4? = fn [a IpAddr] boolExported net/ip/v4? operation.
v6?v6? = fn [a IpAddr] boolExported net/ip/v6? operation.
loopback?loopback? = fn [a IpAddr] boolReturns true if a is a loopback address (127.0.0.0/8 or ::1).
private?private? = fn [a IpAddr] boolReturns true if a is an RFC 1918 / link-local / ULA private address.
parse-cidrparse-cidr = fn [s str] CidrParses a CIDR prefix string ('10.0.0.0/8' or '2001:db8::/32').
contains?contains? = fn [cidr Cidr, target IpAddr] boolReturns true if cidr contains target.

Verified Doctest (net/ip/parse)

VEKO
use [ip = net/ip]
a = ip/parse '192.168.1.10'
b = ip/parse '2001:db8::1'
if (not (ip/v4? a)) or (not (ip/private? a)) or (not (ip/v6? b)) [ err 'ip parse' ] else [ .ok ]

Module net/tls13

Exported Functions

SymbolSignatureDescription
build-client-hello-extbuild-client-hello-ext = fn [sni str, eph_pub bytes, mlkem_ek bytes, rnd bytes, sess_id bytes, alpn str] bytesBuilds an RFC 8446 ClientHello handshake payload supporting optional hybrid X25519MLKEM768 (0x11EC) PQC key share.
build-client-hellobuild-client-hello = fn [sni str, eph_pub bytes, rnd bytes, sess_id bytes, alpn str] bytesBuilds an RFC 8446 ClientHello handshake payload (without TLS record header).
build-quic-client-hellobuild-quic-client-hello = fn [sni str, eph_pub bytes, rnd bytes, quic_tp bytes] bytesBuilds an RFC 9001 QUIC-TLS ClientHello (legacy_session_id = empty, alpn = 'h3', 0x0039 = quic_tp).
parse-quic-server-helloparse-quic-server-hello = fn [msg bytes] anyParses a QUIC-TLS ServerHello (legacy_session_id == empty), extracting cipher suite and extension-order-independent key_share.
client-handshakeclient-handshake = fn [sock i64, host str, opts map] anyPerforms a full pure-Veko TLS 1.3 client handshake over an already-connected TCP socket sock. opts supports server_name, alpn, pqc (enables hybrid X25519MLKEM768 0x11EC), roots_pem, roots_der, pins_sha256, insecure_skip_verify.
connectconnect = fn [host str, port i64, opts map] anyConnects TCP (resolving DNS hostnames) + performs full pure-Veko TLS 1.3 handshake (opts: roots_pem, pins_sha256, alpn, server_name, timeout).
sendsend = fn [mut conn map, data bytes] anySends plaintext application data encrypted as TLS 1.3 ApplicationData records.
recvrecv = fn [mut conn map] anyReceives decrypted application data (skips post-handshake NewSessionTicket records cleanly).
closeclose = fn [mut conn map]Sends encrypted close_notify alert and closes underlying TCP socket.
https-requesthttps-request = fn [host str, port i64, method str, target str, headers map, body bytes, opts map] anyExported net/tls13/https-request operation.
parse-pem-identityparse-pem-identity = fn [fullchain_pem str, privkey_pem str] anyParses PEM certificate chain (fullchain_pem) and private key (privkey_pem: Ed25519, ECDSA P-256, or RSA). Returns { chain_ders, key_info = { kind, priv, n, d } }.
load-pem-identityload-pem-identity = fn [cert_path str, key_path str] anyLoads a TLS 1.3 PEM identity from cert_path and key_path on disk.
ensure-dev-p256-identityensure-dev-p256-identity = fn [cert_path str, key_path str, domain str] anyEnsures a bootstrap ECDSA P-256 certificate & PKCS#8 key exist at cert_path and key_path (generating them in pure Veko if absent).
new-cert-reloadernew-cert-reloader = fn [cert_path str, key_path str] anyCreates a zero-downtime CertReloader tracking file mtime changes on cert_path and key_path.
get-identityget-identity = fn [mut rel map] anyReturns the active TLS identity, reloading automatically if either PEM file's mtime changed on disk.
build-server-flightbuild-server-flight = fn [ch_msg bytes, ident map, srv_alpns block, srv_quic_tp bytes, is_quic bool] anyPure-bytes TLS 1.3 / QUIC-TLS server flight builder (shared by server-handshake-identity and net/http3).
verify-client-finishedverify-client-finished = fn [c_hs_sec bytes, th_srv_fin bytes, cfin_msg bytes] boolVerifies a TLS 1.3 / QUIC-TLS client Finished handshake message (0x14 || u24(hlen) || verify_data).
server-handshake-identity-optsserver-handshake-identity-opts = fn [sock i64, ident map, srv_alpns block, hs_timeout dur, idle_timeout dur] anyPerforms a browser-grade RFC 8446 TLS 1.3 server handshake with an enforced wall-clock deadline (hs_timeout, e.g. 5s).
server-handshake-identityserver-handshake-identity = fn [sock i64, ident map, srv_alpns block] anyPerforms a browser-grade RFC 8446 TLS 1.3 server handshake using ident (parse-pem-identity: ECDSA P-256, RSA-PSS, or Ed25519) and negotiates srv_alpns (e.g. ['h2' 'http/1.1']) plus AES-128-GCM or CHACHA20-POLY1305 and optional X25519MLKEM768.
server-handshakeserver-handshake = fn [sock i64, chain_ders block, leaf_seed bytes] anyPerforms a minimal pure-Veko RFC 8446 server handshake on accepted socket sock using Ed25519 leaf keypair. Automatically negotiates hybrid X25519MLKEM768 (0x11EC) and ALPN ('h2' / 'http/1.1') when offered by client. Returns a connection handle compatible with tls13/send, tls13/recv, tls13/close, and tls13/tls-stream.
tls-streamtls-stream = fn [conn map] io/StreamWraps an established TLS 1.3 connection (connect or server-handshake) as an ORO io/Stream.

Module net/websocket

Exported Structs & Interfaces

  • Frame: Frame = struct { fin bool = ..., opcode i64, masked bool = ..., payload bytes } — Decoded WebSocket frame.
  • FrameTry: FrameTry = struct { complete bool, consumed i64, frame Frame } — Result of incremental non-blocking WebSocket frame parsing (try-decode-frame).

Exported Functions

SymbolSignatureDescription
OP-CONTOP-CONT = fn [] i64WebSocket opcodes (RFC 6455 Section 5.2).
OP-TEXTOP-TEXT = fn [] i64Exported net/websocket/OP-TEXT operation.
OP-BINARYOP-BINARY = fn [] i64Exported net/websocket/OP-BINARY operation.
OP-CLOSEOP-CLOSE = fn [] i64Exported net/websocket/OP-CLOSE operation.
OP-PINGOP-PING = fn [] i64Exported net/websocket/OP-PING operation.
OP-PONGOP-PONG = fn [] i64Exported net/websocket/OP-PONG operation.
accept-keyaccept-key = fn [client_key str] strComputes the RFC 6455 Sec-WebSocket-Accept header value from client_key.
encode-frameencode-frame = fn [f Frame, mask_key bytes] bytesEncodes a WebSocket Frame into RFC 6455 wire bytes (applying 4-byte XOR mask_key when f.masked == true).
decode-framedecode-frame = fn [wire bytes] FrameDecodes a single RFC 6455 WebSocket Frame from wire bytes (unmasking payload automatically).
write-framewrite-frame = fn [mut s io/Stream, f Frame] i64Writes a WebSocket Frame onto io/Stream s (generating fresh CSPRNG mask when f.masked == true).
read-frameread-frame = fn [mut s io/Stream] FrameReads the next RFC 6455 WebSocket Frame from io/Stream s.
client-handshakeclient-handshake = fn [mut s io/Stream, host str, path str] enumPerforms an RFC 6455 client HTTP/1.1 WebSocket Upgrade handshake over io/Stream s.
server-handshakeserver-handshake = fn [mut s io/Stream] strPerforms an RFC 6455 server HTTP/1.1 WebSocket Upgrade handshake over io/Stream s and returns the request path.
try-decode-frametry-decode-frame = fn [raw bytes] FrameTryIncrementally decodes one RFC 6455 frame from a non-blocking receive buffer raw. Returns FrameTry { complete = false, consumed = 0, ... } if more bytes are needed.

Verified Doctest (net/websocket/accept-key)

VEKO
use [ws = net/websocket]
acc = ws/accept-key 'dGhlIHNhbXBsZSBub25jZQ=='
if acc != 's3pPLMBiTxaQ9kYGzzhZRbK+xOo=' [ err 'ws accept-key' ] else [ .ok ]

Module otel

Exported Structs & Interfaces

  • TraceContext: TraceContext = struct { trace_id str, span_id str, sampled bool = ... } — W3C traceparent context (00-<trace_id_32hex>-<span_id_16hex>-<flags_2hex>).
  • Span: Span = struct { name str, trace_id str, span_id str, parent_id str, start_ns i64, end_ns i64 = ..., status str = ..., attributes map[str] = ... } — Recorded distributed trace span.
  • Registry: Registry = struct { service_name str, counters map[i64], gauges map[i64], helps map[str] } — In-memory metrics registry supporting counters and gauges.

Exported Functions

SymbolSignatureDescription
make-contextmake-context = fn [trace_hi i64, trace_lo i64, span_num i64, sampled bool] TraceContextFormats a TraceContext as a W3C traceparent HTTP header value.
format-traceparentformat-traceparent = fn [ctx TraceContext] strSerializes ctx into 00-<32hex>-<16hex>-<01|00>.
parse-traceparentparse-traceparent = fn [header_val str] TraceContextParses and validates a W3C traceparent header string (returns err if malformed; combine with /or).
start-spanstart-span = fn [name str, parent TraceContext, span_num i64, start_ns i64] SpanStarts a child Span linked to parent with explicit start_ns timestamp and span_num ID.
set-attrset-attr = fn [mut sp Span, key str, val str]Sets a string attribute on sp.
finish-spanfinish-span = fn [mut sp Span, end_ns i64, /status st str] SpanCompletes sp with end_ns and status ('OK' or 'ERROR').
export-otlp-jsonexport-otlp-json = fn [service_name str, spans block[Span]] strExports a block[Span] as an OpenTelemetry OTLP/HTTP ExportTraceServiceRequest JSON payload.
new-registrynew-registry = fn [service_name str] RegistryCreates a new metrics Registry for service_name.
inc-counterinc-counter = fn [mut reg Registry, name str, delta i64, /help help_txt str] i64Increments monotonic counter name by delta (delta >= 0).
set-gaugeset-gauge = fn [mut reg Registry, name str, val i64, /help help_txt str] i64Sets instantaneous gauge name to val.
export-prometheusexport-prometheus = fn [reg Registry] strRenders all counters and gauges in Prometheus 0.0.4 text exposition format.

Verified Doctest (otel/make-context)

VEKO
use [otel]
ctx = otel/make-context 0x1122334455667788 0x99aabbccddeeff00 0x0102030405060708 true
hdr = otel/format-traceparent ctx
parsed = otel/parse-traceparent hdr
if parsed.trace_id != ctx.trace_id or parsed.span_id != ctx.span_id or (not parsed.sampled) [
    err 'traceparent roundtrip'
] else [ .ok ]

Module profile/flamegraph

Exported Structs & Interfaces

  • StackSample: StackSample = struct { stack block[str], weight i64 } — One folded call-stack sample (stack ordered root -> leaf, weight in nanoseconds or sample ticks).
  • FnStat: FnStat = struct { name str, calls i64, self_ns i64, incl_ns i64 } — Per-function hotspot summary row.

Exported Functions

SymbolSignatureDescription
format-nsformat-ns = fn [ns i64] strFormats nanoseconds into a compact human-readable duration ('14.2 ms', '320 us', '850 ns').
parse-foldedparse-folded = fn [text str] block[StackSample]Parses standard Brendan Gregg folded-stack lines ('main;parse;lex 4200\n...') into block[StackSample].
format-foldedformat-folded = fn [samples block[StackSample]] strSerializes samples into canonical folded-stack text ('a;b;c 123\n').
render-svgrender-svg = fn [title str, samples block[StackSample], /subtitle sub str, /width svg_w i64] strRenders a self-contained, Light-Mode interactive SVG flamegraph (click to zoom, hover for inclusive/self stats, live search bar).

Verified Doctest (profile/flamegraph/parse-folded)

VEKO
use [fg = profile/flamegraph]
samples = fg/parse-folded 'main;parse;tokenize 400\nmain;emit 600\n'
svg = fg/render-svg 'Compiler Profile' samples
if (len samples) != 2 or not (str/contains? svg '<svg') [ err 'flamegraph failed' ] else [ .ok ]

Module reactor

Exported Structs & Interfaces

  • IoEvent: IoEvent = struct { token i64, mask i64 } — One readiness notification delivered by poll.
  • FdEntry: FdEntry = struct { fd i64, token i64, events i64, cb any } — Registered file descriptor entry tracked by a Reactor.
  • TimerEntry: TimerEntry = struct { id i64, fire_at_ns i64, interval_ns i64, active bool, cb any } — Scheduled timer entry tracked by a Reactor.
  • Reactor: Reactor = struct { poller i64, next_token i64 = ..., next_timer i64 = ..., stopped bool = ..., fds map = ..., timers block[TimerEntry] = ..., max_tick dur = ... } — Single-threaded readiness event loop with O(1) kernel readiness + timers + thread-safe waker.

Exported Functions

SymbolSignatureDescription
EV-READEV-READ = fn [] i64Readiness event mask flags.
EV-WRITEEV-WRITE = fn [] i64Exported reactor/EV-WRITE operation.
EV-ERREV-ERR = fn [] i64Exported reactor/EV-ERR operation.
EV-HUPEV-HUP = fn [] i64Exported reactor/EV-HUP operation.
EV-RWEV-RW = fn [] i64Exported reactor/EV-RW operation.
CTL-ADDCTL-ADD = fn [] i64Poller control operations.
CTL-MODCTL-MOD = fn [] i64Exported reactor/CTL-MOD operation.
CTL-DELCTL-DEL = fn [] i64Exported reactor/CTL-DEL operation.
readable?readable? = fn [ev IoEvent] boolReturns true if ev.mask indicates readability (EV-READ).
writable?writable? = fn [ev IoEvent] boolReturns true if ev.mask indicates writability (EV-WRITE).
errored?errored? = fn [ev IoEvent] boolReturns true if ev.mask indicates a socket error (EV-ERR).
closed?closed? = fn [ev IoEvent] boolReturns true if ev.mask indicates peer hangup/EOF (EV-HUP).
newnew = fn [] ReactorCreates a new OS-backed readiness Reactor.
wakerwaker = fn [r Reactor] i64Returns a copyable i64 waker handle that can be passed to spawn workers for wake-handle.
wake-handlewake-handle = fn [poller_handle i64] enumThread-safe wakeup of a Reactor blocked in poll or tick using its waker handle.
wakewake = fn [r Reactor] enumWakes r if blocked in poll or tick.
send-wakesend-wake = fn [ch any, msg any, waker_handle i64] enumSends msg onto channel ch and immediately wakes the target reactor via waker_handle so background spawn workers wake an OS epoll/kqueue/IOCP event loop in one call.
register-cbregister-cb = fn [mut r Reactor, fd i64, events i64, cb any] i64Registers fd with readiness events mask (EV-READ, EV-WRITE, EV-RW) and optional callback cb (.ok for pull mode). Returns the assigned i64 token.
registerregister = fn [mut r Reactor, fd i64, events i64] i64Registers fd for pull-mode event delivery (no callback). Returns the assigned i64 token.
modifymodify = fn [mut r Reactor, token i64, events i64] enumUpdates the readiness interest mask for a registered token.
unregisterunregister = fn [mut r Reactor, token i64] enumUnregisters token from the OS poller and removes it from r.
token-fdtoken-fd = fn [r Reactor, token i64] i64Returns the registered OS socket fd for token, or -1 if not found.
after-cbafter-cb = fn [mut r Reactor, delay dur, cb any] i64Schedules a one-shot timer firing after delay with optional callback cb (.ok for pull mode). Returns the assigned timer_id.
afterafter = fn [mut r Reactor, delay dur] i64Schedules a pull-mode one-shot timer firing after delay. Returns timer_id.
every-cbevery-cb = fn [mut r Reactor, interval dur, cb any] i64Schedules a repeating timer firing every interval with optional callback cb. Returns timer_id.
everyevery = fn [mut r Reactor, interval dur] i64Schedules a pull-mode repeating timer firing every interval. Returns timer_id.
cancel-timercancel-timer = fn [mut r Reactor, timer_id i64] enumCancels timer timer_id (idempotent).
next-waitnext-wait = fn [r Reactor, max_wait dur] durComputes the effective wait duration bounded by max_wait and the earliest active timer deadline.
pollpoll = fn [mut r Reactor, timeout dur] block[IoEvent]Polls the OS reactor for ready I/O events up to timeout (automatically capped by pending timers). Returns a block[IoEvent] of ready notifications.
due-timersdue-timers = fn [mut r Reactor] block[i64]Pull-mode timer drain: returns block[i64] of due timer IDs without invoking callbacks.
ticktick = fn [mut r Reactor, timeout dur] i64Runs one callback-mode reactor iteration: polls I/O up to timeout, invokes FD callbacks and due timer callbacks. Returns total number of events + timers dispatched.
stopstop = fn [mut r Reactor] enumRequests that run stop after the current iteration and wakes the poller.
runrun = fn [mut r Reactor, max_iters i64] i64Runs the callback-mode event loop until stop is called (or max_iters > 0 iterations elapse).
closeclose = fn [mut r Reactor] enumCloses the underlying OS poller and releases all reactor resources (idempotent).

Verified Doctest (reactor/readable?)

VEKO
use [reactor]
ev = reactor/IoEvent { token = 7, mask = (reactor/EV-READ) | (reactor/EV-HUP) }
if (not (reactor/readable? ev)) or (not (reactor/closed? ev)) or (reactor/writable? ev) [ err 'mask' ] else [ .ok ]

Module tui

Exported Structs & Interfaces

  • Cell: Cell = struct { ch str = ..., fg i64 = ..., bg i64 = ..., style i64 = ... } — One character cell in a double-buffered terminal Screen.
  • Screen: Screen = struct { width i64, height i64, cells block[Cell], prev block[Cell], dirty bool = ... } — Double-buffered terminal framebuffer with front (cells) and committed (prev) grids.
  • KeyEvent: KeyEvent = struct { kind enum = ..., ch str = ..., ctrl bool = ..., alt bool = ... } — Decoded keyboard input event returned by parse-key.

Exported Functions

SymbolSignatureDescription
STYLE-NONESTYLE-NONE = fn [] i64Style bitmask flags for Cell.style.
STYLE-BOLDSTYLE-BOLD = fn [] i64Exported tui/STYLE-BOLD operation.
STYLE-DIMSTYLE-DIM = fn [] i64Exported tui/STYLE-DIM operation.
STYLE-UNDERLINESTYLE-UNDERLINE = fn [] i64Exported tui/STYLE-UNDERLINE operation.
STYLE-REVERSESTYLE-REVERSE = fn [] i64Exported tui/STYLE-REVERSE operation.
COLOR-DEFAULTCOLOR-DEFAULT = fn [] i64Default terminal color sentinel (-1).
rgbrgb = fn [r i64, g i64, b i64] i64Packs an 8-bit RGB triple into a 24-bit i64 color ((r << 16) | (g << 8) | b).
color-whitecolor-white = fn [] i64Built-in high-contrast TrueColor palette helpers.
color-slatecolor-slate = fn [] i64Exported tui/color-slate operation.
color-surfacecolor-surface = fn [] i64Exported tui/color-surface operation.
color-cyancolor-cyan = fn [] i64Exported tui/color-cyan operation.
color-emeraldcolor-emerald = fn [] i64Exported tui/color-emerald operation.
color-ambercolor-amber = fn [] i64Exported tui/color-amber operation.
color-rosecolor-rose = fn [] i64Exported tui/color-rose operation.
escesc = fn [] strReturns the ASCII ESC byte (0x1b) as a single-byte string.
csicsi = fn [suffix str] strReturns an ANSI CSI sequence (ESC [ + suffix).
clear-screenclear-screen = fn [] strTerminal screen & cursor control escape sequences.
alt-screen-onalt-screen-on = fn [] strExported tui/alt-screen-on operation.
alt-screen-offalt-screen-off = fn [] strExported tui/alt-screen-off operation.
hide-cursorhide-cursor = fn [] strExported tui/hide-cursor operation.
show-cursorshow-cursor = fn [] strExported tui/show-cursor operation.
reset-stylereset-style = fn [] strExported tui/reset-style operation.
new-screennew-screen = fn [w i64, h i64] ScreenAllocates a new w x h double-buffered Screen initialized to blank spaces.
clearclear = fn [mut s Screen, fg i64, bg i64]Clears every cell on s to a space with foreground fg and background bg.
set-cellset-cell = fn [mut s Screen, x i64, y i64, ch str, fg i64, bg i64, style i64]Sets one cell at (x, y) if within bounds.
get-cellget-cell = fn [s Screen, x i64, y i64] CellReads the cell at (x, y), returning a blank cell if out of bounds.
draw-textdraw-text = fn [mut s Screen, x i64, y i64, text str, fg i64, bg i64, style i64]Draws a single-line string starting at (x, y), clipped to the screen width.
fill-rectfill-rect = fn [mut s Screen, x i64, y i64, w i64, h i64, ch str, fg i64, bg i64, style i64]Fills a rectangle (x, y, w, h) with character ch.
draw-boxdraw-box = fn [mut s Screen, x i64, y i64, w i64, h i64, title str, border enum, fg i64, bg i64]Draws a framed box with optional title. Supported border styles: .single, .double, .rounded, .ascii.
draw-progressdraw-progress = fn [mut s Screen, x i64, y i64, w i64, pct i64, fill_fg i64, track_fg i64, bg i64]Draws a horizontal progress bar of width w filled to pct (clamped 0..100).
draw-sparklinedraw-sparkline = fn [mut s Screen, x i64, y i64, vals block, fg i64, bg i64]Draws an inline sparkline across len vals columns using 8-level vertical bar glyphs.
draw-tabledraw-table = fn [mut s Screen, x i64, y i64, headers block, rows block, col_widths block, fg i64, hdr_fg i64, bg i64]Draws a tabular grid with bold headers and fixed column widths.
draw-menudraw-menu = fn [mut s Screen, x i64, y i64, w i64, items block, selected i64, fg i64, sel_fg i64, sel_bg i64, bg i64]Draws a selectable vertical menu list with highlight row selected.
render-diffrender-diff = fn [mut s Screen] strRenders only cells modified since the previous render-diff call into a minimal ANSI frame, then commits the front buffer into s.prev. Returns '' if nothing changed.
render-plainrender-plain = fn [s Screen] strRenders a clean multi-line plain-text snapshot of s (without ANSI codes) for logs and tests.
parse-keyparse-key = fn [raw bytes] KeyEventDecodes an input byte slice from os/stdin into a structured KeyEvent. Handles ANSI CSI arrows, Home/End/PgUp/PgDn/Delete, Enter, Tab, Backspace, Esc, Ctrl-A..Z, and UTF-8 text.

Verified Doctest (tui/rgb)

VEKO
use [tui]
c = tui/rgb 16 185 129
if c != 1096065 [ err 'rgb pack mismatch' ] else [ .ok ]

Module ui/canvas

Exported Structs & Interfaces

  • Color: Color = struct { r i64, g i64, b i64, a i64 = ... } — 8-bit RGBA color value.
  • Canvas: Canvas = struct { width i64, height i64, pixels bytes, clip_on bool = ..., clip_x i64 = ..., clip_y i64 = ..., clip_w i64 = ..., clip_h i64 = ... } — Offscreen RGBA32 pixel surface (width * height * 4 bytes, top-down row-major) with optional clip rect.

Exported Functions

SymbolSignatureDescription
rgbargba = fn [r i64, g i64, b i64, a i64] ColorConstructs an RGBA Color with components clamped to 0..255.
rgbrgb = fn [r i64, g i64, b i64] ColorConstructs an opaque RGB Color (a = 255).
color-bg-darkcolor-bg-dark = fn [] ColorBuilt-in modern UI palette constructors.
color-surfacecolor-surface = fn [] ColorExported ui/canvas/color-surface operation.
color-bordercolor-border = fn [] ColorExported ui/canvas/color-border operation.
color-text-primarycolor-text-primary = fn [] ColorExported ui/canvas/color-text-primary operation.
color-text-mutedcolor-text-muted = fn [] ColorExported ui/canvas/color-text-muted operation.
color-cyancolor-cyan = fn [] ColorExported ui/canvas/color-cyan operation.
color-emeraldcolor-emerald = fn [] ColorExported ui/canvas/color-emerald operation.
color-ambercolor-amber = fn [] ColorExported ui/canvas/color-amber operation.
color-rosecolor-rose = fn [] ColorExported ui/canvas/color-rose operation.
set-clipset-clip = fn [mut cv Canvas, x i64, y i64, w i64, h i64]Sets an active clipping rectangle (x, y, w, h) on cv (clamped to canvas bounds).
reset-clipreset-clip = fn [mut cv Canvas]Clears any active clipping rectangle on cv, restoring full-canvas drawing.
new-canvasnew-canvas = fn [w i64, h i64] CanvasAllocates a new w x h RGBA32 Canvas initialized to transparent black (0, 0, 0, 0).
clearclear = fn [mut cv Canvas, c Color]Fills the entire canvas with c in place (zero per-frame heap allocation).
get-pixelget-pixel = fn [cv Canvas, x i64, y i64] ColorReads the RGBA Color at (x, y) (returns transparent black if out of bounds).
set-pixelset-pixel = fn [mut cv Canvas, x i64, y i64, c Color]Sets or Porter-Duff SRC_OVER alpha-blends pixel (x, y) with c (honoring any active clip rect).
fill-rectfill-rect = fn [mut cv Canvas, x i64, y i64, w i64, h i64, c Color]Fills a clipped rectangle (x, y, w, h) with c (supports alpha blending and active clip rect).
stroke-rectstroke-rect = fn [mut cv Canvas, x i64, y i64, w i64, h i64, thickness i64, c Color]Draws a rectangle outline of thickness pixels.
fill-gradient-vfill-gradient-v = fn [mut cv Canvas, x i64, y i64, w i64, h i64, top Color, bottom Color]Fills a vertical linear gradient across (x, y, w, h) from top to bottom.
fill-rounded-rectfill-rounded-rect = fn [mut cv Canvas, x i64, y i64, w i64, h i64, radius i64, c Color]Fills a rounded rectangle with corner radius.
stroke-rounded-rectstroke-rounded-rect = fn [mut cv Canvas, x i64, y i64, w i64, h i64, radius i64, c Color]Draws a crisp 1px rounded rectangle border matching fill-rounded-rect.
fill-circlefill-circle = fn [mut cv Canvas, cx i64, cy i64, r i64, c Color]Draws a filled circle centered at (cx, cy) with radius r.
stroke-circlestroke-circle = fn [mut cv Canvas, cx i64, cy i64, r i64, c Color]Draws a 1px circle outline centered at (cx, cy) with radius r.
draw-line-smoothdraw-line-smooth = fn [mut cv Canvas, x0 i64, y0 i64, x1 i64, y1 i64, c Color]Draws an anti-aliased multi-pixel line from (x0, y0) to (x1, y1) with soft fringe.
draw-linedraw-line = fn [mut cv Canvas, x0 i64, y0 i64, x1 i64, y1 i64, c Color]Draws an integer Bresenham line from (x0, y0) to (x1, y1).
draw-chardraw-char = fn [mut cv Canvas, x i64, y i64, ch i64, scale i64, c Color]Draws a single 5x7 glyph scaled by scale at (x, y).
measure-text-widthmeasure-text-width = fn [text str, scale i64] i64Measures the pixel width of text rendered at integer scale.
draw-textdraw-text = fn [mut cv Canvas, x i64, y i64, text str, scale i64, c Color]Draws ASCII text at (x, y) using the built-in 5x7 bitmap font scaled by scale.
encode-bmpencode-bmp = fn [cv Canvas] bytesEncodes cv as an uncompressed 24-bit BMP image ('BM' header + bottom-up BGR rows).
encode-ppmencode-ppm = fn [cv Canvas] bytesEncodes cv as a binary Netpbm PPM (P6) RGB24 image.

Verified Doctest (ui/canvas/rgba)

VEKO
use [cv = ui/canvas]
c = cv/rgba 34 211 238 255
if c.r != 34 or c.g != 211 or c.b != 238 or c.a != 255 [ err 'rgba' ] else [ .ok ]

Module ui/font

Exported Functions

SymbolSignatureDescription
line-heightline-height = fn [size i64] i64Returns the vertical line height in pixels for font size (1 = 12px, 2 = 20px, 3 = 28px).
measure-textmeasure-text = fn [text str, size i64] i64Measures the pixel width of text rendered with proportional kerning at size.
measure-monomeasure-mono = fn [text str, size i64] i64Measures fixed-width monospace text width at size.
draw-textdraw-text = fn [mut c cv/Canvas, x i64, y i64, text str, size i64, col cv/Color]Draws mixed-case proportional UI text at (x, y) at size (1 = 12px body, 2 = 18px heading, 3 = 27px display).
draw-bolddraw-bold = fn [mut c cv/Canvas, x i64, y i64, text str, size i64, col cv/Color]Draws semi-bold proportional UI text (ideal for card headers, active tabs, and primary badges).
draw-monodraw-mono = fn [mut c cv/Canvas, x i64, y i64, text str, size i64, col cv/Color]Draws fixed-width mixed-case monospace text at (x, y) (ideal for code, numeric columns, and metrics).
draw-truncateddraw-truncated = fn [mut c cv/Canvas, x i64, y i64, max_w i64, text str, size i64, col cv/Color]Draws proportional text truncated with '...' if its pixel width exceeds max_w.
draw-bulletsdraw-bullets = fn [mut c cv/Canvas, x i64, y i64, count i64, size i64, col cv/Color] i64Draws count masked secret bullet dots at (x, y) without inspecting secret content.

Verified Doctest (ui/font/measure-text)

VEKO
use [fnt = ui/font]
w1 = fnt/measure-text 'Veko UI' 1
w2 = fnt/measure-text 'Veko UI' 2
if w1 <= 20 or w2 != (w1 * 2) [ err 'measure-text' ] else [ .ok ]

Module ui/layout

Exported Structs & Interfaces

  • Box: Box = struct { x i64, y i64, w i64, h i64 } — Axis-aligned integer layout rectangle.
  • Track: Track = struct { kind i64, value i64 } — 1D flex/grid track specification (kind == 0 fixed pixels; kind == 1 proportional flex weight).
  • Span: Span = struct { offset i64, length i64 } — Solved 1D [offset, length] span along an axis.
  • ClipStack: ClipStack = struct { frames block[Box] } — Stack of nested clipping boxes for scrollable containers, split panes, and modals.

Exported Functions

SymbolSignatureDescription
pxpx = fn [pixels i64] TrackCreates a fixed-pixel Track.
flexflex = fn [weight i64] TrackCreates a proportional flex-grow Track (weight >= 1).
solve-trackssolve-tracks = fn [origin i64, total_len i64, tracks block[Track], gap i64] block[Span]Solves a 1D list of Tracks across [origin .. origin + total_len] with inter-track gap.
pad-edgespad-edges = fn [b Box, top i64, right i64, bottom i64, left i64] BoxInsets b by (top, right, bottom, left) padding.
padpad = fn [b Box, p i64] BoxUniformly insets b on all 4 sides by p pixels.
flex-rowflex-row = fn [bounds Box, tracks block[Track], gap i64] block[Box]Lays out horizontal columns inside bounds from tracks with gap.
flex-colflex-col = fn [bounds Box, tracks block[Track], gap i64] block[Box]Lays out vertical rows inside bounds from tracks with gap.
gridgrid = fn [bounds Box, rows i64, cols i64, row_gap i64, col_gap i64] block[Box]Lays out a 2D rows x cols uniform grid inside bounds (row-major r * cols + c).
split-hsplit-h = fn [bounds Box, ratio_pct i64, divider_w i64] block[Box]Splits bounds horizontally into [left_box, divider_box, right_box] at ratio_pct (10..90).
split-vsplit-v = fn [bounds Box, ratio_pct i64, divider_h i64] block[Box]Splits bounds vertically into [top_box, divider_box, bottom_box] at ratio_pct (10..90).
new-clip-stacknew-clip-stack = fn [] ClipStackCreates an empty ClipStack.
push-clippush-clip = fn [mut cs ClipStack, mut c cv/Canvas, rect Box]Pushes an intersected clip box onto cs and activates it on c.
pop-clippop-clip = fn [mut cs ClipStack, mut c cv/Canvas]Pops the top clip box from cs and restores the parent clip (or full canvas if empty).

Verified Doctest (ui/layout/solve-tracks)

VEKO
use [lay = ui/layout]
spans = lay/solve-tracks 10 310 [(lay/px 100) (lay/flex 1) (lay/flex 1)] 5
if (len spans) != 3 or spans[0].length != 100 or spans[1].length != 100 or spans[2].offset != 220 [
    err 'solve-tracks'
] else [ .ok ]

Module ui/wayland

Exported Structs & Interfaces

  • WlMsgHdr: WlMsgHdr = struct { object_id i64, opcode i64, size i64 } — Decoded 8-byte Wayland wire message header.
  • WlGlobal: WlGlobal = struct { name i64, interface str, version i64 } — Decoded wl_registry.global advertisement event (opcode 0).

Exported Functions

SymbolSignatureDescription
wl-display-idwl-display-id = fn [] i64Exported ui/wayland/wl-display-id operation.
shm-format-argb8888shm-format-argb8888 = fn [] i64Exported ui/wayland/shm-format-argb8888 operation.
shm-format-xrgb8888shm-format-xrgb8888 = fn [] i64Exported ui/wayland/shm-format-xrgb8888 operation.
socket-pathsocket-path = fn [xdg_runtime_dir str, wayland_display str] strResolves the canonical AF_UNIX Wayland socket path from XDG_RUNTIME_DIR and WAYLAND_DISPLAY.
encode-hdrencode-hdr = fn [object_id i64, opcode i64, size i64] bytesEncodes an 8-byte Wayland wire header (object_id, (size << 16) | opcode).
decode-hdrdecode-hdr = fn [pkt bytes, off i64] WlMsgHdrDecodes an 8-byte Wayland wire header at off inside pkt.
push-str-argpush-str-arg = fn [mut buf bytes, s str] i64Appends a Wayland NUL-terminated 32-bit padded string argument to buf and returns bytes written.
encode-syncencode-sync = fn [callback_id i64] bytesEncodes wl_display@1.sync(callback_id) (opcode 0, 12 bytes).
encode-get-registryencode-get-registry = fn [registry_id i64] bytesEncodes wl_display@1.get_registry(registry_id) (opcode 1, 12 bytes).
encode-registry-bindencode-registry-bind = fn [registry_id i64, global_name i64, iface str, version i64, new_id i64] bytesEncodes wl_registry.bind(name, interface, version, new_id) (opcode 0, untyped new_id wire layout).
parse-registry-globalparse-registry-global = fn [pkt bytes, body_off i64] WlGlobalParses a wl_registry.global event body starting at off (after the 8-byte header).
encode-create-surfaceencode-create-surface = fn [compositor_id i64, surface_id i64] bytesEncodes wl_compositor.create_surface(surface_id) (opcode 0, 12 bytes).
encode-shm-create-poolencode-shm-create-pool = fn [shm_id i64, pool_id i64, byte_size i64] bytesEncodes wl_shm.create_pool(pool_id, byte_size) (opcode 0, 16 bytes; fd passed via SCM_RIGHTS).
encode-pool-create-bufferencode-pool-create-buffer = fn [pool_id i64, buf_id i64, offset i64, w i64, h i64, stride i64, fmt i64] bytesEncodes wl_shm_pool.create_buffer(buf_id, offset, w, h, stride, format) (opcode 0, 32 bytes).
encode-get-xdg-surfaceencode-get-xdg-surface = fn [wm_base_id i64, xdg_surf_id i64, wl_surf_id i64] bytesEncodes xdg_wm_base.get_xdg_surface(xdg_surf_id, wl_surf_id) (opcode 2, 16 bytes).
encode-xdg-pongencode-xdg-pong = fn [wm_base_id i64, serial i64] bytesEncodes xdg_wm_base.pong(serial) (opcode 3, 12 bytes).
encode-get-toplevelencode-get-toplevel = fn [xdg_surf_id i64, toplevel_id i64] bytesEncodes xdg_surface.get_toplevel(toplevel_id) (opcode 1, 12 bytes).
encode-ack-configureencode-ack-configure = fn [xdg_surf_id i64, serial i64] bytesEncodes xdg_surface.ack_configure(serial) (opcode 4, 12 bytes).
encode-set-titleencode-set-title = fn [toplevel_id i64, title str] bytesEncodes xdg_toplevel.set_title(title) (opcode 2).
encode-surface-presentencode-surface-present = fn [surface_id i64, buf_id i64, w i64, h i64] bytesEncodes pipelined wl_surface.attach(buf_id, 0, 0) + wl_surface.damage(0, 0, w, h) + wl_surface.commit() (52 bytes).

Verified Doctest (ui/wayland/socket-path)

VEKO
use [wl = ui/wayland]
p1 = wl/socket-path '/run/user/1000' ''
p2 = wl/socket-path '/run/user/1000' 'wayland-1'
p3 = wl/socket-path '/run/user/1000' '/tmp/custom-wl-0'
if p1 != '/run/user/1000/wayland-0' or p2 != '/run/user/1000/wayland-1' or p3 != '/tmp/custom-wl-0' [
    err 'bad wayland socket path'
] else [ .ok ]

Module ui/widgets

Exported Structs & Interfaces

  • Rect: Rect = struct { x i64, y i64, w i64, h i64 } — Axis-aligned integer bounding box.
  • Theme: Theme = struct { bg cv/Color, surface cv/Color, surface_hover cv/Color, border cv/Color, text cv/Color, muted cv/Color, accent cv/Color, accent_text cv/Color, success cv/Color, warning cv/Color, danger cv/Color } — Color theme palette for immediate-mode widgets.
  • UiState: UiState = struct { mouse_x i64 = ..., mouse_y i64 = ..., mouse_down bool = ..., mouse_clicked bool = ..., mouse_rclicked bool = ..., wheel_dy i64 = ..., key_code i64 = ..., text_char i64 = ..., hot_id str = ..., active_id str = ..., focused_id str = ..., selected_id str = ..., open_popup_id str = ..., clipboard str = ..., clipboard_dirty bool = ..., dpi_scale i64 = ..., clip_stack block[Rect] = ..., key_mods i64 = ..., shift_down bool = ..., ctrl_down bool = ..., alt_down bool = ..., key_consumed bool = ..., focus_order block[str] = ..., next_focus_order block[str] = ..., focus_scope_prefix str = ... } — Per-frame pointer, wheel, keyboard, focus, popup, and clipboard state for immediate-mode widgets.
  • SplitResult: SplitResult = struct { first Rect, second Rect, ratio_pct i64 } — Result returned by split-pane-state carrying both pane Rects and updated mouse-dragged ratio_pct.
  • EditorSnap: EditorSnap = struct { text str, cursor i64, anchor i64 } — Undo/redo history snapshot for EditorState.
  • EditorState: EditorState = struct { text str = ..., cursor i64 = ..., sel_anchor i64 = ..., pref_col i64 = ..., scroll_line i64 = ..., scroll_col i64 = ..., undo_stack block[EditorSnap] = ..., redo_stack block[EditorSnap] = ..., tab_width i64 = ..., syntax_vk bool = ... } — Persistent state for code-editor (multi-line cursor, selection, scroll, 64-step undo/redo, Veko syntax highlighting).
  • CommandItem: CommandItem = struct { id str, label str, category str = ..., shortcut str = ... } — Action entry displayed in command-palette.
  • PaletteState: PaletteState = struct { open bool = ..., query str = ..., selected i64 = ..., scroll i64 = ... } — Persistent state for command-palette.
  • FileEntry: FileEntry = struct { name str, is_dir bool = ..., size i64 = ... } — Pure-data directory or file entry displayed in file-picker.
  • FilePickerState: FilePickerState = struct { open bool = ..., dir str = ..., filename str = ..., ext_filter str = ..., filter_on bool = ..., selected i64 = ..., scroll_y i64 = ... } — Persistent state for file-picker.
  • FilePickerResult: FilePickerResult = struct { action enum, path str = ... } — Result returned each frame by file-picker (action in .none, .selected, .cancelled, .chdir).
  • TreeNode: TreeNode = struct { id str, label str, depth i64 = ..., expanded bool = ..., has_children bool = ..., badge str = ... } — Hierarchical node descriptor for tree-view.
  • ModalResult: ModalResult = struct { card Rect, body Rect, closed bool } — Result returned by modal carrying the outer dialog card, inner content Rect, and close-button hit state.
  • ChartSeries: ChartSeries = struct { name str, values block, color cv/Color } — Multi-series data descriptor for line-chart.

Exported Functions

SymbolSignatureDescription
MOD-SHIFTMOD-SHIFT = fn [] i64Keyboard modifier & virtual key constants (mirroring ui/MOD-* and ui/KEY-* with zero .ui capability).
MOD-CTRLMOD-CTRL = fn [] i64Exported ui/widgets/MOD-CTRL operation.
MOD-ALTMOD-ALT = fn [] i64Exported ui/widgets/MOD-ALT operation.
KEY-BACKSPACEKEY-BACKSPACE = fn [] i64Exported ui/widgets/KEY-BACKSPACE operation.
KEY-TABKEY-TAB = fn [] i64Exported ui/widgets/KEY-TAB operation.
KEY-ENTERKEY-ENTER = fn [] i64Exported ui/widgets/KEY-ENTER operation.
KEY-SHIFTKEY-SHIFT = fn [] i64Exported ui/widgets/KEY-SHIFT operation.
KEY-CTRLKEY-CTRL = fn [] i64Exported ui/widgets/KEY-CTRL operation.
KEY-ALTKEY-ALT = fn [] i64Exported ui/widgets/KEY-ALT operation.
KEY-ESCKEY-ESC = fn [] i64Exported ui/widgets/KEY-ESC operation.
KEY-SPACEKEY-SPACE = fn [] i64Exported ui/widgets/KEY-SPACE operation.
KEY-PAGE-UPKEY-PAGE-UP = fn [] i64Exported ui/widgets/KEY-PAGE-UP operation.
KEY-PAGE-DOWNKEY-PAGE-DOWN = fn [] i64Exported ui/widgets/KEY-PAGE-DOWN operation.
KEY-ENDKEY-END = fn [] i64Exported ui/widgets/KEY-END operation.
KEY-HOMEKEY-HOME = fn [] i64Exported ui/widgets/KEY-HOME operation.
KEY-LEFTKEY-LEFT = fn [] i64Exported ui/widgets/KEY-LEFT operation.
KEY-UPKEY-UP = fn [] i64Exported ui/widgets/KEY-UP operation.
KEY-RIGHTKEY-RIGHT = fn [] i64Exported ui/widgets/KEY-RIGHT operation.
KEY-DOWNKEY-DOWN = fn [] i64Exported ui/widgets/KEY-DOWN operation.
KEY-DELETEKEY-DELETE = fn [] i64Exported ui/widgets/KEY-DELETE operation.
dark-themedark-theme = fn [] ThemeDefault dark theme (Slate 900 / Cyan 400).
light-themelight-theme = fn [] ThemeDefault crisp studio light theme (Slate 50 / Sky 600).
new-statenew-state = fn [] UiStateCreates a fresh UiState.
register-focusableregister-focusable = fn [mut st UiState, id str] boolRegisters id in the current frame's Tab-focus ring (respecting st.focus_scope_prefix) and returns true when id is focused.
cycle-focuscycle-focus = fn [mut st UiState, reverse bool] strAdvances (reverse == false) or reverses (reverse == true) st.focused_id along st.focus_order.
draw-focus-ringdraw-focus-ring = fn [mut c cv/Canvas, r Rect, radius i64, th Theme]Draws a soft keyboard focus halo + border ring around r.
apply-keyapply-key = fn [mut st UiState, key i64, text_ch i64, sh bool, ct bool, al bool]Injects a deterministic keyboard event (key, text_ch, and optional /shift, /ctrl, /alt modifiers) for scripted UI frames & tests.
apply-mouseapply-mouse = fn [mut st UiState, x i64, y i64, down bool, clicked bool]Updates pointer coordinates and click state for the current frame.
apply-eventsapply-events = fn [mut st UiState, events block] boolFeeds a frame batch of ui/UiEvent structs (or maps with .kind, .x, .y, .key, .btn) into st.
rect-contains?rect-contains? = fn [r Rect, px i64, py i64] boolReturns true if point (px, py) lies inside r.
insetinset = fn [r Rect, pad i64] RectShrinks r uniformly on all 4 sides by pad pixels.
inset-edgesinset-edges = fn [r Rect, top i64, right i64, bottom i64, left i64] RectInsets r asymmetrically by (top, right, bottom, left).
vstackvstack = fn [bounds Rect, heights block, gap i64] block[Rect]Splits bounds vertically into stacked Rects with fixed heights and spacing gap.
hstackhstack = fn [bounds Rect, widths block, gap i64] block[Rect]Splits bounds horizontally into side-by-side Rects with fixed widths and spacing gap.
pxpx = fn [pixels i64] lay/TrackCreates a fixed-pixel flex track (lay/Track).
flexflex = fn [weight i64] lay/TrackCreates a proportional flex-grow track (lay/Track).
flex-rowflex-row = fn [bounds Rect, tracks block[lay/Track], gap i64] block[Rect]Solves horizontal flex columns inside bounds using w/px and w/flex tracks.
flex-colflex-col = fn [bounds Rect, tracks block[lay/Track], gap i64] block[Rect]Solves vertical flex rows inside bounds using w/px and w/flex tracks.
gridgrid = fn [bounds Rect, rows i64, cols i64, gap i64] block[Rect]Solves a rows x cols uniform 2D grid inside bounds (row-major).
push-clippush-clip = fn [mut st UiState, mut c cv/Canvas, r Rect]Pushes a nested clipping rectangle onto st and activates it on c.
pop-clippop-clip = fn [mut st UiState, mut c cv/Canvas]Pops the top clipping rectangle from st and restores the previous clip on c.
panelpanel = fn [mut c cv/Canvas, r Rect, title str, th Theme]Widget 1: Draws a rounded surface card with a 1px border and optional header title band.
panel-bodypanel-body = fn [r Rect, has_title bool, pad i64] RectReturns the usable inner body Rect of a panel below its header band.
labellabel = fn [mut c cv/Canvas, x i64, y i64, text str, scale i64, col cv/Color]Widget 2: Draws mixed-case proportional UI text at (x, y).
headingheading = fn [mut c cv/Canvas, x i64, y i64, text str, scale i64, col cv/Color]Draws semi-bold heading text at (x, y).
buttonbutton = fn [mut c cv/Canvas, mut st UiState, id str, r Rect, text str, th Theme, is_primary bool] boolWidget 3: Draws an interactive rounded button and returns true when clicked in this frame. Supports /primary true for high-emphasis accent fill.
icon-buttonicon-button = fn [mut c cv/Canvas, mut st UiState, id str, r Rect, icon str, th Theme] boolWidget 4: Draws a compact vector icon button ('plus', 'check', 'close', 'search', 'refresh', 'play', 'folder', 'settings').
badgebadge = fn [mut c cv/Canvas, x i64, y i64, text str, kind str, th Theme] i64Widget 5: Draws a semantic pill badge (kind in 'ok', 'warn', 'err', 'info', 'neutral') and returns its width.
stat-cardstat-card = fn [mut c cv/Canvas, r Rect, title str, metric str, delta str, kind str, th Theme]Widget 6: Draws a KPI metric summary card with muted label, bold scale-2 metric, and delta status badge.
text-inputtext-input = fn [mut c cv/Canvas, mut st UiState, id str, r Rect, val str, placeholder str, th Theme, masked bool] strWidget 7: Interactive single-line text input with placeholder, focus ring, keyboard editing, and optional /secret bullet masking.
secret-inputsecret-input = fn [mut c cv/Canvas, mut st UiState, id str, r Rect, mut secret_buf secret bytes, bullet_count i64, placeholder str, th Theme] i64.secret-safe masked input widget operating directly on a mut secret bytes buffer without converting to str.
text-areatext-area = fn [mut c cv/Canvas, mut st UiState, id str, r Rect, val str, th Theme] strWidget 8: Multi-line editable text area with line numbers and clipped viewport.
checkboxcheckbox = fn [mut c cv/Canvas, mut st UiState, id str, x i64, y i64, text str, checked bool, th Theme] boolWidget 9: Interactive checkbox with crisp vector checkmark and clickable label; returns updated checked state.
toggle-switchtoggle-switch = fn [mut c cv/Canvas, mut st UiState, id str, x i64, y i64, text str, on bool, th Theme] boolWidget 10: Interactive pill toggle switch with sliding circular thumb; returns updated on state.
radio-groupradio-group = fn [mut c cv/Canvas, mut st UiState, id str, r Rect, options block, selected i64, th Theme] i64Widget 11: Interactive radio button group (options list) stacked vertically inside r; returns selected index.
sliderslider = fn [mut c cv/Canvas, mut st UiState, id str, r Rect, val i64, min_v i64, max_v i64, th Theme] i64Widget 12: Horizontal range slider (min_v..max_v) with filled track, circular thumb, and value label; returns updated value.
progress-barprogress-bar = fn [mut c cv/Canvas, r Rect, pct i64, th Theme, show_pct bool]Widget 13: Draws a horizontal progress bar inside r filled to pct (0..100).
dropdowndropdown = fn [mut c cv/Canvas, mut st UiState, id str, r Rect, options block, selected i64, th Theme] i64Widget 14: Select dropdown trigger + popup menu (st.open_popup_id == id controls open state); returns selected index.
chip-groupchip-group = fn [mut c cv/Canvas, mut st UiState, id str, r Rect, labels block, active_flags block, th Theme] i64Widget 15: Horizontal filter/tag chip group (active_flags bool list); toggles clicked chip and returns clicked index (or -1).
tabstabs = fn [mut c cv/Canvas, mut st UiState, id str, r Rect, labels block, active i64, th Theme] i64Widget 16: Segmented single-view tab bar (labels); returns the active tab index.
begin-scrollbegin-scroll = fn [mut c cv/Canvas, mut st UiState, id str, r Rect, content_h i64, scroll_y i64, th Theme] i64Widget 17: Begins a clipped scrollable viewport with scrollbar track/thumb and mouse-wheel scrolling; returns updated scroll_y.
end-scrollend-scroll = fn [mut st UiState, mut c cv/Canvas]Ends a begin-scroll viewport and restores the parent clip rectangle.
list-viewlist-view = fn [mut c cv/Canvas, r Rect, items block, selected i64, th Theme]Widget 18: Draws a selectable list view inside r (backward-compatible 5-arg form).
select-listselect-list = fn [mut c cv/Canvas, mut st UiState, id str, r Rect, items block, selected i64, th Theme] i64Interactive list view returning the newly selected row index on click or Up/Down arrow keys.
data-tabledata-table = fn [mut c cv/Canvas, mut st UiState, id str, r Rect, headers block, col_tracks block[lay/Track], rows block, selected_row i64, th Theme] i64Widget 19: Multi-column data table (headers str list, col_tracks lay/Track list, rows 2D block) with zebra rows & row selection.
tree-viewtree-view = fn [mut c cv/Canvas, mut st UiState, id str, r Rect, nodes block[TreeNode], selected_id str, th Theme] strWidget 20: Hierarchical tree view (nodes of TreeNode) with disclosure triangles, folder/item icons, and optional badges.
split-panesplit-pane = fn [mut c cv/Canvas, mut st UiState, id str, bounds Rect, vertical bool, ratio_pct i64, th Theme] block[Rect]Widget 21: Resizable horizontal or vertical split pane; draws interactive grip handle and returns [first_rect, second_rect].
split-pane-statesplit-pane-state = fn [mut c cv/Canvas, mut st UiState, id str, bounds Rect, vertical bool, ratio_pct i64, th Theme] SplitResultStateful mouse-draggable variant of split-pane returning SplitResult { first, second, ratio_pct }.
menu-barmenu-bar = fn [mut c cv/Canvas, mut st UiState, id str, r Rect, brand str, items block, active_idx i64, th Theme] i64Widget 22: Top application menu bar (items str list); returns clicked menu index (or -1).
context-menucontext-menu = fn [mut c cv/Canvas, mut st UiState, id str, x i64, y i64, w_px i64, items block, th Theme] i64Widget 23: Floating context menu card (items of [label shortcut] or str, '-' for divider); returns clicked item index (or -1).
modalmodal = fn [mut c cv/Canvas, mut st UiState, id str, viewport Rect, dialog_w i64, dialog_h i64, title str, th Theme] ModalResultWidget 24: Modal lightbox overlay over viewport; draws dimmed backdrop + centered card + close button, returning ModalResult.
toasttoast = fn [mut c cv/Canvas, r Rect, title str, message str, kind str, th Theme]Widget 25: Non-blocking toast notification card (kind in 'ok', 'warn', 'err', 'info').
tooltiptooltip = fn [mut c cv/Canvas, x i64, y i64, text str, th Theme]Widget 26: Floating high-contrast tooltip callout anchored at (x, y).
sparklinesparkline = fn [mut c cv/Canvas, r Rect, vals block, col cv/Color, th Theme]Widget 27: Draws an anti-aliased sparkline with soft area tint inside r normalized to [min(vals)..max(vals)].
bar-chartbar-chart = fn [mut c cv/Canvas, r Rect, categories block, values block, bar_col cv/Color, th Theme]Widget 28: Labeled vertical column chart with gridlines, Y-axis scale ticks, value labels, and category axis.
line-chartline-chart = fn [mut c cv/Canvas, r Rect, x_labels block, series_list block[ChartSeries], th Theme]Widget 29: Multi-series anti-aliased line chart (series_list of ChartSeries) with gridlines, markers, X labels, and legend.
new-editornew-editor = fn [initial str] EditorStateCreates a fresh EditorState initialized with initial source text and cursor at the end.
code-editorcode-editor = fn [mut c cv/Canvas, mut st UiState, id str, r Rect, mut ed EditorState, th Theme] strWidget 30: Multi-line Veko studio code editor with line numbers, click/drag & Shift selection, clipboard (Ctrl+A/C/X/V), 64-step Ctrl+Z/Ctrl+Y undo/redo, auto-indent, and Veko syntax highlighting.
fuzzy-scorefuzzy-score = fn [query str, candidate str] i64Pure-Veko subsequence + word-boundary + consecutive-run fuzzy scorer (-1 if query does not match candidate).
command-palettecommand-palette = fn [mut c cv/Canvas, mut st UiState, id str, viewport Rect, mut ps PaletteState, items block[CommandItem], th Theme] strWidget 31: Fuzzy-searchable Studio Command Palette overlay (Ctrl+K / Ctrl+P style). Returns the executed CommandItem.id (and closes ps.open = false), or '' if still open / dismissed.
entries-from-listentries-from-list = fn [items block] block[FileEntry]Converts { name = str, is_dir = bool, size = i64 } maps (e.g. from fs/list-entries) into typed FileEntry values.
file-pickerfile-picker = fn [mut c cv/Canvas, mut st UiState, id str, viewport Rect, mut fp FilePickerState, entries block[FileEntry], th Theme, is_save bool] FilePickerResultWidget 32: Pure-Veko zero-capability modal File Picker (entries of FileEntry, /save true for Save dialog). Returns FilePickerResult with action in .none, .selected, .cancelled, or .chdir.

Verified Doctest (ui/widgets/vstack)

VEKO
use [w = ui/widgets]
rows = w/vstack (w/Rect { x = 10, y = 10, w = 200, h = 100 }) [20 30] 8
if (len rows) != 2 or rows[1].y != 38 [ err 'vstack' ] else [ .ok ]

Module ui/x11

Exported Structs & Interfaces

  • X11Setup: X11Setup = struct { id_base i64, id_mask i64, root_window i64, white_pixel i64, root_visual i64, root_depth i64 } — Parsed X11 server setup parameters for the default root screen.
  • X11Band: X11Band = struct { y i64, height i64, req_words i64, byte_count i64 } — One scanline band descriptor (y offset + height rows) for chunked PutImage transmission.
  • X11Event: X11Event = struct { kind i64, x i64, y i64, key i64, btn i64 } — Decoded 32-byte X11 wire event mapped to canonical Veko ui event fields (kind, x, y, key, btn).

Exported Functions

SymbolSignatureDescription
display-socket-pathdisplay-socket-path = fn [display str] strResolves the canonical AF_UNIX socket path (e.g. '/tmp/.X11-unix/X0') from a DISPLAY string (':0', 'unix:1.0').
parse-xauthority-cookieparse-xauthority-cookie = fn [raw bytes] bytesExtracts the first 16-byte MIT-MAGIC-COOKIE-1 token from raw .Xauthority bytes (or empty bytes if absent).
encode-setupencode-setup = fn [cookie bytes] bytesEncodes the little-endian X11 connection setup packet (12 bytes unauthenticated, or 48 bytes with a 16-byte MIT-MAGIC-COOKIE-1).
parse-setup-replyparse-setup-reply = fn [pkt bytes] X11SetupParses a complete X11 Setup reply buffer (8-byte header + body) into X11Setup.
encode-window-initencode-window-init = fn [setup X11Setup, wid i64, gcid i64, title str, w i64, h i64] bytesEncodes pipelined CreateWindow + CreateGC + ChangeProperty(WM_NAME) + MapWindow core requests.
plan-put-image-bandsplan-put-image-bands = fn [w i64, h i64] block[X11Band]Plans scanline bands (<= 128 KB pixel payload per packet) so PutImage never exceeds X11's 16-bit 4-byte-word request cap (262,140 bytes).
encode-put-image-bandencode-put-image-band = fn [wid i64, gcid i64, depth i64, rgba bytes, w i64, band X11Band] bytesEncodes one 24-byte PutImage (ZPixmap) band packet + BGRA-swizzled scanlines from rgba.
decode-event-32decode-event-32 = fn [ev bytes] X11EventDecodes a 32-byte X11 wire event packet into a canonical X11Event (kind = 0 when ignored).

Verified Doctest (ui/x11/display-socket-path)

VEKO
use [x11 = ui/x11]
p0 = x11/display-socket-path ':0'
p2 = x11/display-socket-path 'unix:2.0'
if p0 != '/tmp/.X11-unix/X0' or p2 != '/tmp/.X11-unix/X2' [ err 'bad x11 path' ] else [ .ok ]

Module ui

Exported Structs & Interfaces

  • UiEvent: UiEvent = struct { kind i64, x i64, y i64, key i64, btn i64 } — Structured window input event decoded from poll-events.
  • Window: Window = struct { handle i64, width i64, height i64, title str } — Handle to an open native or offscreen window surface.

Exported Functions

SymbolSignatureDescription
EV-CLOSEEV-CLOSE = fn [] i64Window event kind constants matching the 5-element PAL event tuples [kind x y key btn].
EV-KEYEV-KEY = fn [] i64Exported ui/EV-KEY operation.
EV-MOUSE-DOWNEV-MOUSE-DOWN = fn [] i64Exported ui/EV-MOUSE-DOWN operation.
EV-MOUSE-UPEV-MOUSE-UP = fn [] i64Exported ui/EV-MOUSE-UP operation.
EV-MOUSE-MOVEEV-MOUSE-MOVE = fn [] i64Exported ui/EV-MOUSE-MOVE operation.
EV-RESIZEEV-RESIZE = fn [] i64Exported ui/EV-RESIZE operation.
EV-TEXTEV-TEXT = fn [] i64Exported ui/EV-TEXT operation.
EV-WHEELEV-WHEEL = fn [] i64Exported ui/EV-WHEEL operation.
EV-KEY-UPEV-KEY-UP = fn [] i64Exported ui/EV-KEY-UP operation.
MOD-SHIFTMOD-SHIFT = fn [] i64Keyboard modifier bitmask constants (UiEvent.btn on EV-KEY / EV-KEY-UP or UiState.key_mods).
MOD-CTRLMOD-CTRL = fn [] i64Exported ui/MOD-CTRL operation.
MOD-ALTMOD-ALT = fn [] i64Exported ui/MOD-ALT operation.
KEY-BACKSPACEKEY-BACKSPACE = fn [] i64Standard cross-platform virtual key constants (UiEvent.key on EV-KEY / EV-KEY-UP).
KEY-TABKEY-TAB = fn [] i64Exported ui/KEY-TAB operation.
KEY-ENTERKEY-ENTER = fn [] i64Exported ui/KEY-ENTER operation.
KEY-SHIFTKEY-SHIFT = fn [] i64Exported ui/KEY-SHIFT operation.
KEY-CTRLKEY-CTRL = fn [] i64Exported ui/KEY-CTRL operation.
KEY-ALTKEY-ALT = fn [] i64Exported ui/KEY-ALT operation.
KEY-ESCKEY-ESC = fn [] i64Exported ui/KEY-ESC operation.
KEY-SPACEKEY-SPACE = fn [] i64Exported ui/KEY-SPACE operation.
KEY-PAGE-UPKEY-PAGE-UP = fn [] i64Exported ui/KEY-PAGE-UP operation.
KEY-PAGE-DOWNKEY-PAGE-DOWN = fn [] i64Exported ui/KEY-PAGE-DOWN operation.
KEY-ENDKEY-END = fn [] i64Exported ui/KEY-END operation.
KEY-HOMEKEY-HOME = fn [] i64Exported ui/KEY-HOME operation.
KEY-LEFTKEY-LEFT = fn [] i64Exported ui/KEY-LEFT operation.
KEY-UPKEY-UP = fn [] i64Exported ui/KEY-UP operation.
KEY-RIGHTKEY-RIGHT = fn [] i64Exported ui/KEY-RIGHT operation.
KEY-DOWNKEY-DOWN = fn [] i64Exported ui/KEY-DOWN operation.
KEY-DELETEKEY-DELETE = fn [] i64Exported ui/KEY-DELETE operation.
BTN-LEFTBTN-LEFT = fn [] i64Mouse button constants carried in UiEvent.btn on EV-MOUSE-DOWN / EV-MOUSE-UP.
BTN-RIGHTBTN-RIGHT = fn [] i64Exported ui/BTN-RIGHT operation.
open-windowopen-window = fn [title str, w i64, h i64] WindowOpens a window surface titled title with dimensions w x h.
pollpoll = fn [win Window] block[UiEvent]Polls all pending OS input events for win without blocking.
present-rgbapresent-rgba = fn [win Window, rgba bytes, w i64, h i64]Presents a raw RGBA32 byte buffer (w * h * 4 bytes) to win.
present-canvaspresent-canvas = fn [win Window, c cv/Canvas]Presents a ui/canvas Canvas directly to win.
close-windowclose-window = fn [win Window]Closes win and releases OS/offscreen surface resources.
window-dpi-scalewindow-dpi-scale = fn [win Window] i64Queries the active Hi-DPI scaling percentage for win (100 = 96 DPI 1x, 150 = 1.5x, 200 = 2x Retina/4K).
clipboard-textclipboard-text = fn [] strReads UTF-8 plain text from the OS/session clipboard.
clipboard-secretclipboard-secret = fn [] secret strReads clipboard contents directly into a .secret-tainted str for pasting tokens/passwords without exposing plain str copies.
set-clipboardset-clipboard = fn [text str]Writes plain text to the OS/session clipboard (.secret values are statically and dynamically rejected).

Verified Doctest (ui/open-window)

VEKO
use [ui, cv = ui/canvas]
win = ui/open-window 'Veko Window' 64 32
mut c = cv/new-canvas 64 32
cv/clear mut c (cv/color-bg-dark)
_ = ui/present-canvas win c
evs = ui/poll win
_ = ui/close-window win
if (len evs) < 0 [ err 'events' ] else [ .ok ]

Module web

Exported Structs & Interfaces

  • Request: Request = struct { method str, path str, target str, query map[str], params map[str], headers map[str], body bytes } — Parsed HTTP/1.1 request passed to route handlers and middleware.
  • Response: Response = struct { status i64 = ..., reason str = ..., headers map[str] = ..., body bytes = ..., has_stream bool = ..., stream any = ..., stream_len i64 = ..., file_path str = ..., file_off i64 = ... } — HTTP/1.1 / HTTP/2 / HTTP/3 response returned by handlers and middleware (supports eager body, positioned file streaming, and io/Stream chunked/fixed streaming).
  • Route: Route = struct { method str, pattern str, handler any } — Single route entry (method: 'GET', 'POST', 'ANY', etc.; pattern: '/users/:id').
  • MultipartPart: MultipartPart = struct { name str, filename str, content_type str, data bytes } — One parsed part from a multipart/form-data request body.
  • App: App = struct { routes block[Route], middlewares block[any], static_prefix str = ..., static_root str = ..., max_header_bytes i64 = ..., max_body_bytes i64 = ... } — Web application container holding routes, middleware, body/header limits, and optional static file mount.
  • AsyncServerOpts: AsyncServerOpts = struct { max_requests i64 = ..., max_connections i64 = ..., max_reqs_per_conn i64 = ..., read_timeout dur = ..., idle_timeout dur = ..., tick_timeout dur = ..., max_header_bytes i64 = ..., max_body_bytes i64 = ... } — Configuration for serve-reactor.
  • AsyncConn: AsyncConn = struct { sock i64, token i64, state enum, rx bytes, tx bytes, tx_off i64, hdr_end i64, content_len i64, started_ns i64, reqs_served i64 = ..., keep_alive bool = ..., file_path str = ..., file_off i64 = ..., file_rem i64 = ... } — Per-connection non-blocking HTTP/1.1 state machine tracked inside serve-reactor (supports keep-alive reuse & positioned file streaming).
  • HttpsServerOpts: HttpsServerOpts = struct { max_requests i64 = ..., max_reqs_per_conn i64 = ..., handshake_timeout dur = ..., idle_timeout dur = ..., alt_svc str = ... } — Configuration for serve-tls-conn-opts, serve-https, and https-worker-loop.

Exported Functions

SymbolSignatureDescription
status-reasonstatus-reason = fn [code i64] strMaps standard HTTP status codes to default reason phrases.
new-appnew-app = fn [] AppCreates a new empty App.
add-routeadd-route = fn [mut app App, method str, pattern str, handler any]Registers a route handler (fn [req Request] Response) on app.
getget = fn [mut app App, pattern str, handler any]Registers a GET route handler (also automatically serves HEAD with empty body unless an explicit HEAD route matches first).
headhead = fn [mut app App, pattern str, handler any]Registers an explicit HEAD route handler.
postpost = fn [mut app App, pattern str, handler any]Registers a POST route handler.
put-routeput-route = fn [mut app App, pattern str, handler any]Registers a PUT route handler.
delete-routedelete-route = fn [mut app App, pattern str, handler any]Registers a DELETE route handler.
use-mwuse-mw = fn [mut app App, mw any]Appends a middleware (fn [req Request, next any] Response) to app.
mount-staticmount-static = fn [mut app App, url_prefix str, root_dir str]Mounts a static file directory under url_prefix (e.g. '/static').
responseresponse = fn [status i64, content_type str, body bytes] ResponseBuilds a generic Response with explicit status, content-type, and body bytes.
stream-responsestream-response = fn [status i64, content_type str, s io/Stream, content_len i64] ResponseBuilds a streaming Response reading from s (content_len >= 0 emits Content-Length; content_len < 0 emits HTTP/1.1 Transfer-Encoding: chunked).
chunked-responsechunked-response = fn [status i64, content_type str, s io/Stream] ResponseBuilds an HTTP/1.1 Transfer-Encoding: chunked (or HTTP/2 DATA-streamed) Response from s.
encode-chunkencode-chunk = fn [chunk bytes] bytesFormats a single HTTP/1.1 chunk (<hex>\r\n<chunk>\r\n, or '0\r\n\r\n' when len chunk == 0).
texttext = fn [status i64, body str] ResponseBuilds a UTF-8 text/plain response.
htmlhtml = fn [status i64, body str] ResponseBuilds a UTF-8 text/html response.
viewview = fn [status i64, node any] ResponseRenders a pure-Veko html/Node or Hiccup component block ([.div { class = 'x' } ['hi']]) as a text/html response.
pagepage = fn [status i64, title str, head_extra block, body_children block] ResponseRenders a complete HTML5 <!DOCTYPE html> document from pure-Veko components as a text/html response.
json-respjson-resp = fn [status i64, val any] ResponseBuilds an application/json response by JSON-encoding val.
redirectredirect = fn [status i64, location str] ResponseBuilds a redirect response (302 or 301).
sse-eventsse-event = fn [event_name str, data str, id str] strFormats one Server-Sent Events (SSE) payload (event: ...\ndata: ...\n\n).
sse-respsse-resp = fn [payload str] ResponseBuilds a text/event-stream SSE response containing one or more formatted events.
sse-writesse-write = fn [mut stream io/Stream, event_name str, data str, id str] i64Streams a live Server-Sent Event frame directly over an open io/Stream.
build-multipartbuild-multipart = fn [boundary str, fields map[str], files block[MultipartPart]] bytesEncodes an RFC 7578 multipart/form-data payload from text fields and binary files.
bad-requestbad-request = fn [msg str] ResponseConvenience error responses.
unauthorizedunauthorized = fn [msg str] ResponseExported web/unauthorized operation.
not-foundnot-found = fn [msg str] ResponseExported web/not-found operation.
server-errorserver-error = fn [msg str] ResponseExported web/server-error operation.
headerheader = fn [req Request, name str, default_val str] strLooks up a request header case-insensitively (returns default_val if absent).
query-getquery-get = fn [req Request, key str, default_val str] strReturns a query parameter or default_val.
paramparam = fn [req Request, key str, default_val str] strReturns a matched :param route parameter or default_val.
bind-jsonbind-json = fn [req Request] anyDecodes a JSON request body into a Veko value.
bind-formbind-form = fn [req Request] map[str]Decodes an application/x-www-form-urlencoded request body into map[str].
cookie-getcookie-get = fn [req Request, name str, default_val str] strExtracts a named cookie value from the Cookie request header (or default_val if absent).
match-patternmatch-pattern = fn [pattern str, path str] mapMatches a route pattern like '/users/:id/posts/*rest' against path. Returns { ok = true, params = map } or { ok = false, params = {} }.
parse-multipartparse-multipart = fn [body bytes, boundary str] block[MultipartPart]Parses a multipart/form-data body given its boundary string.
mime-typemime-type = fn [path str] strMaps common file extensions to MIME types.
stream-file-rangestream-file-range = fn [root_dir str, rel_path str, range_hdr str] ResponseStreams a static file (supporting Range: bytes=... 206 Partial Content) in 64 KiB positioned os/pread chunks with zero whole-file RAM allocation.
stream-filestream-file = fn [root_dir str, rel_path str] ResponseStreams a static file confined beneath root_dir without loading the file into RAM.
serve-static-rangeserve-static-range = fn [root_dir str, rel_path str, range_hdr str] ResponseServes a static file safely confined beneath root_dir (binary-safe, supporting HTTP Range: bytes=... 206 Partial Content; automatically switches to 64 KiB positioned file streaming for slices > 256 KiB).
serve-staticserve-static = fn [root_dir str, rel_path str] ResponseServes a static file safely confined beneath root_dir, rejecting path traversal.
mw-security-headersmw-security-headers = fn [req Request, next any] ResponseBuilt-in middleware that attaches defensive HTTP security headers.
use-security-headersuse-security-headers = fn [mut app App]Registers the built-in defensive HTTP security headers middleware on app.
handle-requesthandle-request = fn [app App, req Request] ResponseDispatches a Request through app's middleware chain and router (automatically stripping body on HEAD while preserving Content-Length).
parse-http-requestparse-http-request = fn [raw bytes] RequestDecodes raw HTTP/1.1 wire bytes into a structured Request.
encode-http-responseencode-http-response = fn [resp Response] bytesEncodes a Response into HTTP/1.1 wire bytes (materializing streamed payloads if invoked directly).
write-http-response-streamwrite-http-response-stream = fn [mut stream io/Stream, mut resp Response] i64Streams resp directly onto stream without whole-file RAM buffering (supports positioned file_path, fixed-length io/Stream, and Transfer-Encoding: chunked).
read-http-request-stream-limitsread-http-request-stream-limits = fn [mut stream io/Stream, max_header_bytes i64, max_body_bytes i64] RequestReads a complete HTTP/1.1 request enforcing max_header_bytes and max_body_bytes (returns err 'web: payload too large' on overflow).
read-http-request-streamread-http-request-stream = fn [mut stream io/Stream] RequestReads a complete HTTP/1.1 request (headers + Content-Length or chunked body) from an io/Stream.
serve-streamserve-stream = fn [mut stream io/Stream, app App] ResponseServes a single HTTP/1.1 request/response exchange over any io/Stream (TCP, TLS 1.3, or memory).
serve-onceserve-once = fn [ln any, app App] ResponseAccepts one connection from a TCP listener ln (net/listen-tcp) and serves one request.
serve-loopserve-loop = fn [ln any, app App, max_requests i64] i64Serves up to max_requests sequential connections on TCP listener ln.
serve-reactorserve-reactor = fn [ln any, app App, opts AsyncServerOpts] i64Serves concurrent HTTP/1.1 connections on a single thread using the OS readiness reactor (epoll on Linux, kqueue on macOS, IOCP+WSAPoll on Windows, WASI net-poll on Wasm). Supports HTTP/1.1 keep-alive reuse, max_connections DoS protection, 413 body limits, and 64 KiB non-blocking file streaming.
serve-asyncserve-async = fn [ln any, app App, max_requests i64] i64Convenience wrapper serving up to max_requests concurrent HTTP/1.1 connections via serve-reactor.
serve-h2-streamserve-h2-stream = fn [mut stream io/Stream, app App, max_requests i64, alt_svc str] i64Serves an RFC 9113 HTTP/2 connection over stream, dispatching each stream through app (with streaming DATA support & DoS guards).
serve-tls-conn-optsserve-tls-conn-opts = fn [sock i64, ident map, app App, opts HttpsServerOpts] i64Serves an accepted TCP socket sock over pure-Veko TLS 1.3 (ident) with explicit HttpsServerOpts deadlines & body limits.
serve-tls-connserve-tls-conn = fn [sock i64, ident map, app App, max_requests i64, alt_svc str] i64Serves an accepted TCP socket sock over pure-Veko TLS 1.3 (ident), automatically dispatching ALPN 'h2' to serve-h2-stream and 'http/1.1' to serve-stream.
https-accept-loophttps-accept-loop = fn [ln any, mut cert_reloader map, work_ch any, max_conns i64] i64Multi-core shared-nothing HTTPS acceptor: accepts sockets on ln, snapshots closure-free TLS ident from cert_reloader, and dispatches { sock, ident } onto bounded channel work_ch (shedding load cleanly on full backlog).
https-worker-loophttps-worker-loop = fn [work_ch any, app App, opts HttpsServerOpts] i64Multi-core shared-nothing HTTPS worker loop: consumes { sock, ident } jobs from work_ch and serves TLS 1.3 (h2 + http/1.1).
serve-httpsserve-https = fn [ln any, mut cert_reloader map, app App, max_conns i64, alt_svc str] i64Serves native HTTPS (TLS 1.3 + ALPN 'h2' / 'http/1.1' + zero-downtime certificate hot-reload) on TCP listener ln multiplexed with reactor so idle HTTP/1.1 keep-alive sockets never block new accepts.
serve-h3serve-h3 = fn [udp_sock i64, get_ident_fn any, app App, max_requests i64] i64Serves pure-Veko HTTP/3 over QUIC v1 on bound UDP socket udp_sock (net/udp-bind), dispatching to app.
make-acme-redirect-appmake-acme-redirect-app = fn [acme_webroot str, domain str, https_port i64] AppBuilds a dedicated port :80 App serving RFC 8555 Let's Encrypt /.well-known/acme-challenge/:token from acme_webroot and redirecting (301) all other HTTP requests to https://<domain>[:port]<target>.

Verified Doctest (web/match-pattern)

VEKO
use [web]
m = web/match-pattern '/api/:ver/items/:id' '/api/v1/items/42'
if not m.ok or (map/get m.params 'ver') != 'v1' or (map/get m.params 'id') != '42' [
  err 'route match'
] else [ .ok ]