API: stdlib

Generated from Geblang source declarations and docblocks.

async.atomic

Source: stdlib/async/atomic.gb

Class AtomicInt

class AtomicInt

Lock-free atomic int64 cell. Operations are sequentially consistent.

let counter = AtomicInt(0);
counter.add(1);
counter.compareAndSwap(1, 42);
io.println(counter.load());   # 42

Field _h

any _h

Method AtomicInt

func AtomicInt(int initial = 0)

Method load

func load(): int

Returns the current value.

Method store

func store(int value): void

Replaces the current value.

Method add

func add(int delta): int

Atomically adds delta and returns the new value. delta may be negative for subtraction.

Method compareAndSwap

func compareAndSwap(int old, int next): bool

Atomically sets the value to next if and only if the current value is old. Returns true on success.

Class AtomicBool

class AtomicBool

Lock-free atomic bool cell. Useful for one-shot flags (closed, cancelled, initialised).

Field _h

any _h

Method AtomicBool

func AtomicBool(bool initial = false)

Method load

func load(): bool

Method store

func store(bool value): void

Method compareAndSwap

func compareAndSwap(bool old, bool next): bool

async.channel

Source: stdlib/async/channel.gb

Class Channel

class Channel<T>

Typed message-passing channel. Send and recv block; with a positive buffer, sends are non-blocking until the buffer fills. close() halts further sends; subsequent recvs drain the buffer then return null.

import async;
import async.channel as ch;

let c = ch.Channel<int>(8);
async.run(func(): void {
for (let i = 0; i < 5; i++) { c.send(i); }
c.close();
});
for (v in c) {
io.println(v);
}

Field _h

any _h

Field _buffer

int _buffer

Method Channel

func Channel(int buffer = 0)

Method send

func send(T value): void

Sends value to the channel, blocking until a receiver is ready (unbuffered) or the buffer has space. Throws on send-after-close.

Method recv

func recv(): T

Receives the next value. Blocks until one is available. Returns null when the channel is closed and drained.

Method tryRecv

func tryRecv(): T

Non-blocking receive: returns the next value if one is immediately available, otherwise null. Pair with isClosed() to disambiguate "no value pending" from "closed and drained".

Method trySend

func trySend(T value): bool

Non-blocking send: returns true if the send completed immediately, false if it would have blocked. Throws on send-after-close.

Method close

func close(): void

Closes the channel. Subsequent sends throw; pending and subsequent recvs drain the buffer then return null. Double-close throws.

Method isClosed

func isClosed(): bool

True when the channel has been closed.

Method __iter

func __iter(): ChannelIterator<T>

Iterator protocol: for (x in channel) blocks on each recv and terminates when the channel is closed and drained. Returns a fresh per-consumer iterator so the shared channel is never mutated during iteration - concurrent producers can keep sending safely.

async.http

Source: stdlib/async/http.gb

Function get

func get(string url): Task<any>

Starts an asynchronous HTTP GET request and resolves to the native HTTP response value.

Function post

func post(string url, any body): Task<any>

Starts an asynchronous HTTP POST request with the given body.

Function postJson

func postJson(string url, any body): Task<any>

Starts an asynchronous JSON POST request, encoding the body as JSON.

Function request

func request(string method, string url, any body): Task<any>

Starts an asynchronous HTTP request for the supplied method, URL, and body.

Function requestWithOptions

func requestWithOptions(dict<string, any> options): Task<any>

Starts an asynchronous HTTP request using the native HTTP options dictionary.

Function parseJson

func parseJson(any response): Task<any>

Parses an HTTP response body as JSON asynchronously.

async.io

Source: stdlib/async/io.gb

Function readText

func readText(string path): Task<string>

Reads a text file asynchronously and resolves to its full contents.

Function writeText

func writeText(string path, string text): Task<any>

Writes text to a file asynchronously, replacing any existing contents.

Function appendText

func appendText(string path, string text): Task<any>

Appends text to a file asynchronously.

Function readBytes

func readBytes(string path): Task<bytes>

Reads a file as bytes asynchronously.

Function writeBytes

func writeBytes(string path, bytes data): Task<any>

Writes bytes to a file asynchronously, replacing any existing contents.

Function appendBytes

func appendBytes(string path, bytes data): Task<any>

Appends bytes to a file asynchronously.

Function read

func read(any handle, int size): Task<any>

Reads up to size units from an open handle asynchronously.

Function readAll

func readAll(any handle): Task<any>

Reads all remaining data from an open handle asynchronously.

Function write

func write(any handle, any value): Task<any>

Writes a value to an open handle asynchronously.

Function writeln

func writeln(any handle, any value): Task<any>

Writes a value and newline to an open handle asynchronously.

Function flush

func flush(any handle): Task<any>

Flushes an open handle asynchronously when the handle supports flushing.

Function close

func close(any handle): Task<any>

Closes an open handle asynchronously.

Function stat

func stat(string path): Task<any>

Reads filesystem metadata for a path asynchronously.

Function listDir

func listDir(string path): Task<any>

Lists directory entries asynchronously.

async.net

Source: stdlib/async/net.gb

Function lookupHost

func lookupHost(string host): Task<any>

Resolves a host name asynchronously.

Function listenTcp

func listenTcp(string address): Task<any>

Starts a TCP listener asynchronously.

Function connectTcp

func connectTcp(string address): Task<any>

Opens a TCP connection asynchronously.

Function accept

func accept(any listener): Task<any>

Accepts the next TCP connection from a listener asynchronously.

Function read

func read(any conn, int size): Task<any>

Reads from a network connection asynchronously.

Function write

func write(any conn, any data): Task<any>

Writes data to a network connection asynchronously.

Function close

func close(any handle): Task<any>

Closes a network listener or connection asynchronously.

Function listenUdp

func listenUdp(string address): Task<any>

Starts a UDP listener asynchronously.

Function dialUdp

func dialUdp(string address): Task<any>

Opens a UDP connection asynchronously.

Function readFrom

func readFrom(any conn, int size): Task<any>

Reads a UDP datagram and sender address asynchronously.

Function writeTo

func writeTo(any conn, any data, string address): Task<any>

Writes a UDP datagram to an address asynchronously.

async.rate

Source: stdlib/async/rate.gb

Function throttle

func throttle(func fn, int ms): func

Returns a wrapper that invokes fn at most once per ms milliseconds.

Subsequent calls within the window return the result of the most recent invocation without calling fn again. Useful for rate-limiting handlers that fire on every keystroke / scroll / message.

let log = async.rate.throttle(func(string m): void {
io.println(m);
}, 200);
log("a"); log("b"); log("c");  # only one io.println in 200ms

Function debounce

func debounce(func fn, int ms): func

Returns a wrapper that delays invocation until ms milliseconds have passed since the last call. Repeated calls within that window cancel prior pending invocations.

The wrapper returns a Task<any> that resolves to the value of fn once it eventually runs, or null if a later call superseded it. await it if you care about the result.

let save = async.rate.debounce(func(string text): void {
persist(text);
}, 300);
save("hello"); save("hello!"); save("hello world");
# persist("hello world") runs 300ms after the last call

async.scope

Source: stdlib/async/scope.gb

Class TaskGroup

class TaskGroup

Tracks a set of concurrently running tasks under a single scope. Use async.scope(body) instead of constructing this directly: scope wires up the await-all-on-exit and cancel-siblings-on-error semantics the structured-concurrency pattern expects.

Field tasks

list<any> tasks

Field cancelled

bool cancelled

Method TaskGroup

func TaskGroup()

Method spawn

func spawn(callable fn): any

Spawns a child task running the supplied no-arg callable. Returns the Task value so the caller can await it directly when a result is needed.

Method cancel

func cancel(): void

Marks the group cancelled and signals every child task. Workers that observe their cancellation token can exit early; workers that don't run to completion.

Function scope

func scope(callable body): any

Runs body inside a fresh TaskGroup, awaiting every child task before returning. If body throws or any child task throws, the remaining children are cancelled and the first error is rethrown once the wait completes.

Usage:

let results = async.scope(func(group): list { let a = group.spawn(func(): int { return fetchUser(1); }); let b = group.spawn(func(): int { return fetchUser(2); }); return [async.await(a), async.await(b)]; });

async.stream

Source: stdlib/async/stream.gb

Function jsonStream

func jsonStream(any source, any handler): Task<int>

Streams JSON values from a source through a handler asynchronously.

Function jsonReader

func jsonReader(any source): Task<any>

Creates a JSON streaming reader asynchronously.

Function yamlStream

func yamlStream(any source, any handler): Task<int>

Streams YAML values from a source through a handler asynchronously.

Function yamlReader

func yamlReader(any source): Task<any>

Creates a YAML streaming reader asynchronously.

Function xmlStream

func xmlStream(any source, any handler): Task<int>

Streams XML values from a source through a handler asynchronously.

Function xmlReader

func xmlReader(any source): Task<any>

Creates an XML streaming reader asynchronously.

Function csvStream

func csvStream(any source, any handler): Task<int>

Streams CSV rows from a source through a handler asynchronously.

Function csvReader

func csvReader(any source): Task<any>

Creates a CSV streaming reader asynchronously.

async.sync

Source: stdlib/async/sync.gb

Class Mutex

class Mutex

Mutual-exclusion lock. Blocks the current goroutine until the lock is acquired. Re-entrancy is NOT supported - a goroutine that calls lock() twice without an intervening unlock() deadlocks (matches Go's sync.Mutex).

let m = Mutex();
m.lock();
try {
# protected section
} finally {
m.unlock();
}

Field _h

any _h

Method Mutex

func Mutex()

Method lock

func lock(): void

Acquires the lock. Blocks if another holder is present.

Method unlock

func unlock(): void

Releases the lock. Calling unlock on an unlocked Mutex throws.

Method tryLock

func tryLock(): bool

Acquires the lock if available without blocking. Returns true on success, false if the lock is held elsewhere.

Class RWMutex

class RWMutex

Reader / writer lock. Many readers may hold the lock simultaneously; writers are exclusive. Acquiring a write lock blocks until all readers have released.

let rw = RWMutex();
rw.rLock();
try { # shared read
} finally { rw.rUnlock(); }

rw.lock();
try { # exclusive write
} finally { rw.unlock(); }

Field _h

any _h

Method RWMutex

func RWMutex()

Method lock

func lock(): void

Acquires the write lock. Blocks until all readers release.

Method unlock

func unlock(): void

Method tryLock

func tryLock(): bool

Method rLock

func rLock(): void

Acquires a shared read lock.

Method rUnlock

func rUnlock(): void

Method tryRLock

func tryRLock(): bool

Class Semaphore

class Semaphore

Counted semaphore. Semaphore(n) lets up to n holders acquire simultaneously; further acquirers block. Initial permit count must be at least 1.

Field _h

any _h

Method Semaphore

func Semaphore(int permits)

Method acquire

func acquire(): void

Blocks until a permit is available, then takes it.

Method release

func release(): void

Returns a permit. Throws if released more than acquired.

Method tryAcquire

func tryAcquire(): bool

Tries to take a permit without blocking. Returns true on success, false if none are currently available.

Class WaitGroup

class WaitGroup

Wait group: a counter you increment with add(n) for each task started, done() when a task finishes, and wait() blocks until the counter reaches zero.

let wg = WaitGroup();
for (let i = 0; i < 10; i++) {
wg.add(1);
async.run(func(): void {
try { # work
} finally { wg.done(); }
});
}
wg.wait();

Field _h

any _h

Method WaitGroup

func WaitGroup()

Method add

func add(int delta): void

Increments the counter by delta (typically before a task starts).

Method done

func done(): void

Decrements the counter by one (typically when a task finishes).

Method wait

func wait(): void

Blocks until the counter reaches zero.

async.tasks

Source: stdlib/async/tasks.gb

Function map

func map(list<any> items, callable fn, ?dict<string, any> opts = null): list<any>

Function forEach

func forEach(list<any> items, callable fn, ?dict<string, any> opts = null): void

Function retry

func retry(callable fn, ?dict<string, any> opts = null): any

Function settle

func settle(list<any> tasks): list<any>

Function any

func any(list<any> tasks): any

Function parallel

func parallel(any fns): any

cli.color

Source: stdlib/cli/color.gb

Function isEnabled

func isEnabled(): bool

Returns true when color output is currently enabled (NO_COLOR unset or empty).

Function bold

func bold(string s): string

Function dim

func dim(string s): string

Function italic

func italic(string s): string

Function underline

func underline(string s): string

Function black

func black(string s): string

Function red

func red(string s): string

Function green

func green(string s): string

Function yellow

func yellow(string s): string

Function blue

func blue(string s): string

Function magenta

func magenta(string s): string

Function cyan

func cyan(string s): string

Function white

func white(string s): string

Function bgBlack

func bgBlack(string s): string

Function bgRed

func bgRed(string s): string

Function bgGreen

func bgGreen(string s): string

Function bgYellow

func bgYellow(string s): string

Function bgBlue

func bgBlue(string s): string

Function bgMagenta

func bgMagenta(string s): string

Function bgCyan

func bgCyan(string s): string

Function bgWhite

func bgWhite(string s): string

cli.command

Source: stdlib/cli/command.gb

Class Option

class Option

Describes a typed command-line option and converts it to cli.parseArgs schema data.

Field name

string name

Field kind

string kind

Field shortName

string shortName

Field helpText

string helpText

Field requiredFlag

bool requiredFlag

Field hasDefaultValue

bool hasDefaultValue

Field defaultValue

any defaultValue

Method Option

func Option(string name, string kind)

Method short

func short(string name): Option

Method help

func help(string text): Option

Method required

func required(): Option

Method default

func default(any value): Option

Method toSchema

func toSchema(): dict<string, any>

Class Command

class Command

Describes a command with options, parsing, help text, and required-argument validation.

Field name

string name

Field description

string description

Field options

list<any> options

Method Command

func Command(string name, string description)

Method option

func option(Option option): Command

Method schema

func schema(): dict<string, any>

Method parse

func parse(list<string> argv): dict<string, any>

Method help

func help(): string

Method requireParsed

func requireParsed(list<string> argv): dict<string, any>

Function newOption

func newOption(string name, string kind): Option

Creates a command option builder for the given long name and type.

Function newCommand

func newCommand(string name, string description): Command

Creates a command builder with a name and human-readable description.

cli.widgets

Source: stdlib/cli/widgets.gb

Class Spinner

class Spinner

Spinner draws a rotating frame to stderr while a long-running task is in progress. Call .tick() periodically (the caller owns the cadence), then .stop(finalMessage?) to clear the line.

Field message

string message

Field _frame

int _frame

Method Spinner

func Spinner(string message)

Method tick

func tick(): void

Method update

func update(string message): void

Method stop

func stop(string finalMessage = ""): void

Class ProgressBar

class ProgressBar

ProgressBar renders [#####-----] 50% (5/10) label on stderr. Use .advance() for the common +1 case, .set() for explicit values, and .finish() to clear the line.

Field current

int current

Field total

int total

Field width

int width

Field label

string label

Method ProgressBar

func ProgressBar(int total, int width = 30, string label = "")

Method advance

func advance(int n = 1): void

Method set

func set(int value): void

Method updateLabel

func updateLabel(string label): void

Method finish

func finish(string finalMessage = ""): void

clib.curses

Source: stdlib/clib/curses.gb

Function init

func init(): void

Initialise the screen (initscr + cbreak + noecho + keypad).

Function end

func end(): void

End the curses session (endwin). Safe to call before init.

Function addStr

func addStr(string s): void

Write a string at the current cursor position.

Function mvAddStr

func mvAddStr(int y, int x, string s): void

Write a string at position (y, x).

Function move

func move(int y, int x): void

Move the cursor to (y, x).

Function clear

func clear(): void

Clear the screen.

Function refresh

func refresh(): void

Refresh the display.

Function getCh

func getCh(): int

Read a single keystroke (blocking). Returns the key code.

Function maxY

func maxY(): int

Number of rows in the terminal window.

Function maxX

func maxX(): int

Number of columns in the terminal window.

Function startColor

func startColor(): void

Enable colour support. Call before initPair.

Function initPair

func initPair(int id, int fg, int bg): void

Define colour pair id with foreground fg and background bg.

Function attrOn

func attrOn(int attrs): void

Enable the given attribute bits.

Function attrOff

func attrOff(int attrs): void

Disable the given attribute bits.

Function colorPair

func colorPair(int n): int

Returns the attribute value for colour pair n (COLOR_PAIR(n) = n * 256).

clib.loader

Source: stdlib/clib/loader.gb

Function load

func load(string name, list<string> candidates): ffi.Library

Open name's shared object, trying candidates in order and returning the first that opens. Cached per name. Throws a single actionable error naming the library when every candidate fails.

Function guard

func guard(): sync.Mutex

A fresh Mutex for a binding to serialise calls on a stateful, non-thread-safe native handle.

clib.magic

Source: stdlib/clib/magic.gb

Class Magic

class Magic

Detect file type or MIME from a path or buffer via libmagic.

int _cookie

Field _closed

bool _closed

Field _guard

any _guard

Method Magic

func Magic(int flags = 0)

Method detect

func detect(string path): string

Return a content description for the file at path.

Method detectBuffer

func detectBuffer(bytes data): string

Return a content description for the given bytes buffer.

Method close

func close(): void

Close the libmagic handle. Idempotent.

Function detect

func detect(string path): string

Return a content description for the file at path (NONE flags).

Function mime

func mime(string path): string

Return the MIME type for the file at path (MIME_TYPE flags).

clib.systemd

Source: stdlib/clib/systemd.gb

Function notify

func notify(string state): bool

Send a raw sd_notify state string (e.g. "READY=1", "STATUS=...", "WATCHDOG=1"). Returns true if delivered to the service manager, false if not running under systemd.

Function ready

func ready(): bool

Signal service readiness ("READY=1").

Function watchdog

func watchdog(): bool

Ping the systemd watchdog ("WATCHDOG=1").

Function status

func status(string text): bool

Set the service status line shown by systemctl status.

Function journal

func journal(string message, dict<string, string> fields = {...}): void

Send a structured journald entry. message becomes the MESSAGE field; each key/value in fields is sent as an additional "KEY=value" field (PRIORITY, UNIT, custom keys, ...).

clib.zstd

Source: stdlib/clib/zstd.gb

Function compress

func compress(bytes data, int level = 3): bytes

Compress data at level (1..22; default 3). Returns a zstd frame carrying its content size so decompress needs no size hint.

Function decompress

func decompress(bytes frame): bytes

Decompress a zstd frame produced by compress (one that carries its content size).

config

Source: stdlib/config.gb

Function clone

func clone(dict<string, any> data): dict<string, any>

Returns a shallow copy of a configuration dictionary.

Function merge

func merge(dict<string, any> base, dict<string, any> overrides): dict<string, any>

Recursively merges override values into a copy of base.

Function defaults

func defaults(dict<string, any> values, dict<string, any> defaultValues): dict<string, any>

Applies default values first, then overlays explicit values.

Function layer

func layer(list<any> layers): dict<string, any>

Merges a list of configuration dictionaries from first to last.

Function has

func has(dict<string, any> data, string path): bool

Returns true when a dotted configuration path exists.

Function get

func get(dict<string, any> data, string path): any

Returns a required dotted configuration value or throws ValueError.

Function getOr

func getOr(dict<string, any> data, string path, any fallback): any

Returns a dotted configuration value, or fallback when any path segment is missing.

Function require

func require(dict<string, any> data, string path): any

Alias for get when call sites want to make required configuration explicit.

Class Config

class Config

Immutable-style wrapper around configuration dictionaries with dotted-path lookup helpers.

Field data

dict<string, any> data

Method Config

func Config(dict<string, any> data)

Method has

func has(string path): bool

Method require

func require(string path): any

Method get

func get(string path): any

Method getOr

func getOr(string path, any fallback): any

Method toDict

func toDict(): dict<string, any>

Function parse

func parse(string format, string text): Config

Parses a serde-supported document into a Config object.

deque

Source: stdlib/deque.gb

Class Deque

class Deque<T>

Double-ended queue with amortised O(1) push / pop at both ends. Internally a ring buffer with capacity doubling: when the buffer fills, a new buffer twice the size is allocated and elements are copied in front-to-back order.

let d = Deque<int>();
d.pushBack(1);
d.pushBack(2);
d.pushFront(0);
io.println(d.popFront());   # 0
io.println(d.popBack());    # 2

Field _buf

list<any> _buf

Field _head

int _head

Field _size

int _size

Field _cap

int _cap

Field _iterPos

int _iterPos

Method Deque

func Deque()

Method pushFront

func pushFront(T value): void

Inserts at the front. Amortised O(1).

Method pushBack

func pushBack(T value): void

Inserts at the back. Amortised O(1).

Method popFront

func popFront(): T

Removes and returns the front element. Throws ValueError on an empty deque. O(1).

Method popBack

func popBack(): T

Removes and returns the back element. Throws ValueError on an empty deque. O(1).

Method peekFront

func peekFront(): T

Returns the front element without removing it. Throws ValueError on an empty deque. O(1).

Method peekBack

func peekBack(): T

Returns the back element without removing it. Throws ValueError on an empty deque. O(1).

Method get

func get(int i): T

Returns the element at logical position i (0 = front). Negative i counts from the back (-1 = last). Throws ValueError on an out-of-range index. O(1).

Method length

func length(): int

Number of elements currently in the deque.

Method isEmpty

func isEmpty(): bool

True when the deque holds no elements.

Method clear

func clear(): void

Discards every element. Resets the buffer slots so any references they held are released for GC. O(cap).

Method toList

func toList(): list<T>

Returns a list snapshot in front-to-back order. Useful for inspection and debugging. O(n).

Method __iter

func __iter(): Deque<T>

Iterator-protocol entry. Resets the internal cursor and returns this. Note: concurrent iteration of the same deque is not supported because the cursor is shared.

Method __done

func __done(): bool

Method __next

func __next(): T

Method _grow

func _grow(): void

ffi

Source: stdlib/ffi.gb

Class Library

class Library

Library is an opened shared object. Construct via ffi.dlopen. symbol(name, argTypes, retType) resolves a function and returns a Geblang callable bound to the native code; invoking the callable dispatches into C through libffi-style trampolines with no per-call IPC.

Capability gating runs at dlopen time. If the project's geblang.yaml does not list the requested path (or --allow-ffi was not supplied), dlopen throws a PermissionError that user code can catch.

Field handle

int handle

Field path

string path

Field _closed

bool _closed

Method Library

func Library(int handle, string path)

Method symbol

func symbol(string name, list<int> argTypes, int retType): callable

Resolve a symbol and return a callable bound to the signature.

Method close

func close(): void

Release the library handle. Idempotent.

Method isClosed

func isClosed(): bool

True once close() has run.

Function dlopen

func dlopen(string path): Library

Open a shared library at path and return a Library wrapping the dlopen handle. Path resolution matches the platform dlopen search rules: an absolute or relative path is loaded directly; a bare library name (e.g. libm.so.6) goes through the system loader's search path.

Throws PermissionError when the active capability policy does not include the requested path.

Function alloc

func alloc(int n): int

Allocate n bytes on the libc heap; returns the pointer as int. The caller must Free it.

Function free

func free(int ptr): void

Release memory previously allocated by alloc (NULL-safe).

Function readBytes

func readBytes(int ptr, int n): bytes

Copy n bytes starting at ptr into a fresh bytes value.

Function writeBytes

func writeBytes(int ptr, bytes data): void

Copy data into the C-side buffer at ptr.

Function readCString

func readCString(int ptr): string

Read a null-terminated C string at ptr into a Geblang string.

Function cString

func cString(string s): int

Allocate a null-terminated copy of s on the libc heap; returns the pointer. Caller must Free it.

Function errno

func errno(): int

Read the value of the C errno variable on the calling thread.

Class Struct

class Struct

Layout descriptor for a C struct. Construct via ffi.Struct([...]) passing field declarations in their C declaration order.

let Timeval = ffi.Struct([ ["tv_sec", ffi.INT64], ["tv_usec", ffi.INT64], ]); let ptr = ffi.alloc(Timeval.size); Timeval.set(ptr, "tv_sec", 1700000000); io.println(Timeval.get(ptr, "tv_sec")); ffi.free(ptr);

Fields use the standard C alignment rules (each field aligned to its size; struct size padded to max alignment). PTR, INT*, UINT*, FLOAT, DOUBLE are valid as fields. CSTRING / BYTES are not - model those as PTR and manage the pointed-at memory explicitly.

Field handle

int handle

Field size

int size

Method Struct

func Struct(int handle)

Method get

func get(int ptr, string name): any

Read field name from the struct pointed at by ptr.

Method set

func set(int ptr, string name, any value): void

Write field name of the struct pointed at by ptr.

Method alloc

func alloc(): int

Allocate size bytes for one struct instance; returns the pointer. Caller frees via ffi.free.

Function StructOf

func StructOf(list<list<any>> fields): Struct

Build a struct layout from a list of [name, type] pairs in C declaration order. Returns a Struct you can use to read and write fields on a pointer.

Function sizeOf

func sizeOf(int elemType): int

Byte size of the given element type code. Useful for sizing buffers when passing typed arrays to native calls.

Function writeArray

func writeArray(int ptr, int elemType, list<any> values): void

Pack a Geblang list into a C-side buffer at ptr. The buffer must be at least values.length() * sizeOf(elemType) bytes.

Function readArray

func readArray(int ptr, int elemType, int length): list<any>

Read length elements of elemType from the C-side buffer at ptr into a Geblang list.

Function bytesView

func bytesView(int ptr, int length): bytes

Zero-copy view of length bytes starting at ptr as a Geblang bytes value. The returned bytes ALIAS the C memory - no copy is performed. The caller MUST guarantee that the underlying memory outlives every use of the value; once the C side frees it, accessing the bytes is undefined behaviour.

For most code, prefer ffi.readBytes(ptr, n) which copies. Reach for bytesView only when the buffer is large enough that the copy cost matters (image frames, audio buffers, tensors).

Function callback

func callback(callable fn, list<int> argTypes, int retType): int

Build a C function pointer that dispatches into fn when C calls it. argTypes and retType declare the C-ABI signature.

let cmp = ffi.callback( func(int a, int b): int { return (a as int) - (b as int); }, [ffi.PTR, ffi.PTR], ffi.INT32 );

The returned int is the C function pointer; pass it through a symbol declared as ffi.PTR to native libraries that expect a callback (e.g. qsort's comparator).

Constraints:

  • Argument types: INT*, UINT*, PTR only. Floats, CSTRING, and BYTES are not supported in callback signatures - if a C callback receives a string or a struct, declare PTR and decode it inside the Geblang function using ffi.readCString, ffi.readBytes, or struct.get.
  • Return types: VOID, INT*, UINT*, PTR.
  • Callbacks live for the rest of the process; up to 2000 may be allocated per process. Don't create them inside hot loops.
  • The Geblang runtime must be reachable when C calls back. Multi-threaded libraries that invoke callbacks from arbitrary OS threads may fail; document the threading model per binding.

file

Source: stdlib/file.gb

Class File

class File

File is an object wrapper over an io file handle. Open one with file.open(path, mode), then call methods for positioning, reading, writing, flushing, and locking. It implements the context-manager protocol, so with (f = file.open(path, "r+")) { ... } closes the handle automatically on exit, and __iter so for (line in f) walks the file line by line. The raw io.* free functions remain available when a low-level handle is more convenient.

Field handle

int handle

Field _closed

bool _closed

Method File

func File(string path, string mode = "r")

Method read

func read(int n): string

Reads up to n bytes; empty string at EOF.

Method readBytes

func readBytes(int n): bytes

Reads up to n bytes as a bytes value.

Method readAll

func readAll(): string

Reads all remaining content as a string.

Method readLine

func readLine(): ?string

Reads one line (newline stripped); null at EOF.

Method readLines

func readLines(): list<string>

Reads all remaining lines.

Method lines

func lines(): generator<string>

Lazy generator yielding each line until EOF.

Method write

func write(string text): int

Writes text; returns bytes written.

Method writeln

func writeln(string text): int

Writes text followed by a newline; returns bytes written.

Method writeBytes

func writeBytes(bytes data): int

Writes bytes; returns bytes written.

Method seek

func seek(int offset, string whence = "start"): int

Repositions the handle; whence is "start", "current", or "end". Returns the new absolute offset.

Method tell

func tell(): int

Current byte offset.

Method truncate

func truncate(int size): void

Resizes the file to size bytes.

Method atEnd

func atEnd(): bool

Whether the handle is at end-of-file.

Method flush

func flush(): void

Flushes buffered data.

Method sync

func sync(): void

Flushes file data and metadata to storage.

Method lock

func lock(): void

Acquires an exclusive advisory lock, blocking if needed.

Method tryLock

func tryLock(): bool

Attempts an exclusive advisory lock without blocking.

Method unlock

func unlock(): void

Releases an advisory lock.

Method close

func close(): void

Closes the handle. Safe to call more than once.

Method isClosed

func isClosed(): bool

True after close() has been called.

Method __enter

func __enter(): File

Method __exit

func __exit(): void

Method __iter

func __iter(): any

Function open

func open(string path, string mode = "r"): File

Opens a file and returns a File object. mode accepts the same strings as io.open (r, w, a, r+, w+, a+, x, x+).

functools

Source: stdlib/functools.gb

Function pipe

func pipe(list<func> fns): func

Returns a function that applies fns left-to-right.

pipe([f, g, h])(x) is equivalent to h(g(f(x))).

Function compose

func compose(list<func> fns): func

Returns a function that applies fns right-to-left.

compose([f, g, h])(x) is equivalent to f(g(h(x))).

Function partial

func partial(func fn, any ... bound): func

Returns a function that calls fn with bound prepended to its arguments.

partial(add, 1)(2) is equivalent to add(1, 2). For holes in any position, use the native _ placeholder syntax instead.

Function memoize

func memoize(func fn, int max = 128): func

Returns an LRU-cached wrapper of fn.

Cache keys are derived from the JSON representation of the call arguments, so memoized functions must take JSON-serialisable arguments (primitives, lists and dicts of primitives). When the cache reaches max entries the least-recently-used entry is evicted.

http.server

Source: stdlib/http/server.gb

Function handle

func handle(dict<string, any> request): dict<string, any>

Function main

func main(list<string> args): int

image

Source: stdlib/image.gb

Class Image

class Image

Raster image handle: load, transform, and re-encode PNG / JPEG / GIF (and decode WebP). Each transform returns a NEW Image; the source stays valid. Call close() to release a handle, or let the process exit reclaim everything.

Field _handle

any _handle

Method Image

func Image(any handle)

Method width

func width(): int

Pixel width.

Method height

func height(): int

Pixel height.

Method resize

func resize(int w, int h): Image

A new Image scaled to w x h (high-quality resampling).

Method crop

func crop(int x, int y, int w, int h): Image

A new Image cropped to the rectangle at (x, y) of size w x h.

Method rotate

func rotate(int degrees): Image

A new Image rotated clockwise by a multiple of 90 degrees.

Method encode

func encode(string format): bytes

Encode to bytes in the given format ("png", "jpeg", "gif").

Method save

func save(string path, string format): void

Encode and write to path; the format is taken from format.

Method close

func close(): void

Release the native handle; using the Image afterwards throws.

Function loadBytes

func loadBytes(bytes data): Image

Decode an image from raw bytes (PNG / JPEG / GIF / WebP).

Function load

func load(string path): Image

Load and decode an image file at path.

Function blank

func blank(int w, int h): Image

A new blank (transparent) Image of w x h.

llm

Source: stdlib/llm.gb

Interface Client

interface Client

Provider-agnostic LLM client. One interface for chat completions, text embeddings, image analysis, and image generation across OpenAI, Anthropic, and AWS Bedrock.

Choose a provider through llm.client({"provider": "..."}); the rest of the calling code stays the same regardless of which backend is wired up.

let c = llm.client({"provider": "anthropic", "apiKey": key}); let resp = c.chat([ {"role": "user", "content": "Summarise this..."} ], {"model": "claude-opus-4-8", "maxTokens": 1024}); io.println(resp["content"]);

The model field is a free-form string; pass whatever name the provider exposes. Providers do not validate it locally, so the caller is responsible for picking a model the account has access to.

Method chat

func chat(list<dict<string, any>> messages, dict<string, any> opts): dict<string, any>

Run a chat completion against messages. Each message is a dict with role (one of "user", "assistant", "system") and content (string). Returns {content, model, stopReason, usage} where usage has inputTokens, outputTokens, totalTokens.

Method embed

func embed(string text, dict<string, any> opts): dict<string, any>

Embed a single text string into a dense vector. Returns {vector, model, usage} with usage containing inputTokens.

Method analyzeImage

func analyzeImage(bytes image, string prompt, dict<string, any> opts): dict<string, any>

Multimodal image analysis. image is the raw bytes of a PNG / JPEG / WebP; prompt is the user instruction. Returns the same shape as chat (content, model, usage).

Method generateImage

func generateImage(string prompt, dict<string, any> opts): dict<string, any>

Generate one or more images for prompt. Returns {images, model} where images is a list of {bytes, format} dicts (format is "png" / "jpeg").

Function client

func client(dict<string, any> opts): Client

Build a provider client from a backend-agnostic options dict. The dict's provider key picks the implementation; remaining keys are validated by the chosen backend.

Supported providers: "openai", "anthropic", "bedrock".

llm.anthropic

Source: stdlib/llm/anthropic.gb

Class AnthropicClient

class AnthropicClient

Anthropic Messages API client. Authenticates via the x-api-key header and pins the anthropic-version header to a known release.

The Anthropic direct API does not expose embeddings or image generation; those methods throw "not supported" so the abstraction can fail fast and let callers route around the limitation (e.g. embed via OpenAI, then chat via Anthropic).

Field apiKey

string apiKey

Field endpoint

string endpoint

Field apiVersion

string apiVersion

Method chat

func chat(list<dict<string, any>> messages, dict<string, any> opts): dict<string, any>

Method chatStream

func chatStream(list<dict<string, any>> messages, dict<string, any> opts, callable callback): dict<string, any>

Method embed

func embed(string text, dict<string, any> opts): dict<string, any>

Method embedBatch

func embedBatch(list<string> texts, dict<string, any> opts): dict<string, any>

Method analyzeImage

func analyzeImage(bytes image, string prompt, dict<string, any> opts): dict<string, any>

Method generateImage

func generateImage(string prompt, dict<string, any> opts): dict<string, any>

Method runMessages

func runMessages(list<dict<string, any>> messages, dict<string, any> opts): dict<string, any>

Method post

func post(string path, dict<string, any> payload): dict<string, any>

Method models

func models(): list<dict<string, any>>

Method get

func get(string path): dict<string, any>

Function connect

func connect(dict<string, any> opts): AnthropicClient

Build an AnthropicClient. Required: apiKey. Optional: endpoint (default https://api.anthropic.com), apiVersion (default 2023-06-01, the stable Messages API release).

llm.bedrock

Source: stdlib/llm/bedrock.gb

Class BedrockClient

class BedrockClient

AWS Bedrock Runtime client. Speaks the InvokeModel REST API at https://bedrock-runtime.<region>.amazonaws.com/model/<modelId>/ invoke and signs each request with AWS Signature V4.

Bedrock hosts many model families and each accepts its own request schema. This client emits the Anthropic Messages schema (anthropic_version + messages + max_tokens) for chat and image analysis, which covers every Claude model available through Bedrock. Other model families (Titan, Llama, Mistral, Stable Diffusion) are not handled by this v1; callers needing them can use the raw invoke() helper to POST a provider-specific payload to InvokeModel directly.

Field region

string region

Field accessKey

string accessKey

Field secretKey

string secretKey

Field endpoint

string endpoint

Field controlEndpoint

string controlEndpoint

Method chat

func chat(list<dict<string, any>> messages, dict<string, any> opts): dict<string, any>

Method chatStream

func chatStream(list<dict<string, any>> messages, dict<string, any> opts, callable callback): dict<string, any>

Method embed

func embed(string text, dict<string, any> opts): dict<string, any>

Method embedBatch

func embedBatch(list<string> texts, dict<string, any> opts): dict<string, any>

Method embedTitan

func embedTitan(string text, string model): dict<string, any>

Method embedCohere

func embedCohere(string text, string model, dict<string, any> opts): dict<string, any>

Method analyzeImage

func analyzeImage(bytes image, string prompt, dict<string, any> opts): dict<string, any>

Method generateImage

func generateImage(string prompt, dict<string, any> opts): dict<string, any>

Method generateImageTitan

func generateImageTitan(string prompt, string model, dict<string, any> opts): dict<string, any>

Method generateImageStability

func generateImageStability(string prompt, string model, dict<string, any> opts): dict<string, any>

Method runMessages

func runMessages(list<dict<string, any>> messages, dict<string, any> opts): dict<string, any>

Method invoke

func invoke(string model, dict<string, any> payload): dict<string, any>

Escape hatch: send any payload to InvokeModel directly. Returns the parsed response body. Useful when the caller needs a Bedrock model family this v1 doesn't fold into the common shape (Titan, Llama, Stable Diffusion, etc.).

Method request

func request(string method, string path, string body): dict<string, any>

Method models

func models(): list<dict<string, any>>

Method controlRequest

func controlRequest(string method, string path): dict<string, any>

Function connect

func connect(dict<string, any> opts): BedrockClient

Build a BedrockClient. Required: region, accessKey, secretKey. Optional: endpoint (default https://bedrock-runtime..amazonaws.com).

llm.openai

Source: stdlib/llm/openai.gb

Class OpenaiClient

class OpenaiClient

OpenAI Chat Completions / Embeddings / Image APIs. Authenticates via Authorization: Bearer <apiKey> on every request. Endpoint defaults to https://api.openai.com; override for Azure OpenAI or compatible local stacks via opts.endpoint.

Duck-types llm.Client; explicit implements is omitted to break a parser-level circular import with the facade module.

Field apiKey

string apiKey

Field endpoint

string endpoint

Field organization

?string organization

Method chat

func chat(list<dict<string, any>> messages, dict<string, any> opts): dict<string, any>

Method chatStream

func chatStream(list<dict<string, any>> messages, dict<string, any> opts, callable callback): dict<string, any>

Method embed

func embed(string text, dict<string, any> opts): dict<string, any>

Method embedBatch

func embedBatch(list<string> texts, dict<string, any> opts): dict<string, any>

Method analyzeImage

func analyzeImage(bytes image, string prompt, dict<string, any> opts): dict<string, any>

Method generateImage

func generateImage(string prompt, dict<string, any> opts): dict<string, any>

Method post

func post(string path, dict<string, any> payload): dict<string, any>

Method models

func models(): list<dict<string, any>>

Method get

func get(string path): dict<string, any>

Function connect

func connect(dict<string, any> opts): OpenaiClient

Build an OpenaiClient from a llm.client options dict. Required: apiKey. Optional: endpoint (default https://api.openai.com), organization.

lrucache

Source: stdlib/lrucache.gb

Class LruCache

class LruCache<K, V>

LRU (least-recently-used) cache with optional TTL. Doubly- linked-list + dict for O(1) get / put / evict. On eviction the least-recently-used entry is dropped; on a TTL hit-but- expired the entry is dropped lazily and the call counts as a miss.

import lrucache;

let c = lrucache.LruCache<string, int>(100);
c.put("a", 1);
c.put("b", 2);
io.println(c.get("a"));    # 1 - now most recent
io.println(c.length());    # 2

let withTtl = lrucache.LruCache<string, int>(100, 60);   # 60s expiry

get(k) returns null on a miss (or on a hit whose entry has expired). Pair with has(k) if you need to distinguish a stored-null value from an absent key (but note has does NOT bump LRU order).

Field _capacity

int _capacity

Field _ttlSeconds

int _ttlSeconds

Field _index

dict<K, any> _index

Field _head

any _head

Field _tail

any _tail

Field _size

int _size

Field _hits

int _hits

Field _misses

int _misses

Field _evictions

int _evictions

Field _expirations

int _expirations

Method LruCache

func LruCache(int capacity, int ttlSeconds = 0)

Method get

func get(K key): any

Returns the value for key, bumping it to most-recent. Returns null on a miss or on a hit whose TTL has lapsed.

Method put

func put(K key, V value): void

Stores value under key. If key is already present the entry is updated and bumped to most-recent. Otherwise a new entry is inserted at the head; if the cache is at capacity, the least-recently-used entry is evicted first.

Method delete

func delete(K key): bool

Removes the entry for key if present. Returns true when a removal happened, false when the key was absent.

Method has

func has(K key): bool

Reports whether key has a non-expired entry, without bumping it to most-recent. An expired entry is dropped lazily as a side effect.

Method length

func length(): int

Number of entries currently held.

Method capacity

func capacity(): int

Configured maximum entry count.

Method isEmpty

func isEmpty(): bool

True when the cache holds no entries.

Method clear

func clear(): void

Discards every entry without yielding them. Counters are preserved so stats() still reflects lifetime activity.

Method keys

func keys(): list<K>

Returns the keys in MRU-to-LRU order. Iteration does not affect access ordering. O(n).

Method values

func values(): list<V>

Returns the values in MRU-to-LRU order. Does not affect access ordering. O(n).

Method stats

func stats(): dict<string, int>

Returns counters {hits, misses, evictions, expirations} accumulated since construction (or the last clear was a no-op here, since stats survive clear).

Method _computeExpiry

func _computeExpiry(): any

Method _isExpired

func _isExpired(any entry): bool

Method _moveToHead

func _moveToHead(any entry): void

Method _addToHead

func _addToHead(any entry): void
func _unlink(any entry): void

Method _removeEntry

func _removeEntry(any entry): void

Method _evict

func _evict(): void

mailer

Source: stdlib/mailer.gb

Class Attachment

class Attachment

File or in-memory attachment for an email message.

Field filename

string filename

Field content

any content

Field path

string path

Field contentType

string contentType

Field inline

bool inline

Field contentId

string contentId

Method Attachment

func Attachment(string filename, any content)

Method withContentType

func withContentType(string value): Attachment

Method asInline

func asInline(string cid): Attachment

Method toDict

func toDict(): dict<string, any>

Function attachmentFromPath

func attachmentFromPath(string path, string contentType): Attachment

Creates an attachment from a file path. The file is read when the message is sent or rendered.

Class Message

class Message

Email message with text, HTML, headers, and attachments.

Field from

string from

Field to

list<string> to

Field cc

list<string> cc

Field bcc

list<string> bcc

Field replyTo

string replyTo

Field subject

string subject

Field text

string text

Field html

string html

Field headers

dict<string, any> headers

Field attachments

list<Attachment> attachments

Method Message

func Message(string subject)

Method fromAddress

func fromAddress(string value): Message

Method toAddress

func toAddress(string value): Message

Method ccAddress

func ccAddress(string value): Message

Method bccAddress

func bccAddress(string value): Message

Method withReplyTo

func withReplyTo(string value): Message

Method withText

func withText(string value): Message

Method withHtml

func withHtml(string value): Message

Method withHeader

func withHeader(string name, string value): Message

Method attach

func attach(Attachment attachment): Message

Method toDict

func toDict(): dict<string, any>

Method render

func render(): string

Class SmtpTransport

class SmtpTransport

SMTP transport configuration.

Field config

dict<string, any> config

Method SmtpTransport

func SmtpTransport(string host, int port, string username, string password)

Method fromAddress

func fromAddress(string value): SmtpTransport

Method withStartTLS

func withStartTLS(bool enabled): SmtpTransport

Method withTLS

func withTLS(bool enabled): SmtpTransport

Method withHello

func withHello(string value): SmtpTransport

Method allowInsecureTLS

func allowInsecureTLS(bool enabled): SmtpTransport

Method toDict

func toDict(): dict<string, any>

Class Mailer

class Mailer

Mailer sends messages through a configured SMTP transport.

Field transport

SmtpTransport transport

Method Mailer

func Mailer(SmtpTransport transport)

Method send

func send(Message message): dict<string, any>

Method render

func render(Message message): string

Function smtpTransport

func smtpTransport(string host, int port, string username, string password): SmtpTransport

Convenience constructor for SMTP transports.

Function smtpMailer

func smtpMailer(string host, int port, string username, string password): Mailer

Convenience constructor for a Mailer using SMTP.

maps

Source: stdlib/maps.gb

Interface DictInterface

interface DictInterface

A dict-like contract for user classes. Implement the two abstract methods - __index(key) for obj[key] reads and keys() for the key set - and inherit contains, get, values, length, isEmpty, and __contains (so key in obj works) as defaults.

For a mutable map, also define __setIndex(key, value) on the class (it is intentionally not part of the interface, so read-only maps can omit it); the engine routes obj[key] = value to it.

import maps;

class Headers implements maps.DictInterface {
dict<string, string> store;
func Headers() { this.store = {}; }
func __index(any key): any { return this.store.get(key as string); }
func __setIndex(any key, any value): void { this.store.set(key as string, value as string); }
func keys(): list<any> { return this.store.keys(); }
}

let h = Headers();
h["Accept"] = "application/json";
io.println(h["Accept"]);            # application/json
io.println("Accept" in h);          # true
io.println(h.contains("Accept"));   # true
io.println(h.length());             # 1

Method __index

func __index(any key): any

Method keys

func keys(): list<any>

messaging

Source: stdlib/messaging.gb

Interface MessageQueue

interface MessageQueue

Common shape every backend implements. Concrete backends (SQS, RabbitMQ, ActiveMQ, Kafka) sit behind this interface so application code can swap brokers without changing its publish / receive call sites.

Messages flowing through this surface are dicts with at least: body the payload (string or bytes depending on the broker) id a broker-specific identifier needed for ack / delete

receive(timeoutMs) blocks up to the timeout. Returns null when no message arrived inside the window. consume(handler) loops: each delivered message is passed to handler which should return normally to ack or throw to nack (where the backend supports it).

Method publish

func publish(any payload): void

Method receive

func receive(int timeoutMs): ?dict<string, any>

Method ack

func ack(any messageId): void

Method consume

func consume(callable handler): void

Method close

func close(): void

Interface MessageTopic

interface MessageTopic

Pub/sub topic. Multiple subscribers each see every published message - in contrast to MessageQueue where each message is delivered to exactly one consumer. The backend chosen by the driver option determines how the fan-out is implemented (RabbitMQ fanout exchange, Kafka unique consumer groups, STOMP topic destinations).

subscribe(handler) runs the handler for each delivered message and blocks until the caller closes the topic.

Method publish

func publish(any payload): void

Method subscribe

func subscribe(callable handler): void

Method close

func close(): void

Function connect

func connect(dict<string, any> opts): MessageQueue

Build a queue handle from a backend-agnostic options dict. The dict's driver key picks the implementation; remaining keys are backend-specific and validated by the chosen backend.

let q = messaging.connect({ "driver": "sqs", "region": "us-east-1", "queueUrl": "https://sqs.us-east-1.amazonaws.com/123/orders", "accessKey": env.get("AWS_ACCESS_KEY_ID"), "secretKey": env.get("AWS_SECRET_ACCESS_KEY") }); q.publish({"orderId": 42});

Function topic

func topic(dict<string, any> opts): MessageTopic

Build a topic handle from a backend-agnostic options dict. Topics broadcast each published message to every active subscriber. The dict's driver key picks the backend; the same connection-shape options as connect() apply.

let topic = messaging.topic({ "driver": "rabbitmq", "url": "amqp://localhost/", "topic": "events.user.signup" }); topic.publish({"userId": 42}); topic.subscribe(func(any msg): void { ... });

SQS does not provide pub/sub directly - use the AWS SNS API for fan-out; SQS subscriptions can receive messages from SNS topics but pub/sub publishing is an SNS concern.

messaging.kafka

Source: stdlib/messaging/kafka.gb

Class KafkaQueue

class KafkaQueue

Kafka backend speaking the native Kafka protocol via the underlying segmentio/kafka-go library. Each KafkaQueue owns one writer (producer) and one reader (consumer group member); they stay open for the queue handle's lifetime.

Duck-types messaging.MessageQueue. The "queue" abstraction maps onto a single Kafka topic with a stable consumer-group id; publishing produces records and receiving fetches the next record assigned to this group member.

Field writer

int writer

Field reader

int reader

Field topic

string topic

Field _closed

bool _closed

Method publish

func publish(any payload): void

Method receive

func receive(int timeoutMs): ?dict<string, any>

Method ack

func ack(any messageId): void

Method consume

func consume(callable handler): void

Method close

func close(): void

Function connect

func connect(dict<string, any> opts): KafkaQueue

Build a KafkaQueue from a messaging.connect options dict.

Required: brokers list bootstrap broker host:port pairs topic string Kafka topic name groupId string consumer group id (the consumer side)

Optional: autoCreateTopic bool default false

Class KafkaTopic

class KafkaTopic

Kafka pub/sub topic. Each subscribe() call opens its own consumer group so every subscriber receives every published record - Kafka's native topic semantics already deliver to all groups, the difference vs the queue API is just that each subscriber gets a fresh group id rather than sharing one.

Field writer

int writer

Field topic

string topic

Field brokers

list<string> brokers

Field subSeq

int subSeq

Field _closed

bool _closed

Method publish

func publish(any payload): void

Method subscribe

func subscribe(callable handler): void

Method close

func close(): void

Function topic

func topic(dict<string, any> opts): KafkaTopic

messaging.rabbitmq

Source: stdlib/messaging/rabbitmq.gb

Class RabbitQueue

class RabbitQueue

RabbitMQ backend speaking AMQP 0.9.1. Each RabbitQueue owns one connection and one channel for the queue's lifetime, declares the queue durably on construction, and routes publish / receive / ack through the channel.

Duck-types messaging.MessageQueue. The explicit implements clause is omitted to avoid a circular module import.

Field conn

int conn

Field ch

int ch

Field queue

string queue

Field exchange

string exchange

Field routingKey

string routingKey

Field _closed

bool _closed

Method publish

func publish(any payload): void

Method receive

func receive(int timeoutMs): ?dict<string, any>

Method ack

func ack(any messageId): void

Method consume

func consume(callable handler): void

Method close

func close(): void

Function connect

func connect(dict<string, any> opts): RabbitQueue

Build a RabbitQueue from a messaging.connect options dict.

Required: url amqp://user:pass@host:port/vhost queue queue name

Optional: exchange default "" (direct-to-queue) routingKey default = queue name durable queue declared durable (default true)

Class RabbitTopic

class RabbitTopic

RabbitMQ pub/sub topic. Backed by a fanout exchange so every subscribed queue gets a copy of each published message. Each subscribe() call declares a fresh server-named queue bound to the exchange; the queue lives only while the subscription is active.

Field conn

int conn

Field ch

int ch

Field exchange

string exchange

Field _closed

bool _closed

Method publish

func publish(any payload): void

Method subscribe

func subscribe(callable handler): void

Method close

func close(): void

Function topic

func topic(dict<string, any> opts): RabbitTopic

Build a RabbitTopic over a fanout exchange named after opts.topic.

Required: url (amqp://...), topic (used as the exchange name). Optional: durable (default true for the exchange).

messaging.sns

Source: stdlib/messaging/sns.gb

Class SnsTopic

class SnsTopic

AWS SNS topic backend. publish() POSTs to the SNS Publish action with sigv4. subscribe() requires a paired SQS queue (set via opts.queueUrl on connect) and polls it; the SNS subscription itself is set up out of band, normally as a one-time aws sns subscribe ... --protocol sqs --endpoint <queue-arn> call.

Duck-types messaging.MessageTopic; explicit implements is omitted to break a circular import (the facade imports this module to dispatch by driver).

Field region

string region

Field topicArn

string topicArn

Field accessKey

string accessKey

Field secretKey

string secretKey

Field subQueue

?sqs.SqsQueue subQueue

Method publish

func publish(any payload): void

Method subscribe

func subscribe(callable handler): void

Method close

func close(): void

Method request

func request(string method, string params): dict<string, any>

Function connect

func connect(dict<string, any> opts): SnsTopic

Build an SnsTopic from a messaging.topic options dict.

Required: region, topicArn, accessKey, secretKey. Optional: queueUrl (an SQS queue subscribed to the topic out of band; subscribe() polls it).

messaging.sqs

Source: stdlib/messaging/sqs.gb

Class SqsQueue

class SqsQueue

AWS SQS backend for the messaging interface. Speaks the SQS REST API (query-string-form Action calls) signed with AWS Signature V4. No long-lived connection: each call is an independent HTTPS request to the queue URL.

Duck-types messaging.MessageQueue; the explicit implements clause is omitted to break a parser-level circular import (the facade module imports this one to dispatch by driver).

Field queueUrl

string queueUrl

Field region

string region

Field accessKey

string accessKey

Field secretKey

string secretKey

Method publish

func publish(any payload): void

Method receive

func receive(int timeoutMs): ?dict<string, any>

Method ack

func ack(any messageId): void

Method consume

func consume(callable handler): void

Method close

func close(): void

Method request

func request(string method, string params): dict<string, any>

Function connect

func connect(dict<string, any> opts): SqsQueue

Build an SqsQueue from a messaging.connect options dict. Required keys: region, queueUrl, accessKey, secretKey.

messaging.stomp

Source: stdlib/messaging/stomp.gb

Class StompQueue

class StompQueue

STOMP 1.2 backend for messaging.MessageQueue. Speaks the text-based STOMP protocol over a single TCP connection, which covers ActiveMQ natively and RabbitMQ when the STOMP plugin is enabled. Duck-types messaging.MessageQueue.

One subscription per StompQueue: receive() and consume() pull from MESSAGE frames delivered against the subscription id this queue installed at connect().

Field sock

sockets.Socket sock

Field destination

string destination

Field subId

string subId

Field nextReceipt

int nextReceipt

Field _closed

bool _closed

Method publish

func publish(any payload): void

Method receive

func receive(int timeoutMs): ?dict<string, any>

Method ack

func ack(any messageId): void

Method consume

func consume(callable handler): void

Method close

func close(): void

Function connect

func connect(dict<string, any> opts): StompQueue

Build a StompQueue from a messaging.connect options dict.

Required: host, port, destination (e.g. "/queue/orders"). Optional: login, passcode, virtualHost (default "/"), ackMode (default "client-individual").

Class StompTopic

class StompTopic

STOMP pub/sub topic. Routes to the same connection / frame code as StompQueue; only the destination changes (broker-side topic semantics are determined by the destination namespace, e.g. ActiveMQ uses /topic/...). publish / subscribe / close map onto SEND / MESSAGE-loop / DISCONNECT.

Field inner

StompQueue inner

Method publish

func publish(any payload): void

Method subscribe

func subscribe(callable handler): void

Method close

func close(): void

Function topic

func topic(dict<string, any> opts): StompTopic

Build a StompTopic. Same opts as connect() but the destination is rewritten to the broker's topic namespace when not already in one. ActiveMQ uses /topic/...; pass an explicit destination that starts with /topic/ for other STOMP brokers.

option

Source: stdlib/option.gb

Class Option

class Option<T>

A value that is either present (some = true) or absent (some = false).

Field some

bool some

Field value

?T value

Method Option

func Option(bool some, ?T value)

Method isSome

func isSome(): bool

Returns true when a value is present.

Method isNone

func isNone(): bool

Returns true when no value is present.

Method unwrap

func unwrap(): T

Returns the wrapped value, or throws if absent.

Method unwrapOr

func unwrapOr(T fallback): T

Returns the wrapped value, or fallback if absent.

Method orNull

func orNull(): ?T

Returns the value or null.

Function some

func some<T>(T value): Option<T>

Returns an Option containing value.

Function none

func none<T>(): Option<T>

Returns an empty Option.

Function ofNullable

func ofNullable<T>(?T value): Option<T>

Returns some(value) when value is not null, otherwise none().

pathlib

Source: stdlib/pathlib.gb

Class Path

class Path

Immutable-style path value with method chaining over native path functions.

Field raw

string raw

Method Path

func Path(string raw)

Method base

func base(): string

Returns the last element of the path.

Method dir

func dir(): Path

Returns all but the last element as a Path.

Method ext

func ext(): string

Returns the file name extension including the dot.

Method stem

func stem(): string

Returns the base name without extension.

Method withExt

func withExt(string newExt): Path

Returns the path with the extension replaced by newExt.

Method join

func join(string ... parts): Path

Joins additional segments to this path and returns a new Path.

Method abs

func abs(): Path

Returns the absolute version of this path.

Method parent

func parent(): Path

Returns the parent directory as a Path.

Method toString

func toString(): string

Returns the path as a plain string.

Method exists

func exists(): bool

Returns true when the path exists on the filesystem.

Method isDir

func isDir(): bool

Returns true when the path is an existing directory.

Method isFile

func isFile(): bool

Returns true when the path is an existing regular file.

Method glob

func glob(string pattern): list<Path>

Returns glob matches relative to this path as a list of Path values.

Function of

func of(string raw): Path

Creates a Path from a string.

Function join

func join(string ... parts): Path

Joins path segments into a Path.

priorityq

Source: stdlib/priorityq.gb

Class PriorityQueue

class PriorityQueue<T>

A binary min-heap-backed priority queue. Smallest-by-order element is always at the head; pop() and peek() return it.

Without a comparator, elements are ordered by Geblang's < operator (works for int, float, decimal, string). Pass a comparator func(T, T): int (returns < 0 / 0 / > 0) for custom types or reverse order.

let q = PriorityQueue<int>();
q.push(3);
q.push(1);
q.push(2);
io.println(q.pop());     # 1

let byPriority = PriorityQueue<Job>(func(Job a, Job b): int {
return a.priority - b.priority;
});

Field _heap

list<T> _heap

Field _size

int _size

Field compare

any compare

Method PriorityQueue

func PriorityQueue(any compare = null)

Method push

func push(T value): void

Inserts value and re-heapifies. O(log n).

Method pop

func pop(): T

Removes and returns the smallest-by-order element. Throws ValueError on an empty queue. O(log n).

Method peek

func peek(): T

Returns the smallest-by-order element without removing it. Throws ValueError on an empty queue. O(1).

Method length

func length(): int

Number of elements currently in the queue.

Method isEmpty

func isEmpty(): bool

True when the queue holds no elements.

Method pushPop

func pushPop(T value): T

Single-pass push-then-pop. Cheaper than calling push then pop separately when the inserted value would immediately become the new head. O(log n).

Method drain

func drain(): list<T>

Pops every element in priority order and returns them as a sorted list, leaving the queue empty.

Method clear

func clear(): void

Discards all elements without yielding them. O(1).

Method _cmp

func _cmp(T a, T b): int

Method _siftUp

func _siftUp(int idx): void

Method _siftDown

func _siftDown(int idx): void

Method _swap

func _swap(int i, int j): void

proc

Source: stdlib/proc.gb

Class Process

class Process

Process represents a running child process started by proc.spawn. stdin, stdout, and stderr are stream wrappers around the process's pipes (or the pty master in pty mode). In pty mode stderr is null because the pty merges output streams.

Use process.wait() to block until the child exits and read the exit code; process.kill() or process.signal("SIGTERM") terminate it.

Field handle

int handle

Field pid

int pid

Field stdin

streams.IOStream stdin

Field stdout

streams.IOStream stdout

Field stderr

any stderr

Method Process

func Process(int handle, int pid, streams.IOStream stdin, streams.IOStream stdout, any stderr)

Method wait

func wait(): int

Blocks until the process exits and returns its exit code.

Method kill

func kill(): void

Sends SIGKILL to the process.

Method signal

func signal(string name): void

Sends a named signal (e.g. "SIGTERM", "SIGHUP") to the process.

Function spawn

func spawn(string command, list<string> args = [], dict<string, any> opts = {...}): Process

Spawns a child process and returns a Process immediately. Args is a list of positional arguments; opts may include {pty: true} to attach a pseudo-terminal (stdin and stdout share the master fd; stderr is null), {cwd: "..."} to set the working directory, and {env: {...}} to replace the environment.

let p = proc.spawn("echo", ["hello"]);
io.println(p.stdout.readAll());
p.wait();

profiler

Source: stdlib/profiler.gb

Class Timer

class Timer

Field _start

int _start

Field _elapsedNs

int _elapsedNs

Method Timer

func Timer()

Method __enter

func __enter(): Timer

Method __exit

func __exit(): void

Method elapsedNs

func elapsedNs(): int

Method elapsedMs

func elapsedMs(): float

Function timer

func timer(): Timer

Class Profile

class Profile

Field _snap

any _snap

Field _delta

dict<string, any> _delta

Method Profile

func Profile()

Method __enter

func __enter(): Profile

Method __exit

func __exit(): void

Method elapsedMs

func elapsedMs(): float

Method cpuMs

func cpuMs(): float

Method heapBytes

func heapBytes(): int

Method allocs

func allocs(): int

Method gcCount

func gcCount(): int

Method report

func report(): dict<string, any>

Function profile

func profile(): Profile

rag

Source: stdlib/rag.gb

Interface Embedder

interface Embedder

Retrieval-augmented generation helpers built on the vectorstore module and the existing llm.embed. Chunk a document, embed and index its chunks, then retrieve the most relevant chunks for a query and assemble them into a prompt-ready context block.

import db; import llm; import rag; import vectorstore;

let store = vectorstore.MemoryVectorStore();
let embedder = rag.LlmEmbedder(llm.client({"provider": "openai", "apiKey": key}),
{"model": "text-embedding-3-small"});
rag.index(store, embedder, "handbook", longText, {"source": "handbook"}, {});
let hits = rag.retrieve(store, embedder, "how do I reset my password?", 4);
let prompt = "Answer using only this context:\n" + rag.context(hits, {});

Turns text into an embedding vector. Decouples rag from any single provider.

Method embed

func embed(string text): list<any>

Class LlmEmbedder

class LlmEmbedder implements Embedder

Embedder backed by an llm client; opts carries the embedding model.

Field _client

any _client

Field _opts

dict<string, any> _opts

Method LlmEmbedder

func LlmEmbedder(any client, dict<string, any> opts = {...})

Method embed

func embed(string text): list<any>

Class LocalEmbedder

class LocalEmbedder implements Embedder

Embedder backed by a local ONNX sentence-transformer model directory (model.onnx + tokenizer.json). Fully offline; requires --allow-onnx. opts pass through to onnx.session (libPath, intraOpThreads) and transformers.pool (pooling, normalize).

Field _session

any _session

Field _tokenizerJson

string _tokenizerJson

Field _opts

dict<string, any> _opts

Method LocalEmbedder

func LocalEmbedder(string modelDir, dict<string, any> opts = {...})

Method embed

func embed(string text): list<any>

Method close

func close(): void

Function chunk

func chunk(string text, dict<string, any> opts): list<string>

Splits text into overlapping chunks for embedding. opts: by: "words" (default) | "chars" | "paragraphs" size: window size (words=200, chars=1000, paragraphs=1000 char budget) overlap: overlap between windows (words=40, chars=200; ignored for paragraphs)

Function index

func index(vs.VectorStore store, Embedder embedder, string docId, string text, dict<string, any> metadata, dict<string, any> opts): int

Chunks text, embeds each chunk, and stores it under id "#". The caller's metadata is attached to every chunk along with the chunk text, docId, and chunk index. Returns the number of chunks indexed.

Function retrieve

func retrieve(vs.VectorStore store, Embedder embedder, string query, int k): list<vs.SearchHit>

Embeds the query and returns the k most similar stored chunks.

Function context

func context(list<vs.SearchHit> hits, dict<string, any> opts): string

Assembles retrieved chunks into a prompt-ready block. opts: withSources: true (default) prefixes each chunk with "[n] (docId): " separator: between chunks (default blank line)

redis

Source: stdlib/redis.gb

Class Client

class Client

Minimal Redis client for strings, lists, sets, hashes, counters, expiry, and raw commands.

Field conn

any conn

Method Client

func Client(string address)

Method command

func command(list<string> parts): any

Method ping

func ping(): bool

Method auth

func auth(string password): bool

Method select

func select(int database): bool

Method get

func get(string key): any

Method set

func set(string key, string value): bool

Method del

func del(string key): int

Method exists

func exists(string key): bool

Method expire

func expire(string key, int seconds): bool

Method incr

func incr(string key): int

Method ttl

func ttl(string key): int

Method lpush

func lpush(string key, string value): int

Method rpush

func rpush(string key, string value): int

Method lpop

func lpop(string key): any

Method rpop

func rpop(string key): any

Method lrange

func lrange(string key, int start, int stop): list<any>

Method sadd

func sadd(string key, string member): int

Method srem

func srem(string key, string member): int

Method sismember

func sismember(string key, string member): bool

Method smembers

func smembers(string key): list<any>

Method hset

func hset(string key, string field, string value): int

Method hget

func hget(string key, string field): any

Method hdel

func hdel(string key, string field): int

Method hgetAll

func hgetAll(string key): dict<string, any>

Method setex

func setex(string key, int seconds, string value): bool

Method eval

func eval(string script, list<string> keys, list<string> args): any

Method close

func close(): void

Function connect

func connect(string address): Client

Connects to a Redis server address and returns a Client.

result

Source: stdlib/result.gb

Class Result

class Result<T, E>

A value that is either a success (ok = true, value set) or a failure (ok = false, error set).

Field ok

bool ok

Field value

?T value

Field error

?E error

Method Result

func Result(bool ok, ?T value, ?E error)

Method isOk

func isOk(): bool

Returns true when this result represents success.

Method isErr

func isErr(): bool

Returns true when this result represents failure.

Method unwrap

func unwrap(): T

Returns the success value, or throws if this is an error.

Method unwrapOr

func unwrapOr(T fallback): T

Returns the success value, or fallback if this is an error.

Method unwrapErr

func unwrapErr(): E

Returns the error value, or throws if this is a success.

Function ok

func ok<T, E>(T value): Result<T, E>

Returns a success Result wrapping value.

Function err

func err<T, E>(E error): Result<T, E>

Returns a failure Result wrapping error.

schema.validator

Source: stdlib/schema/validator.gb

Class Validator

class Validator

Holds a schema definition and validates values against it.

Field schemaDict

dict<string, any> schemaDict

Method Validator

func Validator(dict<string, any> schemaDict)

Method validate

func validate(any value): dict<string, any>

Validates value and returns a Result.

Method isValid

func isValid(any value): bool

Returns true when value passes validation.

Method errors

func errors(any value): list<string>

Returns the list of error strings for a failed validation, or empty list.

Method fieldErrors

func fieldErrors(any value, string field): list<string>

Returns errors for a specific dotted-path prefix (e.g. "$.name").

Function of

func of(dict<string, any> schemaDict): Validator

Returns a Validator wrapping the given schema dict.

Function validate

func validate(any value, dict<string, any> schemaDict): dict<string, any>

Validates value directly and returns the result dict {valid, errors}.

seq

Source: stdlib/seq.gb

Class Stream

class Stream<T>

A lazy, single-use fluent pipeline over any iterable (list, set, range, or generator). Intermediate operations build a generator chain and run nothing; a terminal operation pulls values through the whole pipeline once, so no intermediate lists are materialised.

import collections;

let total = collections.stream([1, 2, 3, 4, 5, 6])
.filter(func(any n): bool { return (n as int) % 2 == 0; })
.map(func(any n): any { return (n as int) * (n as int); })
.sum();                       # 56, no intermediate lists

let firstBig = collections.stream(1..1000000)
.map(func(any n): any { return (n as int) * 2; })
.first();                     # 2, pulls a single element

A stream is consumed by its terminal operation; reuse the source (or build a new stream) to iterate again.

Field _source

any _source

Method Stream

func Stream(any source)

Method map

func map(callable fn): Stream<any>

Transforms each element through fn.

Method filter

func filter(callable fn): Stream<any>

Keeps elements for which fn returns true.

Method flatMap

func flatMap(callable fn): Stream<any>

Maps each element to an iterable and flattens the results.

Method take

func take(int n): Stream<any>

Yields at most the first n elements.

Method drop

func drop(int n): Stream<any>

Skips the first n elements.

Method takeWhile

func takeWhile(callable fn): Stream<any>

Yields elements until fn first returns false.

Method dropWhile

func dropWhile(callable fn): Stream<any>

Skips the leading run for which fn returns true, then yields the rest.

Method distinct

func distinct(): Stream<any>

Yields only the first occurrence of each distinct element.

Method peek

func peek(callable fn): Stream<any>

Runs fn on each element as it passes (for side effects), unchanged.

Method sorted

func sorted(?callable compare = null): Stream<any>

Buffers the pipeline and yields elements in sorted order. No callback = natural order; callback is a less-than predicate (a,b)->bool or a three-way comparator (a,b)->int.

Method sortedBy

func sortedBy(callable keySelector, bool descending = false): Stream<any>

Buffers the pipeline and yields elements sorted by a key.

Method toList

func toList(): list<any>

Collects the remaining elements into a list.

Method toSet

func toSet(): set<any>

Collects the remaining elements into a set (dropping duplicates).

Method forEach

func forEach(callable fn): void

Runs fn for each remaining element.

Method count

func count(): int

Number of remaining elements.

Method reduce

func reduce(any initial, callable fn): any

Folds the elements with fn(accumulator, element) from initial.

Method first

func first(): any

First element, or null if the stream is empty.

Method firstOr

func firstOr(any fallback): any

First element, or fallback if the stream is empty.

Method find

func find(callable fn): any

First element matching fn, or null.

Method any

func any(callable fn): bool

True if any element matches fn.

Method all

func all(callable fn): bool

True if every element matches fn (true for an empty stream).

Method none

func none(callable fn): bool

True if no element matches fn.

Method sum

func sum(): any

Sum of the elements (0 for an empty stream).

Method min

func min(?callable compare = null): any

Smallest element, or null if empty. No callback = natural order; callback is a less-than predicate (a,b)->bool.

Method max

func max(?callable compare = null): any

Largest element, or null if empty (less-than predicate as for min).

Method join

func join(string separator): string

Joins the elements into a string with separator.

Function stream

func stream(any source): Stream<any>

Wraps any iterable in a lazy Stream.

sockets

Source: stdlib/sockets.gb

Class Socket

class Socket

Socket is a TCP (or TLS) connection wrapped in the F3 stream protocol. Methods: read / readAll / readLine / lines / write / writeln / close / isClosed plus the iterator dunder so for (line in sock) { ... } yields lines.

Construct via sockets.dial(host, port, opts?); for server-side sockets you receive a Socket via the sockets.serve(...) callback.

Field handle

int handle

Field stream

streams.IOStream stream

Field _localAddr

string _localAddr

Field _remoteAddr

string _remoteAddr

Field _closed

bool _closed

Method Socket

func Socket(int handle, streams.IOStream stream, string localAddr, string remoteAddr)

Method read

func read(int n): string

Method readAll

func readAll(): string

Method readLine

func readLine(): ?string

Method lines

func lines(): generator<string>

Method write

func write(string buf): int

Method writeln

func writeln(string buf): int

Method close

func close(): void

Method isClosed

func isClosed(): bool

Method localAddr

func localAddr(): string

Method remoteAddr

func remoteAddr(): string

Method __read

func __read(int n): string

F3 dunder protocol so streams.copy / streams.readAll work directly on a Socket.

Method __write

func __write(string buf): int

Method __close

func __close(): void

Method __iter

func __iter(): any

Class Listener

class Listener

Listener owns a bound port and the goroutine that dispatches incoming connections to the user's handler. close() stops accepting and waits for the in-flight handler call (if any) to finish before returning.

Field handle

int handle

Field _localAddr

string _localAddr

Field _closed

bool _closed

Method Listener

func Listener(int handle, string localAddr)

Method close

func close(): void

Method isClosed

func isClosed(): bool

Method localAddr

func localAddr(): string

Function dial

func dial(string host, int port, dict<string, any> opts = {...}): Socket

Opens a TCP (or TLS) connection. opts may include {tls: true} to wrap with TLS and {timeoutMs: int} to bound the connect time.

Function serve

func serve(string host, int port, any handler): Listener

Starts an accept loop on the given (host, port). For each incoming connection, handler(socket) runs in a child evaluator with the original closure (mutations to module-level globals propagate). The handler receives a typed Socket. close() on the returned Listener stops the loop and waits for the current handler invocation to finish.

ssh

Source: stdlib/ssh.gb

Class ExecResult

class ExecResult

ExecResult is the structured outcome of client.exec(cmd): the command's stdout, stderr, and exit code.

Field stdout

string stdout

Field stderr

string stderr

Field exitCode

int exitCode

Method ExecResult

func ExecResult(string stdout, string stderr, int exitCode)

Class SSHSession

class SSHSession

SSHSession is a long-running remote command started by client.spawn(cmd). stdin, stdout, stderr are streams.IOStream values for piping data through the connection. Mirrors proc.Process from F4 so users can reuse muscle memory.

Field handle

int handle

Field stdin

streams.IOStream stdin

Field stdout

streams.IOStream stdout

Field stderr

streams.IOStream stderr

Method SSHSession

func SSHSession(int handle, streams.IOStream stdin, streams.IOStream stdout, streams.IOStream stderr)

Method wait

func wait(): int

Method kill

func kill(): void

Method signal

func signal(string name): void

Class SSHTunnel

class SSHTunnel

SSHTunnel is a port forward established via client.forwardLocal(...) or client.forwardRemote(...). close() stops the accept loop and joins the goroutine.

Field handle

int handle

Field _addr

string _addr

Field _closed

bool _closed

Method SSHTunnel

func SSHTunnel(int handle, string addr)

Method addr

func addr(): string

Method close

func close(): void

Method isClosed

func isClosed(): bool

Class SSHClient

class SSHClient

SSHClient is a connected SSH session. Use exec for one-shot commands, spawn for long-running commands with streaming I/O, the upload / download / sftpList / sftpRemove / sftpMkdir / sftpOpen family for file transfer, and forwardLocal / forwardRemote for port forwarding.

Field handle

int handle

Field user

string user

Field remoteAddr

string remoteAddr

Field _closed

bool _closed

Method SSHClient

func SSHClient(int handle, string user, string remoteAddr)

Method exec

func exec(string command): ExecResult

Runs a single command and returns its full output.

Method spawn

func spawn(string command): SSHSession

Spawns a long-running command and returns immediately with an SSHSession exposing IOStream-shaped stdin / stdout / stderr.

Method upload

func upload(string localPath, string remotePath): int

Uploads a local file via SFTP. Returns bytes transferred.

Method download

func download(string remotePath, string localPath): int

Downloads a remote file via SFTP. Returns bytes transferred.

Method sftpList

func sftpList(string remotePath): list<dict<string, any>>

Lists a remote directory. Returns a list of dicts {name, size, mode, isDir, modUnix}.

Method sftpRemove

func sftpRemove(string remotePath): void

Method sftpMkdir

func sftpMkdir(string remotePath, int mode = 0o755): void

Method sftpOpen

func sftpOpen(string remotePath, string mode = "r"): streams.IOStream

Opens a remote file as a streams.IOStream. mode is "r", "w", or "a". Combine with streams.copy(...) to ship bytes around the SSH connection.

Method forwardLocal

func forwardLocal(int localPort, string remoteTarget): SSHTunnel

Forwards a local port to a remote target through the SSH server. Returns an SSHTunnel; close it to stop the loop.

Method forwardRemote

func forwardRemote(int remotePort, string localTarget): SSHTunnel

Forwards a remote port back to a local target. The remote SSH server binds the port; connections are tunneled to this host. Returns an SSHTunnel; close it to stop the loop.

Method close

func close(): void

Method isClosed

func isClosed(): bool

Function connect

func connect(string target, dict<string, any> opts = {...}): SSHClient

Connects to an SSH server. target is either "user@host" or just "host" (defaults to $USER). opts configures authentication and host-key verification:

Auth (at least one required):

  • password: string
  • privateKey: PEM-encoded key as string
  • privateKeyFile: path to PEM key
  • passphrase: decrypts the key
  • agent: bool, use $SSH_AUTH_SOCK

Host key verification (at least one required):

  • knownHostsFile: path to a known_hosts file
  • insecureSkipHostKey: bool, skip verification (dev only!)

Other:

  • port: int, default 22
  • timeoutMs: int, connect timeout

store

Source: stdlib/store.gb

Class Store

class Store

Thread-safe shared key-value store: the sanctioned way to share mutable state across requests / goroutines. Each request runs on its own goroutine, so sharing a plain dict across them is unsafe (concurrent access crashes the process). A Store serialises every access internally and deep-copies values in and out, so a stored value is an isolated snapshot a caller cannot mutate behind the lock.

import store;

let hits = store.Store();
hits.incr("/home");                 # atomic counter
hits.set("cfg", {"theme": "dark"});
let cfg = hits.get("cfg");

# atomic read-modify-write (compare-and-set retry loop):
hits.update("total", func(any old): any {
return (old == null ? 0 : old as int) + 1;
});

Share infrastructure (db pools, caches) through their own handles; reach for a Store when you need a shared mutable map.

Field _handle

any _handle

Method Store

func Store()

Method get

func get(any key): any

Returns the value for key, or null if absent (a deep copy).

Method set

func set(any key, any value)

Stores a deep copy of value under key.

Method has

func has(any key): bool

Reports whether key is present.

Method delete

func delete(any key): bool

Removes key; returns whether it was present.

Method clear

func clear()

Removes all entries.

Method len

func len(): int

Number of entries.

Method keys

func keys(): list<any>

Keys in a deterministic order.

Method values

func values(): list<any>

Values in the same order as keys() (deep copies).

Method incr

func incr(any key, int delta = 1): int

Atomically adds delta (default 1) to the int at key, treating a missing key as 0; returns the new value.

Method getOrSet

func getOrSet(any key, any value): any

Returns the value at key, or atomically stores and returns value if absent.

Method compareAndSet

func compareAndSet(any key, any expected, any next): bool

Atomically sets key to next only if its current value equals expected (null matches an absent key); returns success.

Method update

func update(any key, callable fn): any

Atomic read-modify-write: applies fn to the current value (null if absent) and stores the result, retrying on contention. Do NOT touch this same key non-atomically inside fn.

streams

Source: stdlib/streams.gb

Class Stream

class Stream

Stream wraps any iterable (list, set, generator, range, or another class with the 1.0.6 iterator protocol) and exposes a fluent, lazy-by-default API. Intermediate steps (map, filter, take) return a new Stream that pulls values on demand; terminal steps (toList, count, reduce, forEach, first, anyMatch, allMatch, toSet) materialise the pipeline.

Streams implement __iter() so they slot directly into for (x in stream) loops and anywhere an iterable<T> is expected.

Field source

any source

Method Stream

func Stream(any source)

Method map

func map(any fn): Stream

Intermediate: maps each value through fn. Applied lazily.

Method filter

func filter(any fn): Stream

Intermediate: keeps values for which fn returns true. Applied lazily.

Method take

func take(int n): Stream

Intermediate: yields at most the first n values.

Method __iter

func __iter(): any

Iterator-protocol entry point: forwards iteration to the wrapped source so for (x in stream) walks the pipeline without materialising it.

Method toList

func toList(): list<any>

Terminal: materialises the pipeline into a list.

Method toSet

func toSet(): set<any>

Terminal: materialises the pipeline into a set. Duplicates collapse.

Method count

func count(): int

Terminal: counts values produced by the pipeline.

Method first

func first(): any

Terminal: returns the first value, or null when empty.

Method forEach

func forEach(any fn): void

Terminal: invokes fn(value) for each value.

Method reduce

func reduce(any initial, any fn): any

Terminal: folds the pipeline left-to-right starting from initial. fn(accumulator, value) returns the next accumulator.

Method anyMatch

func anyMatch(any fn): bool

Terminal: true when at least one value satisfies fn.

Method allMatch

func allMatch(any fn): bool

Terminal: true when every value satisfies fn (vacuously true for an empty pipeline).

Function of

func of(any source): Stream

Wraps any iterable in a Stream for fluent chaining.

Class IOStream

class IOStream

IOStream wraps a low-level handle (file, in-memory buffer, stdin / stdout / stderr) in the F3 stream protocol. Methods: read / readAll / readLine / lines / write / writeln / flush / close / isClosed. Memory-backed instances also expose toString(); non-memory handles raise on that call.

Iterating a stream yields lines: for (line in stream) { ... }. Implements the protocol dunders __read / __write / __close so helpers like streams.copy / streams.readAll consume it without going through the named methods.

Field handle

any handle

Field _closed

bool _closed

Method IOStream

func IOStream(any handle)

Method read

func read(int n): string

Reads up to n bytes from the stream. Returns the empty string at EOF.

Method readAll

func readAll(): string

Reads the entire remaining contents of the stream into a single string.

Method readLine

func readLine(): ?string

Reads the next line with the trailing \n (or \r\n) stripped. Returns null at EOF.

Method lines

func lines(): generator<string>

Lazy generator yielding each line until EOF.

Method write

func write(string buf): int

Writes buf and returns the number of bytes written.

Method writeln

func writeln(string buf): int

Writes buf followed by a newline.

Method seek

func seek(int offset, string whence = "start"): int

Repositions a seekable (file-backed) stream; whence is "start", "current", or "end". Returns the new offset. Raises on memory and standard streams.

Method tell

func tell(): int

Current byte offset of a seekable (file-backed) stream.

Method truncate

func truncate(int size): void

Resizes a file-backed stream to size bytes.

Method atEnd

func atEnd(): bool

Whether a file-backed stream is at end-of-file.

Method flush

func flush(): void

Flushes any buffered output.

Method close

func close(): void

Closes the underlying resource. Safe to call more than once.

Method isClosed

func isClosed(): bool

True after close() has been called.

Method toString

func toString(): string

Returns the full buffer contents of a memory-backed stream without moving the read cursor. Raises on file / stdin / stdout / stderr handles.

Method __read

func __read(int n): string

Method __write

func __write(string buf): int

Method __close

func __close(): void

Method __iter

func __iter(): any

Function open

func open(string path, string mode = "r"): IOStream

Opens a file and wraps it in an IOStream. mode accepts the same strings as io.open (e.g. "r", "w", "a", "r+").

Function memory

func memory(string initial = ""): IOStream

Returns an IOStream backed by an in-memory buffer. The optional initial argument seeds the buffer; reads pull from the seed first, then from anything subsequently written. Memory-backed streams support toString() for inspection.

Function stdin

func stdin(): IOStream

Wraps stdin in an IOStream.

Function stdout

func stdout(): IOStream

Wraps stdout in an IOStream.

Function stderr

func stderr(): IOStream

Wraps stderr in an IOStream.

Function readAll

func readAll(any src, int chunk = 4096): string

Reads everything from src (anything with a __read(int) method) until EOF and returns the accumulated string.

Function copy

func copy(any src, any dst, int chunk = 4096): int

Pipes everything from src.__read(chunk) into dst.__write(...) until src returns EOF. Returns the total number of bytes transferred (as reported by dst.__write).

strings

Source: stdlib/strings.gb

Class StringBuilder

class StringBuilder

Builder-backed string accumulator for tight loops that append many fragments. Amortised O(n) vs O(n²) for naive concatenation. Call dispose() in long-running code to release the underlying handle.

Field handle

any handle

Method StringBuilder

func StringBuilder(string initial = "")

Method append

func append(string s): StringBuilder

Append a string fragment. Returns this for chaining.

Method appendLine

func appendLine(string s): StringBuilder

Append a fragment followed by a newline. Returns this for chaining.

Method build

func build(): string

Materialise the accumulated content as a string.

Method length

func length(): int

Current byte length of the accumulated content.

Method clear

func clear(): StringBuilder

Reset the buffer to empty. Returns this for chaining.

Method dispose

func dispose()

Release the underlying handle. Safe to call multiple times.

testing.assertions

Source: stdlib/testing/assertions.gb

Function contains

func contains(string text, string needle): bool

Returns true when text contains needle.

Function startsWith

func startsWith(string text, string prefix): bool

Returns true when text starts with prefix.

Function endsWith

func endsWith(string text, string suffix): bool

Returns true when text ends with suffix.

Function isBlank

func isBlank(string text): bool

Returns true when text is empty after trimming whitespace.

time.scheduler

Source: stdlib/time/scheduler.gb

Class Timer

class Timer

A one-shot timer that runs fn once after ms milliseconds.

The callback runs on an async task. The timer can be cancelled before it fires with timer.cancel(). After the timer fires (or is cancelled), timer.done is true.

import time.scheduler as sched;
import io;

let t = sched.Timer(500, func(): void {
io.println("fired");
});
# ... do other work ...
await t.wait();

Field task

Task task

Field stopper

Task stopper

Method Timer

func Timer(int ms, func cb)

Method cancel

func cancel(): void

Cancels the timer. If it has not yet fired, the callback will not run.

Method wait

func wait(): Task<any>

Returns a Task that resolves once the timer fires or is cancelled.

Method didFire

func didFire(): bool

True once the callback has run (false if cancelled before firing).

Class Ticker

class Ticker

A repeating ticker that runs fn every ms milliseconds.

The first invocation happens after the first ms-millisecond delay (not immediately). The ticker runs until ticker.stop() is called. After stopping, ticker.ticks() reports how many times fn ran.

import time.scheduler as sched;
import io;

let ticker = sched.Ticker(100, func(): void {
io.println("tick");
});
await async.sleep(350);
ticker.stop();
io.println("fired " + (ticker.ticks() as string) + " times");

Field task

Task task

Field stopper

Task stopper

Method Ticker

func Ticker(int ms, func cb)

Method stop

func stop(): void

Stops the ticker. Any in-flight tick completes; no further ticks fire.

Method ticks

func ticks(): int

How many times the callback has run so far. Blocks until the ticker's in-flight sleep finishes after stop().

Method wait

func wait(): Task<any>

Returns a Task that resolves once the ticker is stopped.

Class Interval

class Interval

Convenience: like Ticker(ms, fn) but also runs fn once immediately, before starting the interval timer.

Use this for poll-on-startup-then-keep-polling patterns where you do not want to wait an entire interval for the first run.

let poll = sched.Interval(60000, func(): void {
refreshConfig();
});
# ...
poll.stop();

Field inner

Ticker inner

Method Interval

func Interval(int ms, func cb)

Method stop

func stop(): void

Method ticks

func ticks(): int

Method wait

func wait(): Task<any>

Function setTimeout

func setTimeout(int ms, func fn): Timer

Helper: run fn once after ms milliseconds. Returns the Timer so the caller can cancel if needed.

let t = sched.setTimeout(1000, func(): void { io.println("hi"); });

Function setInterval

func setInterval(int ms, func fn): Ticker

Helper: run fn every ms milliseconds. Returns the Ticker so the caller can stop it.

let t = sched.setInterval(1000, func(): void { tick(); });

time.stopwatch

Source: stdlib/time/stopwatch.gb

Class Stopwatch

class Stopwatch

A monotonic stopwatch for measuring elapsed durations. Backed by time.monotonic(), so it is immune to wall-clock jumps and is the correct tool for timing work, laps, and timeouts.

import time.stopwatch as sw;
import io;

let s = sw.Stopwatch();
# ... work block A ...
io.println("lap A: " + (s.lap() as string) + " ms");
# ... work block B ...
io.println("lap B: " + (s.lap() as string) + " ms");
io.println("total: " + (s.elapsed() as string) + " ms");

Field startMs

int startMs

Field lapMs

int lapMs

Method Stopwatch

func Stopwatch()

Method elapsed

func elapsed(): int

Milliseconds since creation or the last reset().

Method elapsedFloat

func elapsedFloat(): float

Fractional seconds since creation or the last reset().

Method lap

func lap(): int

Milliseconds since the previous lap (or creation), advancing the lap marker. Call repeatedly to time successive segments.

Method reset

func reset(): void

Restarts the stopwatch from zero.

vectorstore

Source: stdlib/vectorstore.gb

Class VectorRecord

class VectorRecord

In-memory and persistent vector stores for embeddings, with brute-force similarity search. The foundation for retrieval-augmented generation (see the rag module).

import vectorstore;

let store = vectorstore.MemoryVectorStore();
store.add("a", [0.1, 0.2, 0.9], {"text": "about cats"});
store.add("b", [0.9, 0.1, 0.1], {"text": "about cars"});
let hits = store.search([0.1, 0.2, 0.8], 1);   // -> [SearchHit for "a"]
io.println(hits[0].record.metadata["text"]);

Metric is cosine by default; pass "dot" or "euclidean" to the constructor. All scores follow "higher = closer".

Field id

string id

Field vector

list<any> vector

Field metadata

dict<string, any> metadata

Method VectorRecord

func VectorRecord(string id, list<any> vector, dict<string, any> metadata)

Class SearchHit

class SearchHit

Field record

VectorRecord record

Field score

float score

Method SearchHit

func SearchHit(VectorRecord record, float score)

Interface VectorStore

interface VectorStore

A store of id-keyed vectors supporting nearest-neighbour search.

Method add

func add(string id, list<any> vector, dict<string, any> metadata): void

Method addAll

func addAll(list<VectorRecord> records): void

Method get

func get(string id): ?VectorRecord

Method delete

func delete(string id): bool
func search(list<any> query, int k): list<SearchHit>

Method searchWhere

func searchWhere(list<any> query, int k, callable filter): list<SearchHit>

Method searchFilter

func searchFilter(list<any> query, int k, dict<string, any> criteria): list<SearchHit>

Method count

func count(): int

Method clear

func clear(): void

Class MemoryVectorStore

class MemoryVectorStore implements VectorStore

Brute-force in-memory store. O(n) per search; ideal up to ~1e4-1e5 vectors. Mutations and the search snapshot are guarded by a mutex, so a single shared store is safe under concurrent requests.

Field _records

dict<string, any> _records

Field _metric

string _metric

Field _lock

sync.Mutex _lock

Method MemoryVectorStore

func MemoryVectorStore(string metric = "cosine")

Method add

func add(string id, list<any> vector, dict<string, any> metadata): void

Method addAll

func addAll(list<VectorRecord> records): void

Method get

func get(string id): ?VectorRecord

Method delete

func delete(string id): bool

Method count

func count(): int

Method clear

func clear(): void

Method search

func search(list<any> query, int k): list<SearchHit>

Method searchWhere

func searchWhere(list<any> query, int k, callable filter): list<SearchHit>

Method searchFilter

func searchFilter(list<any> query, int k, dict<string, any> criteria): list<SearchHit>

Class SqliteVectorStore

class SqliteVectorStore implements VectorStore

Persistent store backed by a SQL table via the db module. Vectors are stored as little-endian float32 BLOBs and metadata as JSON text; search loads the rows and ranks them in memory (no SQL-side ANN). The table is created on construction if absent. add() upserts by id.

import db; import vectorstore;
let conn = db.connect("sqlite", "vectors.db");
let store = vectorstore.SqliteVectorStore(conn);
store.add("doc-1", embedding, {"text": "..."});
let hits = store.search(queryVector, 5);

Field _conn

any _conn

Field _table

string _table

Field _metric

string _metric

Method SqliteVectorStore

func SqliteVectorStore(any conn, string table = "vectors", string metric = "cosine")

Method add

func add(string id, list<any> vector, dict<string, any> metadata): void

Method addAll

func addAll(list<VectorRecord> records): void

Method get

func get(string id): ?VectorRecord

Method delete

func delete(string id): bool

Method count

func count(): int

Method clear

func clear(): void

Method search

func search(list<any> query, int k): list<SearchHit>

Method searchWhere

func searchWhere(list<any> query, int k, callable filter): list<SearchHit>

Method searchFilter

func searchFilter(list<any> query, int k, dict<string, any> criteria): list<SearchHit>

Class PgVectorStore

class PgVectorStore implements VectorStore

Persistent store backed by Postgres + the pgvector extension via the db module. Uses a typed vector(D) column, a metric-matched HNSW index, jsonb metadata, and index-using ANN queries (the same shape as idiomatic pgvector usage elsewhere). The extension, table, and index are created on construction. add() upserts by id.

import db; import vectorstore;
let conn  = db.connect("postgres", dsn);
let store = vectorstore.PgVectorStore(conn, "items", 1536);
store.add("doc-1", embedding, {"source": "handbook"});
let hits = store.searchFilter(queryVector, 5, {"source": "handbook"});

The pgvector value is bound in its text form with CAST(? AS vector); metadata filters push down server-side as jsonb containment / range predicates.

Field _conn

any _conn

Field _table

string _table

Field _dim

int _dim

Field _metric

string _metric

Method PgVectorStore

func PgVectorStore(any conn, string table = "vectors", int dimension = 0, string metric = "cosine")

Method add

func add(string id, list<any> vector, dict<string, any> metadata): void

Method addAll

func addAll(list<VectorRecord> records): void

Method get

func get(string id): ?VectorRecord

Method delete

func delete(string id): bool

Method count

func count(): int

Method clear

func clear(): void

Method search

func search(list<any> query, int k): list<SearchHit>

Method searchFilter

func searchFilter(list<any> query, int k, dict<string, any> criteria): list<SearchHit>

Method searchWhere

func searchWhere(list<any> query, int k, callable filter): list<SearchHit>

Method runSearch

func runSearch(list<any> query, int k, string whereSql, list<any> whereParams): list<SearchHit>

Class HnswVectorStore

class HnswVectorStore implements VectorStore

In-process approximate-nearest-neighbour store backed by an HNSW index (the native hnsw module). Sublinear search with no external service; ideal when the in-memory brute-force store is too slow but a database is unwanted. Metadata is held in Geblang; the index holds the vectors. add() upserts by id.

import vectorstore;
let store = vectorstore.HnswVectorStore("cosine");
store.add("doc-1", embedding, {"text": "..."});
let hits = store.search(queryVector, 5);

Results are approximate: tune recall via the constructor's m (graph degree) and efSearch (search breadth). Filtered searches over-fetch then filter, so a very selective filter may return fewer than k hits.

Field _index

any _index

Field _metric

string _metric

Field _meta

dict<string, any> _meta

Field _lock

sync.Mutex _lock

Method HnswVectorStore

func HnswVectorStore(string metric = "cosine", int m = 16, int efSearch = 20)

Method add

func add(string id, list<any> vector, dict<string, any> metadata): void

Method addAll

func addAll(list<VectorRecord> records): void

Method get

func get(string id): ?VectorRecord

Method delete

func delete(string id): bool

Method count

func count(): int

Method clear

func clear(): void

Method search

func search(list<any> query, int k): list<SearchHit>

Method searchWhere

func searchWhere(list<any> query, int k, callable filter): list<SearchHit>

Method searchFilter

func searchFilter(list<any> query, int k, dict<string, any> criteria): list<SearchHit>

Method filteredSearch

func filteredSearch(list<any> query, int k, callable keep): list<SearchHit>

Method toHit

func toHit(dict<string, any> h): SearchHit

Function score

func score(string metric, list<any> a, list<any> b): float

Similarity score (higher = closer) between two vectors for the given metric.

web.auth

Source: stdlib/web/auth.gb

Function login

func login(any sessionStore, dict<string, any> response, dict<string, any> user, dict<string, any> options): dict<string, any>

Saves a user dictionary in the supplied session store and returns the updated response.

Function logout

func logout(any sessionStore, dict<string, any> response, dict<string, any> request): dict<string, any>

Clears the current user session through the supplied session store.

Function currentUser

func currentUser(any sessionStore, dict<string, any> request): dict<string, any>

Loads the current user dictionary from the supplied session store.

Function isAuthenticated

func isAuthenticated(any sessionStore, dict<string, any> request): bool

Returns true when the request has an authenticated user in the supplied session store.

Function userHasRole

func userHasRole(dict<string, any> user, string role): bool

Returns true when a user dictionary contains a role or roles list entry.

Function userHasPermission

func userHasPermission(dict<string, any> user, string permission): bool

Returns true when a user dictionary contains a permission or permissions list entry.

Class AuthGuard

class AuthGuard

Field sessionStore

any sessionStore

Field mode

string mode

Field value

string value

Method AuthGuard

func AuthGuard(any sessionStore, string mode, string value)

Method __invoke

func __invoke(dict<string, any> request): any

Function requireAuth

func requireAuth(any sessionStore): callable

Returns middleware that requires any authenticated user.

Function requireLogin

func requireLogin(any sessionStore, string loginPath): callable

Returns middleware that redirects anonymous users to the supplied login path.

Function requireRole

func requireRole(any sessionStore, string role): callable

Returns middleware that requires an authenticated user with the supplied role.

Function requirePermission

func requirePermission(any sessionStore, string permission): callable

Returns middleware that requires an authenticated user with the supplied permission.

Function csrfToken

func csrfToken(string secret): string

Creates a signed CSRF token payload.

Function withCsrf

func withCsrf(dict<string, any> response, string secret, dict<string, any> options): dict<string, any>

Writes a CSRF token cookie to a response.

Function clearCsrf

func clearCsrf(dict<string, any> response): dict<string, any>

Clears the CSRF cookie.

Function verifyCsrf

func verifyCsrf(dict<string, any> request, string secret, string cookieName = "geb_csrf"): bool

Verifies a CSRF cookie against a submitted header or form token.

web.cache

Source: stdlib/web/cache.gb

Class RedisCacheStore

class RedisCacheStore

Cache store backed by Redis keys with JSON payloads and TTL expiry.

Field client

any client

Field prefix

string prefix

Field ttl

int ttl

Method RedisCacheStore

func RedisCacheStore(any client, string prefix, int ttl)

Method key

func key(string name): string

Method get

func get(string name): any

Method set

func set(string name, any value): bool

Method delete

func delete(string name): bool

Method has

func has(string name): bool

Function redisCacheStore

func redisCacheStore(any client, string prefix, int ttl): RedisCacheStore

Creates a Redis-backed cache store.

Class FileCacheStore

class FileCacheStore

Cache store backed by JSON files in a directory.

Field directory

string directory

Field ttl

int ttl

Method FileCacheStore

func FileCacheStore(string directory, int ttl)

Method path

func path(string name): string

Method get

func get(string name): any

Method set

func set(string name, any value): bool

Method delete

func delete(string name): bool

Method has

func has(string name): bool

Function fileCacheStore

func fileCacheStore(string directory, int ttl): FileCacheStore

Creates a file-backed cache store.

Class DatabaseCacheStore

class DatabaseCacheStore

Cache store backed by a database table with cache_key, data, and expiry columns.

Field conn

any conn

Field table

string table

Field ttl

int ttl

Method DatabaseCacheStore

func DatabaseCacheStore(any conn, string table, int ttl)

Method install

func install(): DatabaseCacheStore

Method get

func get(string name): any

Method set

func set(string name, any value): bool

Method delete

func delete(string name): bool

Method has

func has(string name): bool

Function databaseCacheStore

func databaseCacheStore(any conn, string table, int ttl): DatabaseCacheStore

Creates a database-backed cache store; call install() to create its table.

web.forms

Source: stdlib/web/forms.gb

Function bind

func bind(dict<string, any> request): dict<string, any>

Parses URL-encoded form data from a request body.

Function validate

func validate(dict<string, any> request, dict<string, any> rules): dict<string, any>

Validates request form data and returns a result with valid, errors, and data keys.

Function isValid

func isValid(dict<string, any> result): bool

Returns true when a form validation result is valid.

Function data

func data(dict<string, any> result): dict<string, any>

Returns parsed form data from a validation result.

Function fieldErrors

func fieldErrors(dict<string, any> result, string field): list<any>

Returns all validation errors for a field.

Function hasFieldError

func hasFieldError(dict<string, any> result, string field): bool

Returns true when a field has validation errors.

Function firstFieldError

func firstFieldError(dict<string, any> result, string field): string

Returns the first validation error for a field, or an empty string.

Function csrfField

func csrfField(string token): string

Builds an HTML hidden input for a CSRF token value.

Function withCsrf

func withCsrf(dict<string, any> response, string secret, dict<string, any> options): dict<string, any>

Adds a CSRF cookie to a response using web.auth.

Function verifyCsrf

func verifyCsrf(dict<string, any> request, string secret, string cookieName = "geb_csrf"): bool

Returns true when a request passes web.auth CSRF verification.

Function redirectWithFlash

func redirectWithFlash(any sessionStore, dict<string, any> request, string location, string category, string message, dict<string, any> options): dict<string, any>

Creates a redirect response with a flash message saved to the session store.

Function redirectSuccess

func redirectSuccess(any sessionStore, dict<string, any> request, string location, string message, dict<string, any> options): dict<string, any>

Creates a redirect response with a success flash message.

Function redirectError

func redirectError(any sessionStore, dict<string, any> request, string location, string message, dict<string, any> options): dict<string, any>

Creates a redirect response with an error flash message.

web.http

Source: stdlib/web/http.gb

Class Request

class Request

Object wrapper for request dictionaries with query, form, JSON, header, parameter, and cookie helpers.

Field data

dict<string, any> data

Method Request

func Request(dict<string, any> data)

Method method

func method(): string

Method path

func path(): string

Method body

func body(): any

Method query

func query(): dict<string, any>

Method queryParam

func queryParam(string name): string

Method form

func form(): dict<string, any>

Method formValue

func formValue(string name): string

Method jsonBody

func jsonBody(): dict<string, any>

Method validate

func validate(dict<string, any> rules): dict<string, any>

Method validateForm

func validateForm(dict<string, any> rules): dict<string, any>

Method headers

func headers(): dict<string, any>

Method header

func header(string name): string

Method hasHeader

func hasHeader(string name): bool

Method params

func params(): dict<string, any>

Method param

func param(string name): string

Method paramDefault

func paramDefault(string name, string fallback): string

Method hasParam

func hasParam(string name): bool

Method cookies

func cookies(): dict<string, any>
func cookie(string name): string

Method toDict

func toDict(): dict<string, any>

Class Response

class Response

Object wrapper for response dictionaries with fluent header and cookie mutation helpers.

Field data

dict<string, any> data

Method Response

func Response(int status, any body)

Method header

func header(string name, string value): Response

Method statusCode

func statusCode(): int

Method body

func body(): any

Method headers

func headers(): dict<string, any>

Method headerValue

func headerValue(string name): string

Method hasHeader

func hasHeader(string name): bool
func cookie(string name, string value): Response

Method cookieOptions

func cookieOptions(string name, string value, dict<string, any> options): Response

Method toDict

func toDict(): dict<string, any>

Class Context

class Context

Per-request convenience object combining Request accessors with common response builders.

Field request

Request request

Method Context

func Context(dict<string, any> request)

Method method

func method(): string

Method path

func path(): string

Method body

func body(): any

Method query

func query(): dict<string, any>

Method queryParam

func queryParam(string name): string

Method form

func form(): dict<string, any>

Method formValue

func formValue(string name): string

Method jsonBody

func jsonBody(): dict<string, any>

Method validate

func validate(dict<string, any> rules): dict<string, any>

Method validateForm

func validateForm(dict<string, any> rules): dict<string, any>

Method header

func header(string name): string

Method hasHeader

func hasHeader(string name): bool

Method cookies

func cookies(): dict<string, any>
func cookie(string name): string

Method params

func params(): dict<string, any>

Method param

func param(string name): string

Method paramDefault

func paramDefault(string name, string fallback): string

Method hasParam

func hasParam(string name): bool

Method text

func text(any body): dict<string, any>

Method json

func json(any body): dict<string, any>

Method html

func html(any body): dict<string, any>

Method render

func render(string source, dict<string, any> data): dict<string, any>

Method status

func status(int code): dict<string, any>

Method redirect

func redirect(string location): dict<string, any>

Function request

func request(string method, string path): dict<string, any>

Builds a minimal request dictionary with method, path, parsed query parameters, and an empty body.

Function requestWithBody

func requestWithBody(string method, string path, any body): dict<string, any>

Builds a request dictionary with method, path, parsed query parameters, and body.

Function requestObject

func requestObject(dict<string, any> data): Request

Wraps a request dictionary in a Request object.

Function responseObject

func responseObject(int status, any body): Response

Creates a Response object with status and body.

Function context

func context(dict<string, any> request): Context

Wraps a request dictionary in a Context object.

Function validate

func validate(dict<string, any> request, dict<string, any> rules): dict<string, any>

Validates a request JSON body against schema rules.

Function validateForm

func validateForm(dict<string, any> request, dict<string, any> rules): dict<string, any>

Validates a request form body against schema rules.

Function text

func text(any body): dict<string, any>

Creates a 200 response dictionary with the supplied body.

Function response

func response(int status, any body): dict<string, any>

Creates a response dictionary with explicit status and body.

Function normalize

func normalize(any value): dict<string, any>

Normalizes strings, null, and response dictionaries into a response dictionary.

Function statusCode

func statusCode(dict<string, any> response): int

Returns the status code from a response dictionary, defaulting to 200.

Function body

func body(dict<string, any> response): any

Returns the body from a response dictionary, defaulting to an empty string.

Function responseFrom

func responseFrom(dict<string, any> data): Response

Wraps an existing response dictionary in a Response object.

Function headers

func headers(dict<string, any> response): dict<string, any>

Returns response headers, defaulting to an empty dictionary.

Function header

func header(dict<string, any> response, string name): string

Returns a response header value using case-insensitive lookup.

Function hasHeader

func hasHeader(dict<string, any> response, string name): bool

Returns true when a response header is present using case-insensitive lookup.

Function withHeader

func withHeader(dict<string, any> response, string name, string value): dict<string, any>

Adds or replaces a response header.

Function status

func status(int code): dict<string, any>

Creates an empty response dictionary with the supplied status code.

Function jsonResponse

func jsonResponse(any body): dict<string, any>

Creates a JSON response with status 200 and application/json content type.

Function jsonStatus

func jsonStatus(any body, int status): dict<string, any>

Creates a JSON response with an explicit status code.

Function jsonCreated

func jsonCreated(any body): dict<string, any>

Creates a JSON response with status 201.

Function jsonError

func jsonError(string message, int status): dict<string, any>

Creates a JSON error response with an error message and status code.

Function html

func html(any body): dict<string, any>

Creates an HTML response with status 200 and text/html content type.

Function htmlStatus

func htmlStatus(any body, int status): dict<string, any>

Creates an HTML response with an explicit status code.

Function render

func render(string source, dict<string, any> data): dict<string, any>

Renders a template string with data into an HTML response.

Function redirectStatus

func redirectStatus(string location, int status): dict<string, any>

Creates a redirect response with an explicit status code.

Function redirect

func redirect(string location): dict<string, any>

Creates a 302 redirect response with a Location header.

Function created

func created(any body): dict<string, any>

Creates a 201 Created response.

Function noContent

func noContent(): dict<string, any>

Creates a 204 No Content response.

Function badRequest

func badRequest(any body): dict<string, any>

Creates a 400 Bad Request response.

Function unauthorized

func unauthorized(any body): dict<string, any>

Creates a 401 Unauthorized response.

Function forbidden

func forbidden(any body): dict<string, any>

Creates a 403 Forbidden response.

Function notFound

func notFound(any body): dict<string, any>

Creates a 404 Not Found response.

Function withCookie

func withCookie(dict<string, any> response, string name, string value): dict<string, any>

Adds a simple Set-Cookie header to a response dictionary.

Function withCookieOptions

func withCookieOptions(dict<string, any> response, string name, string value, dict<string, any> options): dict<string, any>

Adds a Set-Cookie header using path, domain, maxAge, sameSite, secure, and httpOnly options.

Function deleteCookie

func deleteCookie(dict<string, any> response, string name): dict<string, any>

Adds an expired Set-Cookie header for the named cookie.

web.middleware

Source: stdlib/web/middleware.gb

Class CorsMiddleware

class CorsMiddleware

Field origin

string origin

Field methods

string methods

Field headers

string headers

Field credentials

bool credentials

Method CorsMiddleware

func CorsMiddleware(string origin, string methods, string headers, bool credentials)

Method __invoke

func __invoke(dict<string, any> request, dict<string, any> response): dict<string, any>

Class SecurityHeadersMiddleware

class SecurityHeadersMiddleware

Field headers

dict<string, any> headers

Method SecurityHeadersMiddleware

func SecurityHeadersMiddleware(dict<string, any> headers)

Method __invoke

func __invoke(dict<string, any> request, dict<string, any> response): dict<string, any>

Class RequestIdMiddleware

class RequestIdMiddleware

Field headerName

string headerName

Method RequestIdMiddleware

func RequestIdMiddleware(string headerName)

Method __invoke

func __invoke(dict<string, any> request, dict<string, any> response): dict<string, any>

Class AccessLogMiddleware

class AccessLogMiddleware

Field logger

any logger

Method AccessLogMiddleware

func AccessLogMiddleware(any logger)

Method __invoke

func __invoke(dict<string, any> request, dict<string, any> response): dict<string, any>

Function cors

func cors(string origin, string methods, string headers): callable

Adds CORS response headers.

Function corsCredentials

func corsCredentials(string origin, string methods, string headers): callable

Adds CORS response headers and allows credentials.

Function securityHeaders

func securityHeaders(): callable

Adds a conservative set of browser security response headers.

Function headers

func headers(dict<string, any> values): callable

Adds custom response headers.

Function requestId

func requestId(): callable

Adds or propagates an X-Request-ID response header.

Function requestIdHeader

func requestIdHeader(string name): callable

Adds or propagates a response header for the supplied request ID header name.

Function accessLog

func accessLog(any logger): callable

Logs method, path, and status after a response is produced.

web.router

Source: stdlib/web/router.gb

Function newRouter

func newRouter(): dict<string, any>

Creates a new router dictionary around a native web app.

Function fromApp

func fromApp(any app): dict<string, any>

Wraps an existing native web app as a router dictionary.

Function group

func group(dict<string, any> router, string prefix): dict<string, any>

Creates a router group that prefixes all registered routes.

Function use

func use(dict<string, any> router, callable middleware): dict<string, any>

Adds global response middleware. The middleware receives (request, response) and returns a response.

Function before

func before(dict<string, any> router, callable middleware): dict<string, any>

Adds global before middleware. The middleware receives request and returns null or a response.

Function after

func after(dict<string, any> router, callable middleware): dict<string, any>

Adds global response middleware. Alias of use for readability.

Function route

func route(dict<string, any> router, string method, string path, any handler): dict<string, any>

Registers a route handler for an HTTP method and path.

Function get

func get(dict<string, any> router, string path, any handler): dict<string, any>

Registers a GET route handler.

Function post

func post(dict<string, any> router, string path, any handler): dict<string, any>

Registers a POST route handler.

Function put

func put(dict<string, any> router, string path, any handler): dict<string, any>

Registers a PUT route handler.

Function patch

func patch(dict<string, any> router, string path, any handler): dict<string, any>

Registers a PATCH route handler.

Function delete

func delete(dict<string, any> router, string path, any handler): dict<string, any>

Registers a DELETE route handler.

Function options

func options(dict<string, any> router, string path, any handler): dict<string, any>

Registers an OPTIONS route handler.

Function mountWithOptions

func mountWithOptions(dict<string, any> router, any controller, dict<string, any> options): dict<string, any>

Mounts a controller by reading route, prefix, middleware, auth, and policy decorators.

Function mount

func mount(dict<string, any> router, any controller): dict<string, any>

Mounts a decorator-driven controller without extra middleware or policy options.

Function handle

func handle(dict<string, any> router, dict<string, any> request): dict<string, any>

Dispatches a request dictionary through the router and returns a response dictionary.

Function raw

func raw(dict<string, any> router): any

Returns the underlying native web app value for lower-level integrations.

web.session

Source: stdlib/web/session.gb

Function session

func session(dict<string, any> request, string secret): dict<string, any>

Reads a signed cookie-backed session dictionary from a request.

Function withSession

func withSession(dict<string, any> response, dict<string, any> data, string secret, dict<string, any> options): dict<string, any>

Writes a signed cookie-backed session dictionary to a response.

Function clearSession

func clearSession(dict<string, any> response): dict<string, any>

Clears the signed cookie-backed session cookie.

Class RedisSessionStore

class RedisSessionStore

Session store backed by Redis keys and opaque session-id cookies.

Field client

any client

Field prefix

string prefix

Field ttl

int ttl

Method RedisSessionStore

func RedisSessionStore(any client, string prefix, int ttl)

Method key

func key(string id): string

Method load

func load(dict<string, any> request): dict<string, any>

Method save

func save(dict<string, any> response, dict<string, any> data, dict<string, any> options): dict<string, any>

Method clear

func clear(dict<string, any> response, dict<string, any> request): dict<string, any>

Function redisSessionStore

func redisSessionStore(any client, string prefix, int ttl): RedisSessionStore

Creates a Redis-backed session store.

Class FileSessionStore

class FileSessionStore

Session store backed by JSON files in a directory.

Field directory

string directory

Field ttl

int ttl

Method FileSessionStore

func FileSessionStore(string directory, int ttl)

Method path

func path(string id): string

Method load

func load(dict<string, any> request): dict<string, any>

Method save

func save(dict<string, any> response, dict<string, any> data, dict<string, any> options): dict<string, any>

Method clear

func clear(dict<string, any> response, dict<string, any> request): dict<string, any>

Function fileSessionStore

func fileSessionStore(string directory, int ttl): FileSessionStore

Creates a file-backed session store.

Class DatabaseSessionStore

class DatabaseSessionStore

Session store backed by a database table with id, data, and expiry columns.

Field conn

any conn

Field table

string table

Field ttl

int ttl

Method DatabaseSessionStore

func DatabaseSessionStore(any conn, string table, int ttl)

Method install

func install(): DatabaseSessionStore

Method load

func load(dict<string, any> request): dict<string, any>

Method save

func save(dict<string, any> response, dict<string, any> data, dict<string, any> options): dict<string, any>

Method clear

func clear(dict<string, any> response, dict<string, any> request): dict<string, any>

Function databaseSessionStore

func databaseSessionStore(any conn, string table, int ttl): DatabaseSessionStore

Creates a database-backed session store; call install() to create its table.

Function flashes

func flashes(any sessionStore, dict<string, any> request): list<any>

Returns queued flash messages from a session store.

Function withFlash

func withFlash(any sessionStore, dict<string, any> response, dict<string, any> request, string category, string message, dict<string, any> options): dict<string, any>

Appends a flash message to the current session and saves it.

Function clearFlashes

func clearFlashes(any sessionStore, dict<string, any> response, dict<string, any> request, dict<string, any> options): dict<string, any>

Removes flash messages from the current session and saves it.

web.sse

Source: stdlib/web/sse.gb

Function comment

func comment(string text): string

Formats a raw SSE comment frame.

Function retry

func retry(int milliseconds): string

Formats an SSE retry frame in milliseconds.

Function data

func data(string body): string

Formats a data-only SSE message.

Function event

func event(string name, string body, dict<string, any> options): string

Formats an SSE message with event, id, retry, and data fields.

Function named

func named(string name, string body): string

Formats a named SSE event without extra options.

Function stream

func stream(list<any> frames): string

Joins a list of SSE frame strings.

Function withHeaders

func withHeaders(dict<string, any> response): dict<string, any>

Adds SSE headers to a response dictionary.

Function responseText

func responseText(string body): dict<string, any>

Creates an SSE response from a preformatted body.

Function response

func response(list<any> frames): dict<string, any>

Creates an SSE response from a list of frame strings.

Class EventStream

class EventStream

Source-level wrapper around a native HTTP stream handle for live SSE responses.

Field handle

any handle

Method EventStream

func EventStream(any handle)

Method write

func write(string frame): void

Method flush

func flush(): void

Method close

func close(): void

Function streaming

func streaming(any handler): dict<string, any>

Creates a streaming SSE response. The handler receives an SSE EventStream.

Function write

func write(EventStream stream, string frame): void

Writes a formatted SSE frame to a live SSE stream.

Function flush

func flush(EventStream stream): void

Flushes a live SSE stream.

Function close

func close(EventStream stream): void

Closes a live SSE stream.

web.testing

Source: stdlib/web/testing.gb

Class Client

class Client

Small test client for dispatching request dictionaries through a router.

Field app

dict<string, any> app

Method Client

func Client(dict<string, any> app)

Method request

func request(string method, string path): dict<string, any>

Method requestWithBody

func requestWithBody(string method, string path, any body): dict<string, any>

Method get

func get(string path): dict<string, any>

Method post

func post(string path, any body): dict<string, any>

Function client

func client(dict<string, any> app): Client

Creates a test client for a router dictionary.

Function hasStatus

func hasStatus(dict<string, any> response, int status): bool

Returns true when a response has the expected status code.

Function hasHeader

func hasHeader(dict<string, any> response, string name, string value): bool

Returns true when a response header exactly matches a value.

Function hasBody

func hasBody(dict<string, any> response, any body): bool

Returns true when a response body exactly matches a value.

web.validation

Source: stdlib/web/validation.gb

Function object

func object(dict<string, any> properties, list<any> required): dict<string, any>

Builds an object schema from property rules and a required-field list.

Function stringField

func stringField(): dict<string, any>

Builds a string field schema.

Function intField

func intField(): dict<string, any>

Builds an integer field schema.

Function numberField

func numberField(): dict<string, any>

Builds a numeric field schema accepting int, decimal, or float.

Function boolField

func boolField(): dict<string, any>

Builds a boolean field schema.

Function arrayOf

func arrayOf(dict<string, any> itemSchema): dict<string, any>

Builds an array/list field schema.

Function enumOf

func enumOf(list<any> values): dict<string, any>

Builds a field schema constrained to a fixed list of values.

Function validate

func validate(dict<string, any> data, dict<string, any> rules): dict<string, any>

Validates an arbitrary dictionary and includes the input data in the result.

Function json

func json(dict<string, any> request, dict<string, any> rules): dict<string, any>

Validates a request JSON body and includes parsed data in the result.

Function form

func form(dict<string, any> request, dict<string, any> rules): dict<string, any>

Validates a request form body and includes parsed data in the result.

Function isValid

func isValid(dict<string, any> validation): bool

Returns true when a validation result is valid.

Function errors

func errors(dict<string, any> validation): list<any>

Returns validation errors from a validation result.

Function data

func data(dict<string, any> validation): dict<string, any>

Returns validated data from a validation result.

Function errorResponseStatus

func errorResponseStatus(dict<string, any> validation, int status): dict<string, any>

Builds a JSON validation error response with an explicit status.

Function errorResponse

func errorResponse(dict<string, any> validation): dict<string, any>

Builds a JSON validation error response, defaulting to HTTP 422.

web.websocket

Source: stdlib/web/websocket.gb

Class Connection

class Connection

Source-level wrapper around a native WebSocket connection handle.

Field handle

any handle

Method Connection

func Connection(any handle)

Method sendText

func sendText(string message): void

Method readText

func readText(): string

Method sendJson

func sendJson(any value): void

Method readJson

func readJson(): dict<string, any>

Method sendBytes

func sendBytes(bytes data): void

Method readBytes

func readBytes(): bytes

Method close

func close(): void

Method echoText

func echoText(): void

Function upgrade

func upgrade(any handler): dict<string, any>

Creates a WebSocket upgrade response for a connection handler.

Function upgradeWithHeaders

func upgradeWithHeaders(any handler, dict<string, any> headers): dict<string, any>

Creates a WebSocket upgrade response with extra response headers.

Function connect

func connect(string url): Connection

Connects to a WebSocket URL.

Function connectWithHeaders

func connectWithHeaders(string url, dict<string, any> headers): Connection

Connects to a WebSocket URL with request headers.

Function sendText

func sendText(Connection conn, string message): void

Sends a text message.

Function readText

func readText(Connection conn): string

Reads a text message.

Function sendJson

func sendJson(Connection conn, any value): void

Sends a value as JSON text.

Function readJson

func readJson(Connection conn): dict<string, any>

Reads a JSON text message as a dictionary.

Function sendBytes

func sendBytes(Connection conn, bytes data): void

Sends bytes.

Function readBytes

func readBytes(Connection conn): bytes

Reads bytes.

Function close

func close(Connection conn): void

Closes a WebSocket connection.

Function echoText

func echoText(Connection conn): void

Runs a simple text echo loop until the client closes.