veko-lang.org
Download Free EPUB 3.0

Part I · Language Foundations, Syntax, Cookbook & Tooling

Chapter 5

Idiomatic Veko Cookbook & Production Patterns

Copy-ready patterns for zero-flag workspaces, user /refinements, .secret templates, interfaces, asset embedding, regex, Zstd, and OTel

Practical, copy-ready recipes and side-by-side translations for developers arriving from Go, Rust, Zig, Python, and TypeScript — spanning CLI workspaces, /or error recovery, .secret hygiene, Zero-FFI SQLite ORM, HTTP/1.1 + HTTP/2 + QUIC HTTP/3 services, shared-nothing concurrency, homoiconic [ ... ] mini-DSLs, native desktop UIs, and WebAssembly 3.0 sandboxes.

The Veko Cookbook — Practical Recipes & Rosetta Stone
The Veko Cookbook — Practical Recipes & Rosetta Stone

Chapter 1: The Veko Rosetta Stone & Language Ergonomics

SYNTAX & HOMOICONICITY

Whitespace Disambiguation & Two-Pass Pratt Homoiconic Engine

How [tight] vs [spaced] tokens let kebab-case prefix calls coexist cleanly with infix math, UFCS chains, and macros.

LEXICAL DISAMBIGUATION lexer.vk TWO-PASS PRATT ENGINE parser.vk HOMOICONIC EVALUATION macro_eval.vk + lib/dialect.vk Token stream Typed literals Arity table AST + RawBlock Block values Lexer4 Whitespace Rules[tight] vs [spaced] bits LexerFirst-Class Literals5s, 64kb, 0xFF, '...' Parser Pass 1Pass 1: Signature Scanfn / struct / def / use Parser Pass 2Pass 2: Pratt PrecedenceBP 80 postfix .. BP 10 pipe Homoiconicityquote & composeCode-as-Data Templates Dialectsparse-block DialectsEmbedded Domain Grammars
Component & ModuleArchitectural Role
4 Whitespace Rules
lexer.vk
Eliminates grammar ambiguity using single-character attachment flags.
First-Class Literals
lexer.vk
Parses human-readable durations, binary sizes, hex/binary ints, and UTF-8 strings.
Pass 1: Signature Scan
parser.vk
Collects top-level function arities, refinements, structs, and module imports.
Pass 2: Pratt Precedence
parser.vk
Binds tight postfix chains, prefix word arguments, infix math, comparisons, and \ pipes.
quote & compose
macro_eval.vk
Treats [ ... ] blocks as inspectable values and splices computed expressions cleanly.
parse-block Dialects
parser.vk + lib/dialect.vk
Matches typed pattern rules over homoiconic blocks to drive custom DSLs.

Recipe 1.1: Translating Go, Rust, Python & TypeScript Habits into Idiomatic Veko

Newcomers write fluent Veko fastest when they see familiar constructs side-by-side with their idiomatic Veko counterparts:

TaskGo / Rust / Python / TS HabitIdiomatic Veko (.vk)
Call a 2-arg functionos.WriteFile(path, data)os/write-file path data
Nested call in math / loopwhile i < len(items)while i < (len items) [ ... ]
Call a 0-arg functionhostBinPath()host-bin-path
Subtraction & divisionn-1, total/countn - 1, total / count (spaces required!)
Negative literal argumentseek(fd, -1)seek fd -1 (tight -1, spaced after fd)
Strings & interpolationf"https://{host}:{port}"`https://{host}:{port}` or 'literal\n'
1-arg method chainsraw.trim().toLowerCase()raw.trim.lower
Multi-step data pipelineitems.filter(...).map(...)items \ filter fn [x] [...] \ map fn [x] [...]
In-place buffer mutationbuf.push(10) / push(&mut buf, 10)bytes/push mut buf 10 (mut on both sides)
Fallback on error / missing keyif err != nil / try...catchport = str/to-i64/or raw [ 443 ]
Propagate contextual errorreturn fmt.Errorf("...: %w", err)raw = os/read-file/or p [e -> return (err read {p}: {mold e})]
Unit return / JSON nullNone / null / () / nil.ok (unit action) and .null (wire JSON null)

Recipe 1.2: Side-by-Side Service Function — Go & Rust vs. Veko

Consider loading a JSON peer list over HTTPS with a 3-second timeout, falling back to a local cache file, filtering active endpoints, and returning trimmed URLs.

In Go (imperative error sprawl):

GO
func activePeers(endpoint string) ([]string, error) {
    client := &http.Client{Timeout: 3 * time.Second}
    resp, err := client.Get(endpoint)
    var raw []byte
    if err != nil {
        raw, err = os.ReadFile("peers.cache.json")
        if err != nil {
            return nil, err
        }
    } else {
        defer resp.Body.Close()
        raw, err = io.ReadAll(resp.Body)
        if err != nil {
            return nil, err
        }
    }
    var peers []Peer
    if err := json.Unmarshal(raw, &peers); err != nil {
        return nil, err
    }
    var urls []string
    for _, p := range peers {
        if p.Active {
            urls = append(urls, strings.TrimSpace(p.URL))
        }
    }
    return urls, nil
}

In Idiomatic Veko (peers.vk):

VEKO
use [nc = net/client, j = json]

pub active-peers = fn [endpoint str] block[str] [
    raw = (nc/get/or endpoint (nc/RequestOpts { timeout = 3s }) [
        body_str = os/read-file/or 'peers.cache.json' [e ->
            return (err `peer lookup failed: {mold e}`)
        ]
        nc/HttpResponse { status = 200, reason = 'OK', headers = {}, body = (bytes/from-str body_str), final_url = endpoint }
    ]).body

    (bytes/to-str raw)
        \ j/decode
        \ filter fn [p] [ p.active ]
        \ map fn [p] [ p.url.trim ]
]

Notice how Veko eliminates both hidden exceptions and repetitive if err != nil blocks while keeping every failure boundary explicit on the page.

Recipe 1.3: Readability & Writability vs. Other Languages

Because Veko combines single-owner ORO systems memory (Native, WebAssembly 3.0, and 64-bit VM targets with zero GC pauses) and Rebol/Elixir-inspired expression ergonomics, its learning curve splits distinctly between Day 1 familiarity and Day 14 fluency:

DimensionScoreWhy
First-hour familiarity5.5 / 10Unlearning f(x), n-1, "strings", and null takes deliberate attention for the first few hours.
Steady-state readability9.0 / 10Near-zero syntactic noise; explicit mut at call sites; /or eliminates both hidden exceptions and 4-line error boilerplate; linear \ dataflow.
Steady-state writability8.5 / 10Very low ceremony, gradual types (prototype dynamically, lock down --strict-types for production), and homoiconic blocks/templates. Slight tax from fixed-arity memorization and explicit mut.
  • vs. Go (Readability: Veko >= Go | Writability: Veko > Go): Go and Veko both reject hidden magic. Veko pulls ahead on signal-to-noise ratio by replacing vertical if err != nil { return nil, err } repetition with inline /or [ ... ] and \ pipelines, while Go leads on Day-1 C-syntax familiarity and third-party IDE ecosystem size.
  • vs. Rust (Readability: Veko >> Rust | Writability: Veko >> Rust): Both enforce ownership, explicit mutation (&mut vs mut), and zero-GC safety. Veko delivers single-owner determinism, shared-nothing spawn/chan, and .secret taint safety without <'a, T: Send + Sync + 'static>, Arc<Mutex<...>>, or turbofish ::<> noise — trading away only complex multi-lifetime borrow graphs.
  • vs. Zig (Readability: Veko > Zig | Writability: Veko > Zig): Zig's catch |err| and orelse are close cousins to Veko's /or, and both prize defer and explicitness. Veko is faster to write and scan for networking, CLI, codec, web, and backend work (built-in strings/maps, backtick templates, pipes, gradual typing), while Zig stays lower-level for raw OS kernels or custom allocators.
  • vs. Elixir / Clojure / Rebol (Readability: Veko >= Elixir, > Clojure/Rebol | Writability: Tie): Captures Elixir's |> (\ in Veko) and Lisp's quote/compose homoiconicity without outer parenthesis walls — and solves classic Rebol's dynamic-arity scaling hazard via lexical scoping, explicit use/pub modules, mut borrow checking, and --strict-types.
  • vs. Python / TypeScript (Readability: Tie | Writability: Day-1 Python/TS > Veko; Maintenance Veko > Python/TS): Python and TypeScript feel effortless on Day 1 because everyone already knows their syntax, whereas over time hidden exceptions, None/undefined landmines, shared-reference mutation, and async/await coloring erode clarity. Veko reads like clean pseudocode while encoding mutation, errors, secrets, and capabilities directly on the page.

Chapter 2: Workspaces, CLI Subcommands, Config & Secrets

CAPABILITY GOVERNANCE

Defense-in-Depth Capability Gates, .secret Firewall & Supply-Chain Trust

Compile-time allow-caps enforcement, cryptographic taint tracking, zero-trust Wasm sandboxes, and signed VKP1 packages.

COMPILE-TIME POLICY & SUPPLY CHAIN veko.vk + types.vk + pkg/vkp.vk RUNTIME SANDBOXES & SINK FIREWALLS oro_vm.vk + vvm + native PAL Static audit .secret blocked Verified deps Cap mask Sink checks Manifest Policyveko.vk allow-caps.fs .clocks .env .net .exec .ui FFI IsolationDefault-Deny .ffi Gate--allow-ffi / VEKO_ALLOW_FFI=1 Supply ChainSigned VKP1 BundlesMerkle SHA-256 + Ed25519/ML-DSA Taint FirewallCompile + Runtime .secretZero Leakage Across Sinks Runtime IsolationVM & Wasm HostSandbox--allow-* + fuel + SSRF block
Component & ModuleArchitectural Role
veko.vk allow-caps
types.vk + main.vk
Declares the exact OS capabilities permitted inside the workspace module graph.
Default-Deny .ffi Gate
lib/ffi.vk + types.vk
Keeps foreign C-ABI shared libraries disabled by default and banned in Wasm.
Signed VKP1 Bundles
lib/pkg/vkp.vk
Verifies cryptographic package signatures against pinned trust-keys before compilation.
Compile + Runtime .secret
types.vk + runtime.vk
Blocks secret-tagged values from leaving process memory in cleartext.
VM & Wasm HostSandbox
oro_vm.vk + runtime_pal*.vk
Enforces defense-in-depth host policies at runtime for scripts and plugins.

Recipe 2.1: Zero-Flag Workspaces & Automatic Capability Tightening (veko init & veko mod sync)

Scaffold a workspace with a veko.vk manifest and let the compiler audit and lock down the exact minimal OS capability bitmask ([.fs .clocks .env .net]):

POWERSHELL
# Scaffold a web, CLI, GUI, or library workspace
veko init sync-agent --cli
cd sync-agent

# Run, type-check, test, and compile directly from veko.vk
veko .
veko check --strict-types src/main.vk
veko test
veko compile --native src/main.vk -o dist/sync-agent.exe

# Scan all transitive imports and tighten allow-caps in veko.vk to the exact minimum
veko mod sync

For quick one-off scripts outside a workspace, grant capabilities explicitly on the CLI:

POWERSHELL
veko -C fs,net tools/ping_health.vk
veko run -e 'println `SHA-256 ready: {1 << 8}`'

Recipe 2.2: Declarative Subcommand & Flag CLI (lib/cli.vk)

Build structured multi-subcommand CLIs with typed flags, defaults, and automatic --help rendering:

VEKO
use [cli]

build-cli = fn [] cli/App [
    mut app = cli/new-app 'deploy-ctl' '1.0.0' 'Pure-Veko release rollout utility'
    mut ship = cli/new-cmd 'ship' 'Roll out a signed release bundle'
    cli/add-flag mut ship (cli/FlagSpec { name = 'env',     short = 'e', kind = .string,  default_val = 'staging', help = 'Target environment' })
    cli/add-flag mut ship (cli/FlagSpec { name = 'workers', short = 'w', kind = .int,     default_val = 4,         help = 'Parallel rollout workers' })
    cli/add-flag mut ship (cli/FlagSpec { name = 'dry-run', short = 'n', kind = .boolean, default_val = false,     help = 'Validate without mutating' })
    cli/add-cmd mut app ship
    app
]

main = fn [] any [
    app = build-cli
    parsed = cli/parse/or app os/args [e ->
        println (cli/help-text app)
        return e
    ]
    if parsed.cmd == 'ship' [
        env_name = cli/get-str parsed 'env' 'staging'
        n_work   = cli/get-int parsed 'workers' 4
        dry      = cli/get-bool parsed 'dry-run' false
        println `Rolling out to {env_name} with {n_work} workers (dry_run={dry})`
    ]
    .ok
]

Recipe 2.3: Layered TOML + Environment Configuration with .secret Hygiene

Load human-friendly codec/toml configuration files while keeping API tokens and signing keys quarantined inside Veko's .secret type firewall (zeroized deterministically when scope exits):

VEKO
use [toml = codec/toml]

pub ServiceConfig = struct {
    host       str        = '127.0.0.1'
    port       i64        = 8080
    api_secret secret str = ''
}

pub load-config = fn [path str] ServiceConfig [
    raw = os/read-file/or path [ '' ]
    doc = if raw != '' [ toml/decode/or raw [ {} ] ] else [ {} ]

    host = str/append '' (map/get/or doc 'host' [ os/getenv/or 'APP_HOST' [ '127.0.0.1' ] ])
    port = as-i64 (map/get/or doc 'port' [ str/to-i64/or (os/getenv/or 'APP_PORT' [ '8080' ]) [ 8080 ] ])

    // Secret environment variable is tainted as `secret` and wiped on scope exit
    tok = os/getenv/secret/or 'APP_API_SECRET' [ secret '' ]
    println `Loaded config on {host}:{port} (token={tok})`  // prints token=<secret>

    ServiceConfig {
        host       = host
        port       = port
        api_secret = tok
    }
]

Chapter 3: Zero-nil Error Recovery, Refinements & ORO Memory

MEMORY MODEL

ORO Single-Owner Memory: Borrow, Move, mut Loan & Copy-on-Write

Rust-grade deterministic cleanup and zero garbage collector pauses without lifetime annotations.

ZERO-COPY FAST PATH (RC == 1) 99% of calls & mutations SHARED SPLIT & SCOPE EXIT Cycle-free DAG + zeroize 16B header rc == 1 bind / return mut when rc > 1 scope exit old rc-- Allocation1. Create ValueSSO <=14B or Unique Slab Fast Call2. Read-Only CallZero-Cost Borrow In-Place Mutation3. Explicit mut Loanmut param + mut call site Move / Share4. Binding & ReturnOwnership Transfer Copy-on-Write5. Lazy CoW Splitensure_unique on rc > 1 Cleanup6. Deterministic DropFree-List + .secret Wipe
Component & ModuleArchitectural Role
1. Create Value
runtime.vk + native_rt.vk
Allocates scalars and <=14B strings/bytes inline in 16B Value; larger data gets rc=1 slab.
2. Read-Only Call
vko_emit.vk + native_emit.vk
Normal function parameters borrow the 16-byte Value header with zero refcount traffic.
3. Explicit mut Loan
types.vk + native_emit.vk
Mutates uniquely owned buffers, blocks, maps, and struct fields directly in place.
4. Binding & Return
oro_vm.vk + native_rt.vk
Rebinding or returning transfers ownership cleanly; aliasing increments non-atomic rc.
5. Lazy CoW Split
runtime.vk + native_rt.vk
Clones the backing slab only at the exact moment a shared container is mutated.
6. Deterministic Drop
runtime.vk + native_rt.vk
Reclaims dead slabs immediately at lexical scope exit or /or unwind.

Recipe 3.1: User-Declarable Slash Refinements & Contextual /or [e -> ...]

Any function can declare optional /refinement modifiers with defaults, and callers can combine refinements in left-to-right order plus attach /or error recovery:

VEKO
dial-upstream = fn [host str /port p i64 = 443 /tls secure bool = true] str [
    if host.trim == '' [ return (err 'upstream host cannot be empty') ]
    scheme = if secure [ 'https' ] else [ 'http' ]
    `{scheme}://{host.trim}:{p}`
]

// Base arity uses defaults (p = 443, secure = true)
prod_url = dial-upstream 'veko-lang.org'

// Extend arity cleanly at the call site via /port/tls
dev_url = dial-upstream/port/tls '127.0.0.1' 8080 false

// Recover inline and inspect the caught error `e`
safe_url = dial-upstream/or '' [e ->
    println `Falling back to loopback ({mold e})`
    'http://127.0.0.1:8080'
]

Recipe 3.2: Deterministic LIFO defer Cleanup on Return and /or Unwind

Pair every file handle, socket, or temporary directory with defer [ ... ] on the line immediately below acquisition so cleanup runs in LIFO order on both normal return and early error returns:

VEKO
use [fs]

write-verified-report = fn [dst_path str, lines block[str]] any [
    tmp_dir = str/join [(os/temp-dir) '/report_stage_' (mold (time/unix))] ''
    _ = fs/mkdir-all tmp_dir
    defer [ _ = fs/remove-all tmp_dir ]

    stage_file = `{tmp_dir}/draft.txt`
    payload = bytes/from-str (str/join lines '\n')
    _ = fs/write-atomic/or stage_file payload [e ->
        return (err `staging write failed: {mold e}`)
    ]
    fs/copy-file stage_file dst_path
]

Recipe 3.3: In-Place Byte Slab Building & Disjoint Field Loans (mut)

Pre-allocate binary packet buffers once with bytes/with-cap and pass explicit mut loans (including disjoint struct field loans like mut state.tx_buf) for zero-copy framing:

VEKO
PacketState = struct {
    stream_id i64
    tx_buf    bytes
}

append-tlv-frame = fn [mut buf bytes, tag i64, body bytes] [
    _ = bytes/push mut buf (tag & 0xff)
    _ = bytes/push-u16-be mut buf (len body)
    _ = bytes/push-all mut buf body
    .ok
]

build-hello-packet = fn [] bytes [
    mut st = PacketState {
        stream_id = 1
        tx_buf    = (bytes/with-cap 128)
    }
    append-tlv-frame mut st.tx_buf 0x01 (bytes/from-str 'VEKO-1.0')
    append-tlv-frame mut st.tx_buf 0x02 (bytes/from-str 'veko-lang.org')
    st.tx_buf
]

Chapter 4: Files, Streams, Archives, Compression & Regex

79-MODULE STDLIB & PQC

Pure-Veko Standard Library & Post-Quantum Cryptography Architecture

1,043 exported structs and functions across 79 modules — from core data structures to NIST FIPS 203/204/205 PQC.

CORE DATA, CLI, CODECS & ARCHIVES Zero OS capabilities required CLASSICAL & POST-QUANTUM CRYPTOGRAPHY lib/crypto/* + lib/auth/* buf / bits Wire frames SHA3 / SHAKE AES-GCM / EdDSA ML-KEM / ML-DSA TLS / Vault / JWT FoundationsCore, Text, Math & CLIfmt, cli, coll, seq, regex, utf8 SerializationCodecs, Wire & Archivescbor, csv, toml, der, deflate, zip Systems LayerStreams, Reactor, DB & UIio, reactor, web, db/*, durable, ui Classical CryptoAEAD, Hashes & CurvesAES-GCM, ChaCha20, SHA-2/3, X25519 Post-QuantumNIST FIPS 203 / 204 / 205ML-KEM, ML-DSA & SLH-DSA Envelope & Authcrypto/seal & Auth TokensSealed Envelopes + JWT/OAuth2/TOTP
Component & ModuleArchitectural Role
Core, Text, Math & CLI
lib/fmt.vk + lib/cli.vk + lib/coll.vk
Provides formatting, subcommand CLI parsing, sets/rings/heaps/LRU, regex NFA, and UTF-8.
Codecs, Wire & Archives
lib/codec/* + lib/archive/*
Encodes and decodes binary and text wire formats plus compressed TAR/ZIP archives.
Streams, Reactor, DB & UI
lib/reactor.vk + lib/web.vk + lib/durable.vk
Builds high-level networking, persistence, workflows, and UIs over the capability PAL.
AEAD, Hashes & Curves
lib/crypto/aes.vk + lib/crypto/x25519.vk
Constant-time symmetric AEADs, cryptographic Sponge/Merkle hashes, KDFs, and elliptic curves.
NIST FIPS 203 / 204 / 205
lib/crypto/mlkem.vk + lib/crypto/mldsa.vk
Quantum-resistant lattice KEMs, lattice signatures, and stateless hash signatures.
crypto/seal & Auth Tokens
lib/crypto/seal.vk + lib/auth/jwt.vk
Combines sealed AEAD envelopes with EdDSA/ML-DSA65 JWTs, OAuth2 PKCE, and RFC 6238 TOTP.

Recipe 4.1: Polymorphic io/Stream Pipelines (Memory, Files & TLS Sockets)

Write protocol parsers and serializers against io/Stream so unit tests feed io/mem-stream in memory with zero capabilities while production code passes TCP or TLS 1.3 streams:

VEKO
use [io]

write-netstring = fn [mut s io/Stream, msg str] i64 [
    raw = bytes/from-str msg
    frame = bytes/from-str `{(len raw)}:{msg},`
    io/write-all mut s frame
]

// Test purely in memory with zero .fs or .net capabilities
mut mem = io/mem-stream (bytes/with-cap 0)
_ = write-netstring mut mem 'homoiconic'
wire_text = bytes/to-str (io/read-all mut mem)  // '10:homoiconic,'

Recipe 4.2: Linear-Time ReDoS-Proof Regex Capture Groups (lib/text/re.vk)

Veko's text/re compiles patterns to a Thompson NFA with guaranteed O(n * m) execution time — immune to catastrophic backtracking on untrusted user input:

VEKO
use [re = text/re]

sem_rx = re/compile '([a-z0-9_]+)@([0-9]+\\.[0-9]+\\.[0-9]+)'
m = re/match sem_rx 'http_router@1.2.0'
if m.matched [
    pkg_name = m.groups[1]   // 'http_router'
    pkg_ver  = m.groups[2]   // '1.2.0'
    println `Resolved package {pkg_name} version {pkg_ver}`
]

Recipe 4.3: Zstandard Compression & Deterministic TAR/ZIP Archives

Compress payloads with RFC 8878 Zstandard (compress/zstd) and bundle multi-file release archives in memory with archive/zip or archive/tar:

VEKO
use [zstd = compress/zstd, zip = archive/zip]

pack-diagnostic-bundle = fn [readme_txt str, log_json str] bytes [
    compressed_log = zstd/compress (bytes/from-str log_json)
    zip/pack [
        zip/ZipEntry { path = 'README.txt',    data = (bytes/from-str readme_txt), compress = true }
        zip/ZipEntry { path = 'events.json.zst', data = compressed_log,            compress = false }
    ]
]

Chapter 5: HTTP/1.1, HTTP/2, QUIC HTTP/3 & Homoiconic Web Apps

NETWORKING, WEB & DATABASES

Unified io/Stream Stack, Hybrid PQC TLS 1.3, Web Router & Zero-FFI Databases

End-to-end network services, HTML5 rendering, and wire-native database drivers running across all three runtimes.

TRANSPORT & SECURITY LAYER io/* + net/dns + net/tls13 HTTP, WEB & REAL-TIME LAYER web + html + net/websocket + http2 PERSISTENCE & PACKAGING db/kv + db/postgres + db/redis + vkp Encrypted stream HTTP/1.1 HTTPS / WSS State & sessions SQL & cache Polymorphic I/Oio/Stream Capability Recordio/fs + io/net + io/open Secure TransportDNS & Hybrid PQC TLS 1.3RFC 8446 + X25519MLKEM768 Web Tierweb Router & HTML5 DSLMiddleware + auto-escaped html ProtocolsHTTP Client, HTTP/2 & WSnet/client + http2 + websocket Embedded StoreEmbedded db/kv EngineCRC-32 WAL + put-sealed External DBsPostgres v3, Redis & SidecarSCRAM-SHA-256 + RESP2/3
Component & ModuleArchitectural Role
io/Stream Capability Record
lib/io.vk + lib/io/net.vk
Record-of-closures interface unifying TCP sockets, files, and in-memory test buffers.
DNS & Hybrid PQC TLS 1.3
lib/net/dns.vk + lib/net/tls13.vk
Resolves DNS records over UDP/TCP and negotiates TLS 1.3 with X.509 chain verification.
web Router & HTML5 DSL
lib/web.vk + lib/html.vk
Routes parameterized paths (:id, *splat) through composable middleware and typed HTML5 nodes.
HTTP Client, HTTP/2 & WS
lib/net/client.vk + lib/net/websocket.vk
Provides redirect-following HTTP/1.1 batching, HTTP/2 HPACK framing, and RFC 6455 WebSockets.
Embedded db/kv Engine
lib/db/kv.vk
Crash-safe append-only log-structured key-value database with positioned pread/pwrite.
Postgres v3, Redis & Sidecar
lib/db/postgres.vk + lib/db/redis.vk
Speaks PostgreSQL v3 extended query wire protocol and Redis RESP directly over io/Stream.

Recipe 5.1: Concurrent Non-Blocking HTTP Batch Fetching, HEAD Probes & Keep-Alive Pools (lib/net/client.vk)

Fetch multiple endpoints concurrently on a single readiness reactor thread via nc/get-many (with built-in public CA root verification across Ed25519, ECDSA P-256/P-384, and RSA), issue zero-body nc/head checks, or reuse persistent sockets via nc/new-pool:

VEKO
use [nc = net/client]

probe-cluster = fn [urls block[str]] block[i64] [
    opts = nc/RequestOpts { timeout = 5s, pqc = true }
    responses = nc/get-many urls opts
    responses \ map fn [r] [
        if err? r [ 0 ] else [ r.status ]
    ]
]

check-release-size = fn [url str] str [
    r = nc/head url (nc/RequestOpts { timeout = 5s })
    map/get/or r.headers 'content-length' [ '0' ]
]

Recipe 5.2: XSS-Safe Homoiconic HTML5 Views & Web Router (lib/html.vk + lib/web.vk)

Author HTML5 components as native Veko [.tag { attrs } [ children ]] blocks where text nodes are automatically HTML-escaped against XSS, and GET routes automatically answer RFC-compliant HEAD requests:

VEKO
use [web, html]

status-card = fn [service_name str, proto str] block [
    [.article { class = 'card' } [
        [.h2 {} [`Service: {service_name}`]]
        [.p {} [`Active wire protocol: {proto}`]]
    ]]
]

pub make-app = fn [] web/App [
    mut app = web/new-app
    web/use-security-headers mut app

    web/get mut app '/status/:service' fn [req web/Request] web/Response [
        svc   = web/param req 'service' 'veko-site'
        proto = web/header req 'X-Veko-Proto' 'h1'
        web/view 200 (status-card svc proto)
    ]

    web/get mut app '/api/v1/ping' fn [req web/Request] web/Response [
        web/json-resp 200 { ok = true, proto = (web/header req 'X-Veko-Proto' 'h1') }
    ]
    app
]

Recipe 5.3: Multi-Worker Native TLS 1.3 + HTTP/2 (h2) + WAN QUIC HTTP/3 (h3)

Run one web/App across multi-core shared-nothing TCP :443 workers (https-accept-loop + https-worker-loop with mtime certificate hot-reload, 5s handshake deadlines, and HTTP/2 Rapid Reset guards), UDP :443 WAN QUIC v1 HTTP/3 (ReassemblyBuf + PTO retransmission), and TCP :80 (Let's Encrypt ACME HTTP-01 + 301 redirect) with zero reverse proxy:

VEKO
use [web, inet = io/net, tls = net/tls13]

serve-production = fn [cert_pem str, key_pem str, acme_dir str] any [
    _ = tls/ensure-dev-p256-identity cert_pem key_pem 'veko-lang.org'
    mut rel = tls/new-cert-reloader cert_pem key_pem

    // 1. Spawn port :80 ACME HTTP-01 + 301 HTTPS redirect reactor
    _ = spawn [
        r_ln = inet/listen-nonblock '0.0.0.0:80'
        _ = web/serve-reactor r_ln (web/make-acme-redirect-app acme_dir 'veko-lang.org' 443) (web/AsyncServerOpts { max_requests = 0 })
        .ok
    ]

    // 2. Spawn UDP :443 WAN QUIC v1 HTTP/3 listener
    usock = net/udp-bind '0.0.0.0' 443
    _ = spawn [
        mut h3_rel = tls/new-cert-reloader cert_pem key_pem
        _ = web/serve-h3 usock (fn [] any [ tls/get-identity mut h3_rel ]) (make-app) 0
        .ok
    ]

    // 3. Dispatch TCP :443 TLS 1.3 (h2 + http/1.1) across 4 shared-nothing workers
    work_ch = chan/new 128
    opts = web/HttpsServerOpts {
        max_requests      = 0
        handshake_timeout = 5s
        alt_svc           = 'h3=":443"; ma=86400'
    }
    mut w = 0
    while w < 4 [
        _ = spawn [
            _ = web/https-worker-loop work_ch (make-app) opts
            .ok
        ]
        w = w + 1
    ]
    ln = net/listen-tcp .ip '0.0.0.0:443'
    web/https-accept-loop ln mut rel work_ch 0
]

Recipe 5.4: Constant-Memory File, 206 Range & Chunked Response Streaming

Serve multi-hundred-megabyte SDK archives, video slices, or generated io/Stream feeds without buffering payloads in RAM (serve-static-range automatically switches to 64 KiB positioned os/pread streaming across HTTP/1.1 and flow-controlled HTTP/2 DATA frames for files and byte ranges > 256 KiB):

VEKO
use [io, web]

register-download-routes = fn [mut app web/App] [
    web/get mut app '/downloads/:archive' fn [req web/Request] web/Response [
        name  = web/param req 'archive' ''
        range = web/header req 'Range' ''
        web/serve-static-range 'downloads' name range
    ]

    web/get mut app '/events/export.ndjson' fn [req web/Request] web/Response [
        payload = bytes/from-str '{"seq":1,"ok":true}\n{"seq":2,"ok":true}\n'
        st = io/from-bytes payload
        // Pass -1 content_len (or use web/chunked-response) for HTTP/1.1 chunked / H2 DATA streaming
        web/stream-response 200 'application/x-ndjson' st (len payload)
    ]
]

Chapter 6: Zero-FFI SQLite 3, TLS PostgreSQL & RESP3 Redis

Recipe 6.1: Crash-Safe Schemas, B-Tree Indexes & Homoiconic JOIN Queries (lib/db/sqlite.vk)

Veko's db/sqlite reads and writes genuine 4096-byte "SQLite format 3\0" B-tree files—complete with a CRC-32-verified 'VKJRNL01' rollback journal, incremental dirty-page os/pwrite commits, multi-page 0x02/0x0a B-tree indexes, and relational INNER/LEFT JOIN—in 100% pure Veko with zero libsqlite3 dependencies:

VEKO
use [sq = db/sqlite]

Packages = sq/define-table 'packages' (quote [
    id        i64 .pk
    name      str .unique
    owner_id  i64 .index
    downloads i64 = 0
])

Authors = sq/define-table 'authors' (quote [
    id     i64 .pk
    handle str .unique
])

run-registry-store = fn [db_path str] block [
    mut db = sq/open db_path
    _ = sq/migrate mut db Authors
    _ = sq/migrate mut db Packages

    aid = sq/insert mut db Authors { handle = 'ada' }
    _ = sq/insert mut db Packages {
        name      = 'http_router'
        owner_id  = aid
        downloads = 42
    }
    _ = sq/save mut db

    // Homoiconic LEFT JOIN with qualified projections & indexed ordering
    sq/q db (quote [
        select [p.name a.handle p.downloads]
        from packages p
        left-join authors a on [p.owner_id == a.id]
        where [p.downloads >= 10]
        order-by [p.downloads .desc]
        limit 10
    ])
]

Recipe 6.2: Parameterized SQL Queries & Atomic Online Backups

Combine homoiconic sq/q queries with parameterized SQL (? placeholders) and zero-downtime atomic file snapshots via fs/write-atomic:

VEKO
use [fs, sq = db/sqlite]

increment-downloads = fn [db_path str, pkg_name str] enum [
    mut db = sq/open db_path
    _ = sq/exec mut db 'UPDATE packages SET downloads = downloads + 1 WHERE name = ?' [pkg_name]
    sq/save mut db
]

backup-sqlite-online = fn [db_path str, backup_path str] i64 [
    db = sq/open db_path
    snapshot = sq/to-bytes db
    fs/write-atomic backup_path snapshot
]

Recipe 6.3: Crash-Safe Append-Only KV & Secondary Indexes (lib/db/kv.vk + lib/db/query.vk)

For ultra-fast embedded state, pair db/kv with db/query secondary indexes:

VEKO
use [kv = db/kv, q = db/query]

mut store = kv/open-fast 'sessions.vkkv'
sessions  = q/define-table 'sessions' 'id' ['role']
_ = q/put-row mut store sessions { id = 'sess_01', user = 'ada', role = 'superadmin' }
admins = q/where-eq store sessions 'role' 'superadmin'
_ = kv/close mut store

Recipe 6.4: Pooled TLS PostgreSQL $1 Prepared Queries & RESP3 Redis Transactions (lib/db/postgres.vk + lib/db/redis.vk)

Scale stateless backend workers over bounded, health-checked PgPool (TLS 1.3 SSLRequest + SCRAM-SHA-256 + Extended Query $1, $2 binary parameters) and RedisPool (RESP3 HELLO 3 + MULTI/EXEC transactions):

VEKO
use [pg = db/postgres, rd = db/redis]

fetch-active-tenants = fn [pg_pool pg/PgPool, rd_pool rd/RedisPool, region str] any [
    rows = pg/with-conn pg_pool fn [mut conn pg/PgConn] any [
        pg/with-tx mut conn fn [mut tx pg/PgConn] any [
            pg/query-params mut tx
                'SELECT id, slug FROM tenants WHERE region = $1 AND active = $2'
                [region true]
        ]
    ]

    _ = rd/with-conn rd_pool fn [mut rconn rd/RedisConn] any [
        rd/with-tx mut rconn fn [mut q block] any [
            rd/tx-queue mut q ['INCR' `metrics:queries:{region}`]
            rd/tx-queue mut q ['SET' `cache:count:{region}` (mold (len rows))]
            .ok
        ]
    ]
    rows
]

Chapter 7: Shared-Nothing Concurrency, Reactor & Durable Sagas

DURABLE STATE & WORKFLOWS

Crash-Safe Durable Objects & Replay-Safe Workflows over db/kv

Single-writer transactional actors, memoized step checkpoints, external signals, and LIFO saga compensations.

LIB/DURABLE/OBJECT.VK Transactional Keyed Actors LIB/DURABLE/WORKFLOW.VK Deterministic Checkpoint Replay LIB/DB/KV.VK STORAGE LAYER CRC-32 Append-Only WAL do:<ns>:<id> alarm / inbox keys wf:<run>:step evt / comp keys step-done? + mutate Stateful ActorDurable Object Turnopen-object + atomic mutate Actor Timers & MailAlarms & FIFO Inboxset-alarm + enqueue / drain Replay EngineMemoized Workflow Stepsstart + step + step-with-retry Coordination & RollbackSignals, Timers & LIFO Sagaswait-event + run-compensations Durable StorageCRC-32 Log-Structured KVpwrite + fsync + compact
Component & ModuleArchitectural Role
Durable Object Turn
lib/durable/object.vk
Encapsulates strongly consistent per-entity state keyed by namespace and object ID.
Alarms & FIFO Inbox
lib/durable/object.vk
Persists scheduled wakeups and ordered actor messages inside the same WAL store.
Memoized Workflow Steps
lib/durable/workflow.vk
Executes multi-step business processes that resume from their exact last checkpoint after a crash.
Signals, Timers & LIFO Sagas
lib/durable/workflow.vk
Suspends workflows cleanly on external webhooks/timers and unwinds failures in reverse order.
CRC-32 Log-Structured KV
lib/db/kv.vk
Persists object fields, alarms, workflow steps, signals, and sagas in one crash-safe file.

Recipe 7.1: Shared-Nothing Worker Pool with Bounded Channels & Timeouts

Veko eliminates data races by construction: spawn blocks cannot capture outer mut bindings or .secret values, communicating exclusively over typed channels:

VEKO
parallel-checksums = fn [payloads block[bytes]] block[i64] [
    ch = chan/new (len payloads)
    mut tasks = []
    for [idx buf] payloads [
        b_copy = buf
        i_copy = idx
        push mut tasks (spawn [
            chan/send ch { idx = i_copy, size = (len b_copy) }
            .ok
        ])
    ]
    mut sizes = []
    mut received = 0
    while received < (len payloads) [
        msg = chan/recv/timeout/or ch 3s [ { idx = -1, size = 0 } ]
        push mut sizes msg.size
        received = received + 1
    ]
    for [_ t] tasks [ _ = task/await t ]
    sizes
]

Recipe 7.2: Crash-Safe Replayable Saga Workflows, Worker Leases & Dead-Letter Queues (lib/durable/workflow.vk)

Build multi-step payment, provisioning, or deployment workflows where completed steps replay from db/kv after a process crash, non-blocking RetryPolicy steps route exhausted runs to wf_dlq/*, and unrecoverable failures run LIFO saga compensations automatically:

VEKO
use [d = durable, wf = durable/workflow]

run-order-saga = fn [db_path str, order_id str] any [
    mut db  = d/open-store db_path
    defer [ _ = d/close-store mut db ]
    mut run = d/workflow mut db order_id 'fulfill-order' { order_id = order_id }

    policy = wf/RetryPolicy {
        max_attempts   = 3
        base_backoff   = 100ms
        max_backoff    = 2s
        backoff_factor = 2
        dead_letter    = true
    }

    // Step 1: Memoized inventory reservation + LIFO compensation registration
    rsv_id = wf/step-policy/or mut db mut run 'reserve-inventory' policy fn [attempt] [
        'rsv_901'
    ] [e ->
        return (err `reserve failed: {mold e}`)
    ]
    _ = wf/record-compensation mut db mut run 'release-inventory' rsv_id

    // Step 2: Ledger capture — unwinds registered compensations in LIFO order on failure
    rcpt = wf/step-policy/or mut db mut run 'capture-ledger' policy fn [attempt] [
        'rcpt_442'
    ] [e ->
        _ = wf/run-compensations mut db mut run fn [comp_name payload] [
            println `Compensated {comp_name}: {mold payload}`
            .ok
        ]
        return (err `ledger failed: {mold e}`)
    ]

    wf/complete mut db mut run { reservation = rsv_id, receipt = rcpt }
]

Chapter 8: Homoiconic Mini-DSLs, Studio Desktop UI, TUI & Wasm Plugins

TERMINAL, DESKTOP UI & FFI

Capability-Isolated Terminal UI, RGBA32 Canvas, .ui Window & Opt-In .ffi

Four clean layers keeping CLI binaries tiny while enabling rich TrueColor TUIs, 60 FPS 2D GUIs, and C/Rust interop.

ZERO-CAP PURE-VEKO RENDERING Works on VM, Wasm & Native CAPABILITY-GATED OS & FOREIGN BOUNDARIES .ui and opt-in .ffi mut cv present-canvas RGBA32 pixels Shared telemetry Terminal UIDouble-Buffered TUIlib/tui.vk (TrueColor ANSI) 2D RasterizerRGBA32 Software Canvaslib/ui/canvas.vk (Zero-Copy) Widget ToolkitImmediate-Mode Widgetslib/ui/widgets.vk OS Window (.ui).ui Window Surfacelib/ui.vk + --gui PE switch Foreign Interop (.ffi)Opt-In .ffi C-ABI Bridgelib/ffi.vk (Zero-W^X AOT)
Component & ModuleArchitectural Role
Double-Buffered TUI
lib/tui.vk
Renders flicker-free terminal dashboards by emitting ANSI escapes only for changed cells.
RGBA32 Software Canvas
lib/ui/canvas.vk
Draws alpha-blended shapes, gradients, lines, and crisp 5x7 ASCII glyphs into mut cv.pixels.
Immediate-Mode Widgets
lib/ui/widgets.vk
Composes responsive layouts, themes, hit-tested buttons, lists, and charts over Canvas.
.ui Window Surface
lib/ui.vk + native_pal5.vk
Blits RGBA32 canvases to native Win32 GDI windows or validated headless surfaces.
Opt-In .ffi C-ABI Bridge
lib/ffi.vk + native_pal5.vk
Loads C, C++, Rust, Zig, or Go shared libraries (.dll/.so/.dylib) via static trampolines.

Recipe 8.1: Building a Custom Homoiconic [ ... ] Policy Dialect (quote, compose & parse-block)

Because Veko code and data share the exact same token representation, you can design expressive domain-specific languages in ~20 lines without writing a lexer:

VEKO
eval-acl-rules = fn [rules block, req_role str, req_path str] enum [
    mut i = 0
    while (i + 3) <= (len rules) [
        action = rules[i]       // .allow or .deny
        role   = rules[i + 1]   // 'admin' or '*'
        prefix = rules[i + 2]   // '/admin'
        role_ok = role == '*' or role == req_role
        path_ok = (len req_path) >= (len prefix) and req_path[0..(len prefix)] == prefix
        if role_ok and path_ok [ return action ]
        i = i + 3
    ]
    .deny
]

policy = quote [
    .allow 'superadmin' '/admin'
    .allow '*'          '/stdlib'
    .deny  '*'          '/downloads'
]

decision = eval-acl-rules policy 'guest' '/stdlib/index.html'   // .allow

Recipe 8.2: Official veko-lang.org Ecosystem Packages & Signed VKP1 Bundles

Search, inspect, and install any of the 30 official Ed25519-signed libraries from https://veko-lang.org/packages (cloud_s3, data_formats, openapi, smtp_mail, webauthn, grpc_proto, cluster_raft, mq_streams, db_drivers, resilience, ai_mcp, ai_llm, vec_rag, dataframe_parquet, payments_ledger, graphql, browser_cdp, ldap_saml, oci_k8s, noise_tunnel, iac_fleet, wasm_plugin_sdk, crdt_sync, iot_mqtt, web_live, jobs_cron, doc_media, http_router, veko_ui_kit, sqlite_orm_ext) or pack your own VKP1 archive (lib/pkg/vkp.vk):

POWERSHELL
veko pkg search rag
veko pkg info vec_rag
veko pkg add vec_rag@1.0.0
veko pkg add payments_ledger@1.0.0
veko pkg add graphql@1.0.0
veko pkg verify-lock
VEKO
use [vkp = pkg/vkp, x25 = crypto/x25519, sha = crypto/sha256]

pack-signed-library = fn [] bytes [
    seed = sha/sha256 (bytes/from-str 'publisher-signing-seed-v1')
    pk   = x25/ed25519-pubkey seed
    raw  = vkp/pack-ed25519
        { name = 'veko_ui_kit', version = '1.0.0' }
        { 'mod.vk' = 'pub pill = fn [txt str] str [ `[ {txt} ]` ]' }
        seed
    _ = vkp/verify raw [(vkp/format-trust-key .ed25519 pk)]
    raw
]

Recipe 8.3: Light-Mode Studio UI with Tab Focus Ring, Code Editor & Command Palette (lib/ui/widgets.vk)

Render deterministic RGBA32 Studio surfaces (Win32, zero-libc Linux Wayland/X11, macOS arm64, Wasm <canvas>, or PNG snapshots) with Tab/Shift+Tab keyboard focus traversal, Veko syntax-highlighted code-editor (with 64-step undo/redo), and fuzzy command-palette:

VEKO
use [cv = ui/canvas, w = ui/widgets]

render-studio-frame = fn [mut c cv/Canvas, mut st w/UiState, mut ed w/EditorState, mut pal w/PaletteState] str [
    th = w/light-theme
    cv/clear mut c th.bg
    w/begin-frame mut st

    body = w/panel mut c (w/Rect { x = 16, y = 16, w = 768, h = 448 }) 'Studio Scratchpad' th
    w/code-editor mut c mut st 'main-editor' body mut ed th

    chosen = w/command-palette mut c mut st 'cmd-pal' mut pal [
        w/CommandItem { id = 'run',   label = 'Run Active Module', shortcut = 'Ctrl+Enter' }
        w/CommandItem { id = 'check', label = 'Strict Type Check', shortcut = 'Ctrl+Shift+B' }
    ] th
    w/end-frame mut st
    chosen
]

Recipe 8.4: Fuel-Bounded WebAssembly Sandboxes & Zero-Toolchain Cross-Compilation

Execute untrusted .vk tenant scripts inside vvm with deterministic instruction fuel, or cross-compile standalone native binaries from any host OS:

POWERSHELL
# Run an untrusted plugin in WebAssembly 3.0 with bounded fuel & slab leak verification
veko run --wasm --fuel=500000 --mem-pages=32 --check-slabs plugins/tenant_rule.vk

# Cross-compile standalone native binaries for Windows ARM64, Linux x86_64, Linux ARM64, or Apple Silicon
veko compile --native --target=win-arm64   src/main.vk -o dist/service-win-arm64.exe
veko compile --native --target=linux-x64   src/main.vk -o dist/service-linux-x64
veko compile --native --target=linux-arm64 src/main.vk -o dist/service-linux-arm64
veko compile --native --target=macos-arm64 src/main.vk -o dist/service-macos-arm64