API Reference
Auto-generated from source. 78 files, 779 public items.
Table of Contents
- ai.zig13
- ai/agent.zig19
- ai/chat.zig15
- ai/client.zig6
- ai/embedding.zig3
- ai/fmt.zig4
- ai/models.zig2
- app.zig4
- cli.zig12
- config.zig2
- container.zig17
- context.zig15
- cron.zig16
- crypto.zig1
- dom.zig5
- dom/document.zig11
- dom/element.zig12
- dom/local_name.zig5
- dom/node.zig9
- dom/parser.zig5
- dom/text.zig2
- entities.zig5
- event.zig6
- ext.zig3
- ext/github.zig6
- ext/hackernews.zig6
- ext/reddit.zig7
- html2md.zig9
- http.zig5
- http/client.zig14
- injector.zig8
- iter.zig3
- js.zig5
- main.zig53
- meta.zig30
- middleware/cors.zig1
- middleware/logger.zig1
- middleware/static.zig2
- middleware/swagger.zig2
- mime.zig2
- monitor.zig1
- parse.zig1
- pdf.zig24
- queue.zig17
- regex.zig7
- resource.zig9
- route.zig18
- sax.zig7
- schema.zig4
- selector.zig6
- sendmail.zig4
- serde.zig15
- serde/csv.zig6
- serde/json.zig8
- serde/table.zig7
- serde/yaml.zig7
- server.zig7
- ssr.zig19
- string.zig2
- testing.zig10
- time.zig41
- tpl.zig8
- tui.zig10
- tui/builder.zig40
- tui/color.zig5
- tui/context.zig18
- tui/control.zig1
- tui/frame.zig34
- tui/input.zig4
- tui/screen.zig19
- tui/widgets.zig35
- util.zig10
- util/bptree.zig1
- util/buf.zig1
- util/shm.zig9
- util/slotmap.zig1
- util/sparse.zig1
- vm.zig16
ai.zig
ai/agent.zig
ai/chat.zig
ai/client.zig
ai/embedding.zig
ai/fmt.zig
ai/models.zig
app.zig
cli.zig
Controls how command output is formatted (--json, --yaml, or auto-detect).
Runtime context for CLI commands. Most handlers won't need this directly since dependencies and arguments are injected into the handler function.
Parse a string value into the requested type.
Write a result to the output stream in the configured format.
A CLI command definition with name, description, and handler.
Create a command with explicit argument count. Dependencies are injected, remaining parameters are parsed from command-line arguments.
Create a command with no arguments (dependencies only).
Create a command with one argument.
Create a command with two arguments.
Create a command with three arguments.
Print usage information and available commands.
CLI entry point. Use with tk.app.run(tk.cli.run, &.{YourModule}).
config.zig
container.zig
Creates a new container from the given modules.
At comptime, this builds the dependency graph, resolves initialization order, and generates a specialized struct. At runtime, it allocates the container and initializes all dependencies in the computed order.
Destroy the container and all its dependencies (in reverse order).
Specifies how a dependency should be initialized.
Used with Bundle.provide(), Bundle.override(), and Bundle.mock() to
control dependency initialization.
This dependency should be initialized using the provided comptime value.
NOTE: If the dep type is a mutable ptr, then you can still pass a ref to a global var this way. Not recommended, but good to know.
Initialize the dependency using ptr.* = try inj.call(fun).
The function will be called at the proper time, but if you cause a cycle
you may still get a compile error.
Cycles should be avoided, but you can always define an empty initializer
for one of them, or use .value(undefined). The former is better
because you can still control the order by declaring the deps.
Initialize the dependency using try inj.callArgs(fun, .{ ptr, ...deps }).
Like with factory, if you get into a cycle, you can either adapt the
other end, or in the worst case, force undefined.
Compile-time dependency graph builder.
Registers all fields of module M as dependencies.
For each field:
- Fields with default values use
.value(default) - Fields without defaults use
.auto - Fields with an
interfacesub-field auto-register&T.interface
If there's a pub fn M.configure(*Bundle) defined, it will be called
(and it may recur). This is where you can define extra refs, register
init/deinit/compile hooks or even add more dependencies conditionally
and/or be more explicit about how it will be initialized.
Adds a single dependency with the specified initialization strategy.
Use this to add dependencies that are not module fields. The dependency
can still be overridden via override() or mocked via mock(), but any
other re-definition will result in a compile error.
Only allowed during a test run. Use this in your test module to override how some dependency should be initialized. This should not be part of your regular modules, and calling it outside of the test runner will result in a compile error.
Overrides how an existing dependency should be initialized. Works across
module boundaries (last one wins). Use this sparingly, as it can make
initialization order harder to follow. For post-initialization logic,
prefer addInitHook() instead.
Adds a reference to a struct field as a separate dependency. Use this if you need to inject ptr to some sub-part of your struct.
Registers a function to be called during comptime, when all the modules
are added and configured but before any dependency resolution. Can be
used for validation and post-processing, i.e., for walking the
[]const Route tree and checking if we have all the deps available.
Registers a function to be called during container initialization, as soon as all its deps are ready.
Registers a function to be called right before any of its deps are cleaned up. Executes in reverse order of init hooks.
Finds an existing dependency by type. Matches by base type (T.*).
context.zig
Function signature for route handlers.
Function signature for custom error handlers.
Request context for middleware and advanced handlers. Note that most route
handlers should inject dependencies directly (e.g., *tk.Request,
*tk.Response) instead.
Parse a string value into the requested type.
Reads the query parameters into a struct.
Reads the request body as JSON.
Returns the value of the given cookie or null if it doesn't exist.
Sets a cookie.
Send a response. Accepts strings, JSON-serializable values, errors, or
types with a custom sendResponse method (like EventStream).
Redirects the client to a different URL with an optional status code.
Continue to the next matching route. Used by middleware to pass control.
Continue with additional dependencies available for injection.
Wrapper type over already-initialized iterator, which will be cloned with meta.dupe() and then run in a newly created thread. Every next() result will be JSON stringified and sent as SSE event.
Options for Context.setCookie().
Map well-known errors to HTTP status codes. Returns 500 for unknown errors.
cron.zig
crypto.zig
dom.zig
dom/document.zig
dom/element.zig
dom/local_name.zig
dom/node.zig
dom/parser.zig
dom/text.zig
entities.zig
event.zig
ext.zig
ext/github.zig
ext/hackernews.zig
ext/reddit.zig
html2md.zig
Streaming HTML-to-Markdown formatter. Implements the DOM visitor and writes to the provided writer.
Handle element open
Handle element close
Handle text node
Write content but flush any pending white-space first
http.zig
http/client.zig
injector.zig
Type-erased reference to a dependency.
Creates a Ref from any pointer.
Injector serves as a custom runtime scope for retrieving dependencies. It can be passed around, enabling any code to request a value or reference to a given type. Additionally, it can invoke arbitrary functions and supply the necessary dependencies automatically.
Injectors can be nested. If a dependency is not found, the parent context is searched. If the dependency is still not found, an error is returned.
Looks up a dependency by type, returning null if not found.
Get a dependency from the context.
Call a function with all the args filled-in from this scope.
Call a function with dependencies. The extra_args tuple is used to
pass additional arguments to the function. A function with anytype can
be called as long as the concrete value is provided in the extra_args.
iter.zig
js.zig
main.zig
meta.zig
Ptr to a comptime value, wrapped together with its type. We use this to pass around values (including a concrete fun types!) during the Bundle compilation.
middleware/cors.zig
Adds CORS headers and handles preflight requests. Note that headers cannot be removed so this should always be wrapped in a group.
middleware/logger.zig
Returns a wrapper for logging all requests going through it.
middleware/static.zig
Serve static files from a directory. In debug mode, files are read from disk.
In release builds, files can be embedded if enabled via tk.setup() in build.zig.
Serve a single static file.
middleware/swagger.zig
Serve Swagger UI. Loads the UI from CDN and points it to the schema URL.
Generate OpenAPI 3.0 JSON schema from routes. Extracts path parameters, request bodies, and response types automatically.
mime.zig
Get the MIME type for a given file extension.
monitor.zig
Runs the given processes in parallel, restarting them if they exit.
The processes are tuples of the form: .{ "name", &fn, .{ ...args } }
Example: pub fn main() !void { // do some init checks and setup if needed
return monitor(.{
.{ "server", &serverFn, .{ 8080 } },
.{ "worker 1", &workerFn, .{ 1 } },
.{ "worker 2", &workerFn, .{ 2 } },
});
}
parse.zig
Parse a string value into the requested type. Supports: optional, bool, int, enum, string, and slices (comma-separated).
pdf.zig
queue.zig
A lightweight, crash-safe, at-most-once*, bounded job queue. Jobs can be scheduled in the future and if they have a key, it will be used for avoiding duplicates. There is no persistence guarantee but the queue will remain consistent even if any process dies (or is killed) at any point. It is implemented using POSIX shared memory for storage (macos/linux only) and file locking for synchronization. No broker, no database, no worker thread.
*: At-most-once applies at the API boundary. If a process is killed before
claim() returns, the item will be retrieved again by another caller,
because it was never handed over for processing.
NOTE: Atomic operations are INTENTIONAL for crash-resilience, not for lock-free access. The mutex serializes live processes, but if a process crashes mid-operation, atomics with release/acquire semantics ensure other processes see either a fully-written slot or FREE but NEVER partial state.
Initialize the queue in place. The caller must ensure self is at a
stable memory location that won't be moved after this call.
regex.zig
resource.zig
route.zig
Defines an HTTP route with method, path, handler, and optional children.
Use helper methods like get(), post(), group() to build routes.
Provides a dependency to the children routes by calling the given
factory. If there is a deinit method, it will be called at the end of
the scope.
Returns a route that sends the given, comptime response.
Returns a route that will redirect user somewhere else.
Groups the given routes under a common prefix. The prefix is removed from the request path before the children are called.
Creates a GET route with the given path and handler.
Creates a POST route with the given path and handler. The handler will receive the request body in the last argument.
Creates a POST route with the given path and handler but without a body.
Creates a PUT route with the given path and handler. The handler will receive the request body in the last argument.
Creates a PUT route with the given path and handler but without a body.
Creates a PATCH route with the given path and handler. The handler will receive the request body in the last argument.
Creates a PATCH route with the given path and handler but without a body.
Creates a DELETE route with the given path and handler.
Creates a group of routes from a struct type. Each pub fn will be equivalent to calling the corresponding route function with the method and path.
Path parameters extracted from a route match (e.g., :id segments).
Match a pattern against a path, extracting parameters. Returns null if no match.
sax.zig
A SAX event.
A simple SAX-style XML parser that can be used for both complete input and streaming. In the case of streaming, the returned strings are only valid until the next event.
The parser is forgiving and will attempt to parse as much as possible. It will ignore the XML header and the DOCTYPE, and it will not fail on invalid characters.
Notably, it does not perform entity decoding or unquoting of attributes. This is because many events are typically ignored, making such operations wasteful.
Create a parser for streaming input.
Create a parser for a complete input.
Returns next event or null if we reached the end of the input.
schema.zig
selector.zig
sendmail.zig
serde.zig
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
Serialize a value by calling writer.write(kind, value) for scalar values
and format-specific container factories for sequences, tuples, structs and maps.
Types can customize this in their T.serialize() hook.
The writer must implement:
write(kind: Kind, value: anytype) Error!voidfor scalar kindsbeginSeq(len: usize) Error!anytypefor slices and arraysbeginTuple(len: usize) Error!anytypefor tuple structsbeginStruct(comptime T: type, len: usize) Error!anytypefor structs and tagged unionsbeginMap(len: usize) Error!anytypefor map types (detected viaKVdecl)
Sequence / tuple containers must implement:
element(value: anytype) Error!voidend() Error!void
Struct containers must implement:
field(key: []const u8, value: anytype) Error!voidend() Error!void
Map containers must implement:
entry(key: anytype, value: anytype) Error!voidend() Error!void
serde/csv.zig
serde/json.zig
serde/table.zig
serde/yaml.zig
server.zig
Configuration for Server.init(). Most options are passed through to httpz.
Address and port to listen on.
A simple HTTP server with dependency injection.
Initialize a new server.
Deinitialize the server.
Start listening for incoming connections.
Stop the server.
ssr.zig
string.zig
A simple string type with SSO optimization. Strings up to 15 bytes are stored inline, longer strings are stored as a pointer+length pair.
Discrimination is done via the LSB of the first byte: short strings set it to 1, long strings leave it at 0. Both variants store the actual length shifted left by 1 bit, halving the maximum representable length.
A string that is guaranteed to fit within 2 words (max 15 bytes of data). Note that we always fully-init the struct so that we can reliably compare two short strings just by value.
testing.zig
Like std.testing.expectError() but with flipped args.
Like std.testing.expectEqual() but with flipped args and support for strings and optionals.
Attempts to print arg into a buf and then compare those strings.
Shorthand for MockClient.init() + &mock.interface
time.zig
Units for Time operations (includes time-of-day components).
Units for Date operations (calendar components only).
Returns true if the given year is a leap year in the Gregorian calendar.
Calendar date (year, month, day) without time-of-day or timezone. Uses Rata Die algorithm internally for efficient date arithmetic.
Create a date from year, month (1-12), and day (1-31).
Returns day of week (0 = Sunday, 1 = Monday, ..., 6 = Saturday).
UTC timestamp with second precision, stored as Unix epoch.
Provides fluent API for time manipulation: Time.now().setHour(10).add(.days, 1).
Create a Time from a Unix timestamp (seconds since 1970-01-01 00:00:00 UTC).
Get the current time.
tpl.zig
tui.zig
tui/builder.zig
tui/color.zig
True RGB color
Map to nearest 256-color index (6×6×6 cube or grayscale ramp)
tui/context.zig
Encode a percentage as a fixed-point value below -100_000
Claim the next cell and set up a new child container. NOTE that it is only valid until the next push() at the same depth overwrites it.
Set up a new child container with a specific frame without claiming a cell.
Like push(), but for N equal-sized columns.
Get resolved rect of the next cell without advancing the cursor.
Advance the cursor and return the next cell Frame.
tui/control.zig
tui/frame.zig
Create a border using custom parts (north-west, north, north-east, ...)
Return a copy of self with one field replaced.
True if the frame has zero or negative dimensions.
Frame width in columns.
Frame height in rows.
Sub-frame at relative (x, y) with given size, clamped to self.
Sub-frame at relative (x, y) with the same size.
Shift the frame origin by (x, y) without clamping.
Adjust all four sides; positive = shrink, negative = grow. sides = [top, right, bottom, left]
Narrow to width w, anchored to the left edge.
Narrow to width w, anchored to the right edge.
Narrow to height h, anchored to the top edge.
Narrow to height h, anchored to the bottom edge.
Narrow to width w, centered horizontally.
Narrow to height h, centered vertically.
Narrow to w×h, centered on both axes.
Draw a chunk once at (x, y).
Draw one frame of an animation, cycling by tick.
Draw text at the frame's origin, clipped to frame width. If the frame is taller than one row, renders multiple lines with wrapping at width and honoring '\n'.
Fill the entire frame background.
Fill the entire frame by repeating a chunk per cell (foreground only).
Draw a horizontal line of ─ characters.
Draw a vertical line of │ characters.
Draw a drop shadow (1-cell offset, bottom and right).
Fill the left v fraction of the frame (0.0..1.0).
Fill the bottom v fraction of the frame (0.0..1.0).
tui/input.zig
Poll for a key without blocking. Returns null if no key is available. timeout is in ms. NOTE: This is incomplete, but it's not worth fixing until Zig v0.18
tui/screen.zig
tui/widgets.zig
Render an empty spacer of the given height.
Pushes a single-column layout scope.
Pushes a multi-column grid layout scope.
Render a single line of text clipped to the next layout cell's width.
Alias to text(), at least for now
Render any numeric value (int or float) as text.
Render multiple lines of text, wrapping at width. Reserves the required height from layout (max_height = -1 means auto).
Draws an ASCII border around a stack() and returns the inner scope.
Render a titled separator: ─ Title ──────
Render a collapsible section. Toggles open on Enter/Space.
Render a horizontal separator line.
Render a centered button with a solid background. Returns true when clicked (Enter/Space).
Render a checkbox. Enter/space toggles the value.
Render an interactive number input.
Render an editable single-line text field.
Render an editable multi-line text field with wrapping.
Render a radio-style picker. Up/down moves selection.
Render an interactive slider. Left/right keys adjust the value by step.
Render an animated spinner character.
Render a progress bar as a background fill, value in 0.0..1.0
Render a full-screen overlay with z=100, always on top of other content.
Render short message in always on top overlay.
Render a centered modal overlay with border, shadow, and title.
Render text pinned to the bottom row of the screen, outside the layout.
Begin F1-F10 menu bar pinned to the bottom of the screen.
Render a tab bar. Left/right keys switch tabs.
Render a key-value pair: "label: value" with the label dimmed.
Render a tree view with indentation. depths gives the nesting level per item.
util.zig
util/bptree.zig
util/buf.zig
util/shm.zig
Cross-process mutex which works reliably on Linux/macOS even after crash. Also thread-safe within a single process via std.Thread.Mutex.
Opens or creates a shared memory segment. The size must be page-aligned.
Returns with created = true if this call created the segment (caller
should initialize it), or created = false if it already existed.
Unmaps and closes the shared memory segment.
NOTE: This does NOT unlink the segment - it persists in the system until
explicitly unlinked via Shm.unlink() or until system reboot. This is
intentional: it allows other processes to continue using the segment and
preserves data across process restarts.