API Reference

Auto-generated from source. 67 files, 607 public items.

ai.zig

pub const chat = @import("ai/chat.zig");
pub const embedding = @import("ai/embedding.zig");
pub const ClientConfig = client.Config;
pub const Client = client.Client;
pub const AgentOptions = agent.AgentOptions;
pub const Agent = agent.Agent;
pub const AgentRuntime = agent.AgentRuntime;
pub const AgentToolbox = agent.AgentToolbox;
pub const stringify = format.stringify;
pub const stringifyAlloc = format.stringifyAlloc;
pub const Formatter = format.Formatter;
pub const fmt = format.fmt;

ai/agent.zig

pub const AgentOptions = struct {
debug: bool = true, model: []const u8, tools: []const []const u8, max_tokens: u32 = 4096, temperature: ?f32 = null, top_p: ?f32 = null
}
pub const Agent = struct {
arena: std.mem.Allocator, runtime: *AgentRuntime, options: AgentOptions, messages: std.ArrayListUnmanaged(chat.Message) = .empty, result: ?[]const u8 = null
}
pub fn Agent.init(allocator: std.mem.Allocator, runtime: *AgentRuntime, options: AgentOptions) !Agent
pub fn Agent.deinit(self: *Agent) void
pub fn Agent.addMessage(self: *Agent, msg: chat.Message) !void
pub fn Agent.run(self: *Agent) ![]const u8
pub fn Agent.next(self: *Agent) !?[]const chat.ToolCall
pub fn Agent.finish(self: *Agent, result: []const u8) void
pub fn Agent.acceptAll(self: *Agent, tcs: []const chat.ToolCall) !void
pub fn Agent.accept(self: *Agent, tc: chat.ToolCall) !void
pub fn Agent.reject(self: *Agent, tc: chat.ToolCall) !void
pub fn Agent.respond(self: *Agent, tc: chat.ToolCall, res: anytype) !void
pub fn Agent.retry(self: *Agent) void
pub const AgentRuntime = struct {
event_bus: ?event.Bus = null, client: *Client, toolbox: *AgentToolbox
}
pub fn AgentRuntime.createAgent(self: *AgentRuntime, allocator: std.mem.Allocator, options: AgentOptions) !Agent
pub const AgentTool = struct {
tool: chat.Tool, handler: *const fn (inj: *Injector, arena: std.mem.Allocator, args: []const u8) anyerror![]const u8
}
pub const AgentToolbox = struct {
mutex: std.Thread.Mutex = .{}, allocator: std.mem.Allocator, injector: *Injector, tools: std.StringHashMapUnmanaged(AgentTool) = .empty
}
pub fn AgentToolbox.init(allocator: std.mem.Allocator, injector: *Injector) AgentToolbox
pub fn AgentToolbox.deinit(self: *AgentToolbox) void
pub fn AgentToolbox.addTool(self: *AgentToolbox, comptime name: []const u8, comptime description: []const u8, comptime handler: anytype) !void
pub fn AgentToolbox.removeTool(self: *AgentToolbox, name: []const u8) bool

ai/chat.zig

pub const TextOrContents = union(enum) {
text: []const u8, contents: []const Content
}
pub fn TextOrContents.jsonStringify(self: *const @This(), jw: anytype) !void
pub fn TextOrContents.jsonParse(allocator: std.mem.Allocator, source: anytype, options: std.json.ParseOptions) !@This()
pub const Request = struct {
model: []const u8, messages: []const Message, tools: []const Tool = &.{}, response_format: ?struct { type: []const u8, } = null, max_tokens: u32 = 256, temperature: ?f32 = null, top_p: ?f32 = null
}
pub const Role = enum {
system, user, assistant, tool
}
pub const Message = struct {
role: Role, content: ?TextOrContents = null, tool_calls: ?[]const ToolCall = null, tool_call_id: ?[]const u8 = null
}
pub fn Message.jsonStringify(self: Message, jws: anytype) !void
pub const ToolType = enum {
function
}
pub const Tool = struct {
type: ToolType = .function, function: struct { name: []const u8, description: ?[]const u8, parameters: schema.Schema, strict: bool = true, // structured output / grammar }
}
pub fn Tool.tool(name: []const u8, description: ?[]const u8, comptime Args: type) Tool
pub const ToolCall = struct {
id: []const u8, type: ToolType = .function, function: struct { name: []const u8, arguments: []const u8, // JSON }
}
pub const FinishReason = enum {
stop, length, function_call, tool_calls, content_filter
}
pub const Response = struct {
id: []const u8, object: []const u8, created: u64, model: []const u8, choices: []const Choice, usage: struct { prompt_tokens: u32, completion_tokens: u32, total_tokens: u32, }, system_fingerprint: ?[]const u8
}
pub fn Response.singleChoice(self: Response) ?Choice
pub const Choice = struct {
index: u32, message: Message, logprobs: ?struct {} = .{}, finish_reason: FinishReason
}
pub fn Choice.text(self: Choice) ?[]const u8
pub fn Choice.toolCalls(self: Choice) ?[]const ToolCall

ai/client.zig

pub const Config = struct {
base_url: []const u8 = "https://api.openai.com/v1/", api_key: ?[]const u8 = null, timeout: ?usize = 2 * 60
}
pub const Client = struct {
http_client: *http.Client, config: Config
}
pub fn Client.createChatCompletion(self: *Client, arena: std.mem.Allocator, params: chat.Request) !chat.Response
pub fn Client.createEmbeddings(self: *Client, arena: std.mem.Allocator, params: embedding.Request) !embedding.Response

ai/embedding.zig

pub const Request = struct {
model: []const u8, input: []const u8
}
pub const Response = struct {
object: []const u8, model: []const u8, data: []const Embedding, usage: struct { prompt_tokens: u32, total_tokens: u32, }
}
pub const Embedding = struct {
index: u32, object: []const u8, embedding: []const f32
}

ai/fmt.zig

pub fn stringify(value: anytype, writer: anytype) !void
pub fn stringifyAlloc(arena: std.mem.Allocator, value: anytype) ![]const u8
pub fn fmt(value: anytype) Formatter(@TypeOf(value))
pub fn Formatter(comptime T: type) type

ansi.zig

pub const bel = "\x07";
pub const bs = "\x08";
pub const ht = "\x09";
pub const vt = "\x0A";
pub const lf = "\x0B";
pub const ff = "\x0C";
pub const cr = "\x0D";
pub const esc = "\x1B";
pub const csi = esc ++ "[";
pub const cp = csi ++ "H";
pub const ed = csi ++ "J";
pub const ed1 = csi ++ "1J";
pub const ed2 = csi ++ "2J";
pub const ed3 = csi ++ "3J";
pub const clear = ed2 ++ ed3 ++ cp;

app.zig

pub const Base = struct {
}
pub fn Base.configure(bundle: *Bundle) void
pub fn run(comptime fun: anytype, comptime mods: []const type) !void
pub fn runAlloc(comptime fun: anytype, allocator: std.mem.Allocator, comptime mods: []const type) !void

cli.zig

pub const OutputFormat = enum {
auto, yaml, json
}

Controls how command output is formatted (--json, --yaml, or auto-detect).

pub const Context = struct {
arena: std.mem.Allocator, bin: []const u8, command: *const Command, args: []const []const u8, in: *std.io.Reader, out: *std.io.Writer, err: *std.io.Writer, injector: *Injector, format: OutputFormat = .auto
}

Runtime context for CLI commands. Most handlers won't need this directly since dependencies and arguments are injected into the handler function.

pub fn Context.parse(self: *Context, comptime T: type, s: []const u8) !T

Parse a string value into the requested type.

pub fn Context.output(self: *Context, res: anytype) !void

Write a result to the output stream in the configured format.

pub const Command = struct {
name: []const u8, description: []const u8, handler: *const fn (*Context) anyerror!void, tids: []const meta.TypeId
}

A CLI command definition with name, description, and handler.

pub fn Command.cmd(comptime name: []const u8, comptime description: []const u8, comptime fun: anytype, comptime n_args: usize) Command

Create a command with explicit argument count. Dependencies are injected, remaining parameters are parsed from command-line arguments.

pub fn Command.cmd0(comptime name: []const u8, comptime description: []const u8, comptime fun: anytype) Command

Create a command with no arguments (dependencies only).

pub fn Command.cmd1(comptime name: []const u8, comptime description: []const u8, comptime fun: anytype) Command

Create a command with one argument.

pub fn Command.cmd2(comptime name: []const u8, comptime description: []const u8, comptime fun: anytype) Command

Create a command with two arguments.

pub fn Command.cmd3(comptime name: []const u8, comptime description: []const u8, comptime fun: anytype) Command

Create a command with three arguments.

pub fn printUsage(ctx: *Context, cmds: []const Command) !void

Print usage information and available commands.

pub fn run(inj: *Injector, allocator: std.mem.Allocator, cmds: []const Command) !void

CLI entry point. Use with tk.app.run(tk.cli.run, &.{YourModule}).

config.zig

pub fn read(comptime T: type, allocator: std.mem.Allocator, options: ReadOptions) !std.json.Parsed(T)
pub fn write(comptime T: type, config: T, options: WriteOptions) !void

container.zig

pub const Container = struct {
allocator: std.mem.Allocator, injector: Injector, bundle: *anyopaque, deinit_fn: *const fn (*Container) void
}
pub fn Container.init(allocator: std.mem.Allocator, comptime mods: []const type) !*Container

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.

pub fn Container.deinit(self: *Container) void

Destroy the container and all its dependencies (in reverse order).

pub const How = union(enum) {
auto, init, autowire, val: meta.ComptimeVal, fac: meta.ComptimeVal, fun: meta.ComptimeVal, fref: struct { type, []const u8 }
}

Specifies how a dependency should be initialized.

Used with Bundle.provide(), Bundle.override(), and Bundle.mock() to control dependency initialization.

pub fn How.value(val: anytype) How

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.

pub fn How.factory(fac: anytype) How

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.

pub fn How.initializer(init: anytype) How

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.

pub const Bundle = struct {
deps: Buf(Dep), compile_hooks: Buf(meta.ComptimeVal), runtime_hooks: Buf(Hook), n_inst: usize = 0, n_data: usize = 0
}

Compile-time dependency graph builder.

pub fn Bundle.addModule(self: *Bundle, comptime M: type) void

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 interface sub-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.

pub fn Bundle.provide(self: *Bundle, comptime T: type, how: How) void

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.

pub fn Bundle.mock(self: *Bundle, comptime T: type, how: How) void

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.

pub fn Bundle.override(self: *Bundle, comptime T: type, how: How) void

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.

pub fn Bundle.expose(self: *Bundle, comptime T: type, comptime field: []const u8) void

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.

pub fn Bundle.addCompileHook(self: *Bundle, comptime fun: anytype) void

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.

pub fn Bundle.addInitHook(self: *Bundle, comptime fun: anytype) void

Registers a function to be called during container initialization, as soon as all its deps are ready.

pub fn Bundle.addDeinitHook(self: *Bundle, comptime fun: anytype) void

Registers a function to be called right before any of its deps are cleaned up. Executes in reverse order of init hooks.

pub fn Bundle.findDep(self: *Bundle, comptime T: type) ?*Dep

Finds an existing dependency by type. Matches by base type (T.*).

context.zig

pub const Handler = fn (*Context) anyerror!void;

Function signature for route handlers.

pub const ErrorHandler = fn (*Context, err: anyerror) anyerror!void;

Function signature for custom error handlers.

pub const Context = struct {
server: *Server, allocator: std.mem.Allocator, req: *httpz.Request, res: *httpz.Response, current: Route, params: Params, injector: *Injector, responded: bool = false, error_handler: ?*const ErrorHandler = null
}

Request context for middleware and advanced handlers. Note that most route handlers should inject dependencies directly (e.g., *tk.Request, *tk.Response) instead.

pub fn Context.parse(self: *Context, comptime T: type, s: []const u8) !T

Parse a string value into the requested type.

pub fn Context.readQuery(self: *Context, comptime T: type) !T

Reads the query parameters into a struct.

pub fn Context.readJson(self: *Context, comptime T: type) !T

Reads the request body as JSON.

pub fn Context.getCookie(self: *Context, name: []const u8) ?[]const u8

Returns the value of the given cookie or null if it doesn't exist.

pub fn Context.setCookie(self: *Context, name: []const u8, value: []const u8, options: CookieOptions) !void

Sets a cookie.

pub fn Context.send(self: *Context, res: anytype) !void

Send a response. Accepts strings, JSON-serializable values, errors, or types with a custom sendResponse method (like EventStream).

pub fn Context.redirect(self: *Context, url: []const u8, options: struct { status: u16 = 302 }) !void

Redirects the client to a different URL with an optional status code.

pub fn Context.next(self: *Context) !void

Continue to the next matching route. Used by middleware to pass control.

pub fn Context.nextScoped(self: *Context, ctx: anytype) !void

Continue with additional dependencies available for injection.

pub fn EventStream(comptime T: type) type

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.

pub const CookieOptions = struct {
domain: ?[]const u8 = null, max_age: ?u32 = null, http_only: bool = false, secure: bool = false
}

Options for Context.setCookie().

pub fn getErrorStatus(e: anyerror) u16

Map well-known errors to HTTP status codes. Returns 500 for unknown errors.

cron.zig

pub const Config = struct {
catchup_window: i64 = 30
}
pub const Job = struct {
id: JobId, schedule: Expr, name: []const u8, data: []const u8, next: Time
}
pub const Cron = struct {
config: Config, queue: *Queue, allocator: std.mem.Allocator, jobs: std.ArrayList(Job), time: *const fn () Time = Time.now, mutex: std.Thread.Mutex = .{}, wait: std.Thread.Condition = .{}
}
pub fn Cron.init(allocator: std.mem.Allocator, queue: *Queue, config: Config) Cron
pub fn Cron.deinit(self: *Cron) void
pub fn Cron.schedule(self: *Cron, expr: []const u8, name: []const u8, data: []const u8) !JobId
pub fn Cron.unschedule(self: *Cron, id: JobId) void
pub fn Cron.run(self: *Cron) !void
pub fn Cron.tick(self: *Cron, now: Time) !Time
pub const Expr = struct {
minute: u60, hour: u24, day: u32, month: u13, weekday: u7
}
pub fn Expr.match(self: *const Expr, step: Time) bool
pub fn Expr.next(self: *const Expr, since: Time) Time
pub fn Expr.parse(expr: []const u8) !Expr

crypto.zig

pub fn sha1(key: anytype) [40]u8

csv.zig

pub fn Response(comptime T: type) type
pub const Writer = struct {
inner: *std.io.Writer, options: WriterOptions, row: usize = 0, col: usize = 0
}
pub fn Writer.init(inner: *std.io.Writer, options: WriterOptions) Writer
pub fn Writer.writeAll(self: *Writer, comptime T: type, items: []const T) !void
pub fn Writer.writeHeader(self: *Writer, comptime T: type) !void
pub fn Writer.writeRow(self: *Writer, row: anytype) !void
pub fn Writer.finish(self: *Writer) !void

dom.zig

pub const Document = @import("dom/document.zig").Document;
pub const Element = @import("dom/element.zig").Element;
pub const Node = @import("dom/node.zig").Node;
pub const LocalName = @import("dom/local_name.zig").LocalName;
pub const Text = @import("dom/text.zig").Text;

dom/document.zig

pub const Document = struct {
node: Node, arena: std.mem.Allocator
}
pub fn Document.init(allocator: std.mem.Allocator) !*Document
pub fn Document.deinit(self: *Document) void
pub fn Document.arenaSize(self: *Document) usize
pub fn Document.parseFromSlice(allocator: std.mem.Allocator, input: []const u8) !*Document
pub fn Document.parseFromStream(allocator: std.mem.Allocator, reader: *std.io.Reader) !*Document
pub fn Document.createElement(self: *Document, local_name: []const u8) !*Element
pub fn Document.createTextNode(self: *Document, data: []const u8) !*Text
pub fn Document.querySelector(self: *Document, selector: []const u8) !?*Element
pub fn Document.querySelectorAll(self: *Document, selector: []const u8) !QuerySelectorIterator(*Element)
pub fn Document.documentElement(self: *Document) ?*Element

dom/element.zig

pub const Attr = struct {
next: ?*Attr = null, name: LocalName, value: util.Smol128
}
pub const Element = struct {
node: Node, local_name: LocalName, attributes: ?*Attr = null
}
pub fn Element.init(self: *Element, document: *Document, local_name: []const u8) !void
pub fn Element.parentElement(self: *Element) ?*Element
pub fn Element.firstElementChild(self: *Element) ?*Element
pub fn Element.previousElementSibling(self: *Element) ?*Element
pub fn Element.nextElementSibling(self: *Element) ?*Element
pub fn Element.localName(self: *Element) []const u8
pub fn Element.id(self: *Element) []const u8
pub fn Element.className(self: *Element) []const u8
pub fn Element.getAttribute(self: *Element, name: []const u8) ?[]const u8
pub fn Element.setAttribute(self: *Element, name: []const u8, value: []const u8) !void

dom/local_name.zig

pub const LocalName = enum(u128) {
_
}
pub fn LocalName.parse(local_name: []const u8) LocalName
pub fn LocalName.name(self: *const LocalName) []const u8
pub fn LocalName.isVoid(self: LocalName) bool
pub fn LocalName.isRaw(self: LocalName) bool

dom/node.zig

pub const Node = struct {
kind: enum { element, text, document }, document: *Document, parent_node: ?*Node = null, first_child: ?*Node = null, last_child: ?*Node = null, previous_sibling: ?*Node = null, next_sibling: ?*Node = null
}
pub fn Node.element(self: *Node) ?*Element
pub fn Node.text(self: *Node) ?*Text
pub fn Node.appendChild(self: *Node, child: *Node) void
pub fn Node.insertBefore(self: *Node, child: *Node, before: *Node) void
pub fn Node.removeChild(self: *Node, child: *Node) void
pub fn Node.depth(self: *Node) usize
pub fn Node.visit(self: *Node, visitor: anytype) !void
pub fn Node.dump(self: *Node) void

dom/parser.zig

pub const HtmlParser = struct {
sax: sax.Parser
}
pub fn HtmlParser.initCompleteInput(input: []const u8) HtmlParser
pub fn HtmlParser.initStreaming(reader: *std.io.Reader) HtmlParser
pub fn HtmlParser.parseDocument(self: *HtmlParser, allocator: std.mem.Allocator) !*Document
pub fn HtmlParser.parseInto(self: *HtmlParser, root: *Node) !void

dom/text.zig

pub const Text = struct {
node: Node, data: util.Smol128
}
pub fn Text.init(self: *Text, document: *Document, data: []const u8) !void

entities.zig

pub fn Decoder(comptime entities: anytype) type
pub fn decode(allocator: std.mem.Allocator, input: []const u8, comptime entities: anytype) ![]const u8
pub fn decodeInplace(buf: []u8, comptime entities: anytype) []u8
pub const xml = .{ .{ "&amp", "&" }, .{ "&lt", "<" }, .{ "&gt", ">" }, .{ "&quot", "\"" }, .{ "&apos", "'" }, };
pub const html4 = xml ++ .{ .{ "&apos", "'" }, .{ "&nbsp", " " }, .{ "&iexcl", "¡" }, .{ "&cent", "¢" }, .{ "&pound", "£" }, .{ "&curren", "¤" }, .{ "&yen", "¥" }, .{ "&brvbar", "¦" }, .{ "&sect", "§" }, .{ "&uml", "¨" }, .{ "&copy", "©" }, .{ "&ordf", "ª" }, .{ "&laquo", "«" }, .{ "&not", "¬" }, .{ "&shy", "­" }, .{ "&reg", "®" }, .{ "&macr", "¯" }, .{ "&deg", "°" }, .{ "&plusmn", "±" }, .{ "&sup2", "²" }, .{ "&sup3", "³" }, .{ "&acute", "´" }, .{ "&micro", "µ" }, .{ "&para", "¶" }, .{ "&middot", "·" }, .{ "&cedil", "¸" }, .{ "&sup1", "¹" }, .{ "&ordm", "º" }, .{ "&raquo", "»" }, .{ "&frac14", "¼" }, .{ "&frac12", "½" }, .{ "&frac34", "¾" }, .{ "&iquest", "¿" }, .{ "&Agrave", "À" }, .{ "&Aacute", "Á" }, .{ "&Acirc", "Â" }, .{ "&Atilde", "Ã" }, .{ "&Auml", "Ä" }, .{ "&Aring", "Å" }, .{ "&AElig", "Æ" }, .{ "&Ccedil", "Ç" }, .{ "&Egrave", "È" }, .{ "&Eacute", "É" }, .{ "&Ecirc", "Ê" }, .{ "&Euml", "Ë" }, .{ "&Igrave", "Ì" }, .{ "&Iacute", "Í" }, .{ "&Icirc", "Î" }, .{ "&Iuml", "Ï" }, .{ "&ETH", "Ð" }, .{ "&Ntilde", "Ñ" }, .{ "&Ograve", "Ò" }, .{ "&Oacute", "Ó" }, .{ "&Ocirc", "Ô" }, .{ "&Otilde", "Õ" }, .{ "&Ouml", "Ö" }, .{ "&times", "×" }, .{ "&Oslash", "Ø" }, .{ "&Ugrave", "Ù" }, .{ "&Uacute", "Ú" }, .{ "&Ucirc", "Û" }, .{ "&Uuml", "Ü" }, .{ "&Yacute", "Ý" }, .{ "&THORN", "Þ" }, .{ "&szlig", "ß" }, .{ "&agrave", "à" }, .{ "&aacute", "á" }, .{ "&acirc", "â" }, .{ "&atilde", "ã" }, .{ "&auml", "ä" }, .{ "&aring", "å" }, .{ "&aelig", "æ" }, .{ "&ccedil", "ç" }, .{ "&egrave", "è" }, .{ "&eacute", "é" }, .{ "&ecirc", "ê" }, .{ "&euml", "ë" }, .{ "&igrave", "ì" }, .{ "&iacute", "í" }, .{ "&icirc", "î" }, .{ "&iuml", "ï" }, .{ "&eth", "ð" }, .{ "&ntilde", "ñ" }, .{ "&ograve", "ò" }, .{ "&oacute", "ó" }, .{ "&ocirc", "ô" }, .{ "&otilde", "õ" }, .{ "&ouml", "ö" }, .{ "&divide", "÷" }, .{ "&oslash", "ø" }, .{ "&ugrave", "ù" }, .{ "&uacute", "ú" }, .{ "&ucirc", "û" }, .{ "&uuml", "ü" }, .{ "&yacute", "ý" }, .{ "&thorn", "þ" }, .{ "&yuml", "ÿ" }, .{ "&quot", "\"" }, .{ "&amp", "&" }, .{ "&lt", "<" }, .{ "&gt", ">" }, .{ "&OElig", "Œ" }, .{ "&oelig", "œ" }, .{ "&Scaron", "Š" }, .{ "&scaron", "š" }, .{ "&Yuml", "Ÿ" }, .{ "&circ", "ˆ" }, .{ "&tilde", "˜" }, .{ "&ensp", " " }, .{ "&emsp", " " }, .{ "&thinsp", " " }, .{ "&zwnj", "‌" }, .{ "&zwj", "‍" }, .{ "&lrm", "‎" }, .{ "&rlm", "‏" }, .{ "&ndash", "–" }, .{ "&mdash", "—" }, .{ "&lsquo", "‘" }, .{ "&rsquo", "’" }, .{ "&sbquo", "‚" }, .{ "&ldquo", "“" }, .{ "&rdquo", "”" }, .{ "&bdquo", "„" }, .{ "&dagger", "†" }, .{ "&Dagger", "‡" }, .{ "&permil", "‰" }, .{ "&lsaquo", "‹" }, .{ "&rsaquo", "›" }, .{ "&euro", "€" }, .{ "&fnof", "ƒ" }, .{ "&Alpha", "Α" }, .{ "&Beta", "Β" }, .{ "&Gamma", "Γ" }, .{ "&Delta", "Δ" }, .{ "&Epsilon", "Ε" }, .{ "&Zeta", "Ζ" }, .{ "&Eta", "Η" }, .{ "&Theta", "Θ" }, .{ "&Iota", "Ι" }, .{ "&Kappa", "Κ" }, .{ "&Lambda", "Λ" }, .{ "&Mu", "Μ" }, .{ "&Nu", "Ν" }, .{ "&Xi", "Ξ" }, .{ "&Omicron", "Ο" }, .{ "&Pi", "Π" }, .{ "&Rho", "Ρ" }, .{ "&Sigma", "Σ" }, .{ "&Tau", "Τ" }, .{ "&Upsilon", "Υ" }, .{ "&Phi", "Φ" }, .{ "&Chi", "Χ" }, .{ "&Psi", "Ψ" }, .{ "&Omega", "Ω" }, .{ "&alpha", "α" }, .{ "&beta", "β" }, .{ "&gamma", "γ" }, .{ "&delta", "δ" }, .{ "&epsilon", "ε" }, .{ "&zeta", "ζ" }, .{ "&eta", "η" }, .{ "&theta", "θ" }, .{ "&iota", "ι" }, .{ "&kappa", "κ" }, .{ "&lambda", "λ" }, .{ "&mu", "μ" }, .{ "&nu", "ν" }, .{ "&xi", "ξ" }, .{ "&omicron", "ο" }, .{ "&pi", "π" }, .{ "&rho", "ρ" }, .{ "&sigmaf", "ς" }, .{ "&sigma", "σ" }, .{ "&tau", "τ" }, .{ "&upsilon", "υ" }, .{ "&phi", "φ" }, .{ "&chi", "χ" }, .{ "&psi", "ψ" }, .{ "&omega", "ω" }, .{ "&thetasym", "ϑ" }, .{ "&upsih", "ϒ" }, .{ "&piv", "ϖ" }, .{ "&bull", "•" }, .{ "&hellip", "…" }, .{ "&prime", "′" }, .{ "&Prime", "″" }, .{ "&oline", "‾" }, .{ "&frasl", "⁄" }, .{ "&weierp", "℘" }, .{ "&image", "ℑ" }, .{ "&real", "ℜ" }, .{ "&trade", "™" }, .{ "&alefsym", "ℵ" }, .{ "&larr", "←" }, .{ "&uarr", "↑" }, .{ "&rarr", "→" }, .{ "&darr", "↓" }, .{ "&harr", "↔" }, .{ "&crarr", "↵" }, .{ "&lArr", "⇐" }, .{ "&uArr", "⇑" }, .{ "&rArr", "⇒" }, .{ "&dArr", "⇓" }, .{ "&hArr", "⇔" }, .{ "&forall", "∀" }, .{ "&part", "∂" }, .{ "&exist", "∃" }, .{ "&empty", "∅" }, .{ "&nabla", "∇" }, .{ "&isin", "∈" }, .{ "&notin", "∉" }, .{ "&ni", "∋" }, .{ "&prod", "∏" }, .{ "&sum", "∑" }, .{ "&minus", "−" }, .{ "&lowast", "∗" }, .{ "&radic", "√" }, .{ "&prop", "∝" }, .{ "&infin", "∞" }, .{ "&ang", "∠" }, .{ "&and", "∧" }, .{ "&or", "∨" }, .{ "&cap", "∩" }, .{ "&cup", "∪" }, .{ "&int", "∫" }, .{ "&there4", "∴" }, .{ "&sim", "∼" }, .{ "&cong", "≅" }, .{ "&asymp", "≈" }, .{ "&ne", "≠" }, .{ "&equiv", "≡" }, .{ "&le", "≤" }, .{ "&ge", "≥" }, .{ "&sub", "⊂" }, .{ "&sup", "⊃" }, .{ "&nsub", "⊄" }, .{ "&sube", "⊆" }, .{ "&supe", "⊇" }, .{ "&oplus", "⊕" }, .{ "&otimes", "⊗" }, .{ "&perp", "⊥" }, .{ "&sdot", "⋅" }, .{ "&lceil", "⌈" }, .{ "&rceil", "⌉" }, .{ "&lfloor", "⌊" }, .{ "&rfloor", "⌋" }, .{ "&lang", "〈" }, .{ "&rang", "〉" }, .{ "&loz", "◊" }, .{ "&spades", "♠" }, .{ "&clubs", "♣" }, .{ "&hearts", "♥" }, .{ "&diams", "♦" }, };

event.zig

pub const Bus = struct {
mutex: std.Thread.Mutex.Recursive = .init, injector: *Injector, pool: std.heap.MemoryPool(Node), head: ?*Node = null, tail: ?*Node = null, dispatching: usize = 0, needs_cleanup: bool = false
}
pub fn Bus.init(allocator: std.mem.Allocator, injector: *Injector) Bus
pub fn Bus.deinit(self: *Bus) void
pub fn Bus.addListener(self: *Bus, comptime E: type, comptime listener: anytype) !ListenerId
pub fn Bus.removeListener(self: *Bus, id: ListenerId) void
pub fn Bus.dispatch(self: *Bus, event: anytype) !void

ext.zig

pub const github = @import("ext/github.zig");
pub const hackernews = @import("ext/hackernews.zig");
pub const reddit = @import("ext/reddit.zig");

ext/github.zig

pub const Config = struct {
base_url: []const u8 = "https://api.github.com/", api_key: ?[]const u8 = null, timeout: ?usize = 2 * 60
}
pub const Issue = struct {
url: []const u8, id: u64, number: u64, title: []const u8, state: []const u8, body: ?[]const u8
}
pub const Repository = struct {
id: u64, name: []const u8, description: ?[]const u8, url: []const u8
}
pub const Client = struct {
http_client: *http.Client, config: Config = .{}
}
pub fn Client.listRepoIssues(self: *Client, arena: std.mem.Allocator, owner: []const u8, repo: []const u8) ![]const Issue
pub fn Client.listRepos(self: *Client, arena: std.mem.Allocator, owner: []const u8) ![]const Repository

ext/hackernews.zig

pub const Config = struct {
base_url: []const u8 = "https://hacker-news.firebaseio.com/v0/", timeout: ?usize = 2 * 60
}
pub const Story = struct {
id: u64, parent: ?u64 = null, type: []const u8, by: []const u8, title: ?[]const u8 = null, url: ?[]const u8 = null, text: ?[]const u8 = null, kids: ?[]const u64 = null, descendants: u64 = 0, time: u64 = 0
}
pub const Client = struct {
http_client: *http.Client, config: Config = .{}
}
pub fn Client.getTopStories(self: *Client, arena: std.mem.Allocator, limit: u9) ![]const Story
pub fn Client.getNewStories(self: *Client, arena: std.mem.Allocator, limit: u9) ![]const Story
pub fn Client.getBestStories(self: *Client, arena: std.mem.Allocator, limit: u9) ![]const Story

ext/reddit.zig

pub const Config = struct {
base_url: []const u8 = "https://www.reddit.com/", timeout: ?usize = 2 * 60
}
pub const Post = struct {
id: []const u8, title: []const u8, author: []const u8, subreddit: []const u8, score: i64 = 0, num_comments: u64 = 0, created_utc: f64 = 0, is_self: bool = false
}
pub const RedditResponse = struct {
data: struct { children: []struct { data: Post, }, }
}
pub const Client = struct {
http_client: *http.Client, config: Config = .{}
}
pub fn Client.getHotPosts(self: *Client, arena: std.mem.Allocator, sub: []const u8, limit: u32) ![]const Post
pub fn Client.getNewPosts(self: *Client, arena: std.mem.Allocator, sub: []const u8, limit: u32) ![]const Post
pub fn Client.getTopPosts(self: *Client, arena: std.mem.Allocator, sub: []const u8, limit: u32) ![]const Post

html2md.zig

pub const Options = struct {
em_delim: []const u8 = "*", strong_delim: []const u8 = "**"
}
pub fn html2md(allocator: std.mem.Allocator, node: *dom.Node, options: Options) ![]const u8
pub const Html2Md = struct {
options: Options, out: *std.io.Writer, in_line: u32 = 0, empty: bool = true, pending: union(enum) { nop, sp, br: u2 } = .nop
}
pub fn Html2Md.init(out: *std.io.Writer, options: Options) !Html2Md
pub fn Html2Md.renderNode(self: *Html2Md, node: *dom.Node) !void
pub fn Html2Md.open(self: *Html2Md, element: *dom.Element) !void
pub fn Html2Md.close(self: *Html2Md, element: *dom.Element) !void
pub fn Html2Md.text(self: *Html2Md, tn: *dom.Text) !void
pub fn Html2Md.push(self: *Html2Md, chunk: []const u8) !void

http.zig

pub const Client = client.Client;
pub const StdClient = client.StdClient;
pub const ClientResponse = client.Response;
pub const RequestOptions = client.RequestOptions;
pub const RequestBody = client.RequestBody;

http/client.zig

pub const RequestOptions = struct {
base_url: ?[]const u8 = null, method: std.http.Method = .GET, url: []const u8 = "", headers: []const std.http.Header = &.{}, body: ?RequestBody = null, max_len: usize = 1024 * 1024, timeout: ?usize = 60
}
pub const RequestBody = struct {
ctx: *const anyopaque, content_type: []const u8, render: *const fn (ctx: *const anyopaque, writer: *std.io.Writer) anyerror!void
}
pub fn RequestBody.write(self: RequestBody, writer: *std.io.Writer) !void
pub fn RequestBody.json(ptr: anytype) RequestBody
pub const Response = struct {
arena: std.mem.Allocator, status: std.http.Status, headers: std.StringHashMapUnmanaged([]const u8), body: []const u8
}
pub fn Response.json(self: Response, comptime T: type) !T
pub const Client = struct {
make_request: *const fn (*Client, std.mem.Allocator, RequestOptions) Error!Response
}
pub fn Client.request(self: *Client, arena: std.mem.Allocator, options: RequestOptions) !Response
pub fn Client.get(self: *Client, arena: std.mem.Allocator, url: []const u8) !Response
pub fn Client.post(self: *Client, arena: std.mem.Allocator, url: []const u8, body: ?RequestBody) !Response
pub fn Client.resolveUrl(buf: *[]u8, url: []const u8, base: ?[]const u8) !std.Uri
pub const StdClient = struct {
std_client: std.http.Client, interface: Client = .{ .make_request = &make_request, }
}
pub fn StdClient.init(allocator: std.mem.Allocator) !@This()
pub fn StdClient.deinit(self: *StdClient) void

injector.zig

pub const Ref = struct {
tid: meta.TypeId, ptr: *anyopaque, is_const: bool
}

Type-erased reference to a dependency.

pub fn Ref.ref(ptr: anytype) Ref

Creates a Ref from any pointer.

pub const Injector = struct {
refs: []const Ref = &.{}, parent: ?*Injector = null
}

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.

pub fn Injector.init(refs: []const Ref, parent: ?*Injector) Injector
pub fn Injector.find(self: *Injector, comptime T: type) ?T

Looks up a dependency by type, returning null if not found.

pub fn Injector.get(self: *Injector, comptime T: type) !T

Get a dependency from the context.

pub fn Injector.call(self: *Injector, comptime fun: anytype) anyerror!meta.Result(fun)

Call a function with all the args filled-in from this scope.

pub fn Injector.callArgs(self: *Injector, comptime fun: anytype, extra_args: anytype) anyerror!meta.Result(fun)

Call a function with dependencies. The extra_args tuple is used to pass additional arguments to the function. Function with anytype can be called as long as the concrete value is provided in the extra_args.

js.zig

pub const Context = struct {
vm: vm.Context
}
pub fn Context.init(arena: std.mem.Allocator) !Context
pub fn Context.parent(self: *Context) ?*Context
pub fn Context.eval(self: *Context, expr: []const u8) !Value
pub fn Context.print(self: *Context, writer: *std.io.Writer, val: Value) !void

main.zig

pub const ai = @import("ai.zig");
pub const ansi = @import("ansi.zig");
pub const app = @import("app.zig");
pub const cli = @import("cli.zig");
pub const config = @import("config.zig");
pub const cron = @import("cron.zig");
pub const crypto = @import("crypto.zig");
pub const csv = @import("csv.zig");
pub const dom = @import("dom.zig");
pub const entities = @import("entities.zig");
pub const event = @import("event.zig");
pub const ext = @import("ext.zig");
pub const html2md = @import("html2md.zig");
pub const http = @import("http.zig");
pub const js = @import("js.zig");
pub const meta = @import("meta.zig");
pub const monitor = @import("monitor.zig").monitor;
pub const pdf = @import("pdf.zig");
pub const queue = @import("queue.zig");
pub const regex = @import("regex.zig");
pub const resource = @import("resource.zig");
pub const sax = @import("sax.zig");
pub const selector = @import("selector.zig");
pub const sendmail = @import("sendmail.zig");
pub const ssr = @import("ssr.zig");
pub const testing = @import("testing.zig");
pub const time = @import("time.zig");
pub const tpl = @import("tpl.zig");
pub const tui = @import("tui.zig");
pub const util = @import("util.zig");
pub const vm = @import("vm.zig");
pub const yaml = @import("yaml.zig");
pub const Injector = @import("injector.zig").Injector;
pub const Container = @import("container.zig").Container;
pub const Bundle = @import("container.zig").Bundle;
pub const Server = @import("server.zig").Server;
pub const ServerOptions = @import("server.zig").InitOptions;
pub const ListenOptions = @import("server.zig").ListenOptions;
pub const Route = @import("route.zig").Route;
pub const Context = @import("context.zig").Context;
pub const Handler = @import("context.zig").Handler;
pub const ErrorHandler = @import("context.zig").ErrorHandler;
pub const EventStream = @import("context.zig").EventStream;
pub const Schema = @import("schema.zig").Schema;
pub const Request = httpz.Request;
pub const Response = httpz.Response;
pub const cors = @import("middleware/cors.zig").cors;
pub const logger = @import("middleware/logger.zig").logger;
pub const static = @import("middleware/static.zig");
pub const swagger = @import("middleware/swagger.zig");
pub const send = Route.send;
pub const redirect = Route.redirect;

meta.zig

pub const TypeId = *const struct { name: [*:0]const u8, pub fn sname(self: *const @This()) []const u8 { // NOTE: we can't switch (invalid record Zig 0.14.1) if (self == tid([]const u8)) return "str"; if (self == tid(?[]const u8)) return "?str"; return shortName(std.mem.span(self.name), '.'); } };
pub fn tid(comptime T: type) TypeId
pub fn tids(comptime types: []const type) []const TypeId
pub const ComptimeVal = struct {
type: type, ptr: *const anyopaque
}

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.

pub fn ComptimeVal.wrap(comptime val: anytype) ComptimeVal
pub fn ComptimeVal.unwrap(self: ComptimeVal) self.type
pub fn dupe(allocator: std.mem.Allocator, value: anytype) !@TypeOf(value)
pub fn free(allocator: std.mem.Allocator, value: anytype) void
pub fn upcast(context: anytype, comptime T: type) T
pub fn Return(comptime fun: anytype) type
pub fn Result(comptime fun: anytype) type
pub fn LastArg(comptime fun: anytype) type
pub fn isStruct(comptime T: type) bool
pub fn isTuple(comptime T: type) bool
pub fn isGeneric(comptime fun: anytype) bool
pub fn isOptional(comptime T: type) bool
pub fn isOnePtr(comptime T: type) bool
pub fn isSlice(comptime T: type) bool
pub fn isString(comptime T: type) bool
pub fn Deref(comptime T: type) type
pub fn Unwrap(comptime T: type) type
pub fn Const(comptime T: type) type
pub fn hasDecl(comptime T: type, comptime name: []const u8) bool
pub fn fieldTypes(comptime T: type) []const type
pub fn fnParams(comptime fun: anytype) []const type

middleware/cors.zig

pub fn cors() Route

Adds CORS headers and handles preflight requests. Note that headers cannot be removed so this should always wrapped in a group.

middleware/logger.zig

pub fn logger(options: struct { scope: @TypeOf(.EnumLiteral) = .server }, children: []const Route) Route

Returns a wrapper for logging all requests going through it.

middleware/static.zig

pub fn dir(comptime path: []const u8, comptime options: DirOptions) Route

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.

pub fn file(comptime path: []const u8) Route

Serve a single static file.

middleware/swagger.zig

pub fn ui(comptime options: UiOptions) Route

Serve Swagger UI. Loads the UI from CDN and points it to the schema URL.

pub fn json(comptime options: SchemaOptions) Route

Generate OpenAPI 3.0 JSON schema from routes. Extracts path parameters, request bodies, and response types automatically.

mime.zig

pub const mime_types = if (@hasDecl(root, "mime_types")) root.mime_types else std.StaticStringMap([]const u8).initComptime(.{ .{ ".html", "text/html" }, .{ ".css", "text/css" }, .{ ".png", "image/png" }, .{ ".jpg", "image/jpeg" }, .{ ".jpeg", "image/jpeg" }, .{ ".gif", "image/gif" }, .{ ".svg", "image/svg+xml" }, .{ ".ico", "image/x-icon" }, .{ ".js", "text/javascript" }, .{ ".md", "text/markdown" }, });
pub fn mime(ext: []const u8) []const u8

Get the MIME type for a given file extension.

monitor.zig

pub fn monitor(processes: anytype) noreturn

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

pub fn parseValue(comptime T: type, s: []const u8, arena: std.mem.Allocator) !T

Parse a string value into the requested type. Supports: optional, bool, int, enum, string, and slices (comma-separated).

pdf.zig

pub const Error = error{ InvalidPageSize, EmptyDocument, InvalidObjectReference, StreamWriteError, AllocationError, };
pub const TextStyle = struct {
size: f64 = 12, bold: bool = false
}
pub const Value = union(enum) {
null, boolean: bool, integer: i64, real: f64, string: []const u8, name: []const u8, array: []Value, dictionary: []DictEntry, reference: ObjectRef
}
pub const DictEntry = struct {
key: []const u8, value: Value
}
pub fn DictEntry.kv(key: []const u8, value: Value) DictEntry
pub const ObjectRef = struct {
id: u32, generation: u16 = 0
}
pub const PdfObject = struct {
ref: ObjectRef, value: Value
}
pub const Document = struct {
arena: std.mem.Allocator, objects: ArrayList(PdfObject) = .empty, pages: ArrayList(*Page) = .empty, next_object_id: u32 = 1, stream_page_map: std.AutoHashMap(u32, usize)
}
pub fn Document.init(allocator: Allocator) !Document
pub fn Document.deinit(self: *Document) void
pub fn Document.addPage(self: *Document, width: f64, height: f64) !*Page
pub fn Document.render(self: *Document, allocator: std.mem.Allocator) ![]u8
pub const Page = struct {
document: *Document, width: f64, height: f64, buf: std.io.Writer.Allocating
}
pub fn Page.init(document: *Document, width: f64, height: f64) !Page
pub fn Page.addText(self: *Page, x: f64, y: f64, text: []const u8, style: TextStyle) !void
pub fn Page.addLine(self: *Page, x1: f64, y1: f64, x2: f64, y2: f64) !void
pub fn Page.addRect(self: *Page, x: f64, y: f64, w: f64, h: f64) !void
pub fn Page.moveTo(self: *Page, x: f64, y: f64) !void
pub fn Page.lineTo(self: *Page, x: f64, y: f64) !void
pub fn Page.curveTo(self: *Page, x1: f64, y1: f64, x2: f64, y2: f64, x3: f64, y3: f64) !void
pub fn Page.closePath(self: *Page) !void
pub fn Page.stroke(self: *Page) !void
pub fn Page.fill(self: *Page) !void
pub fn Page.fillAndStroke(self: *Page) !void

queue.zig

pub const JobId = u64;
pub const JobState = enum(u8) {
pending, running
}
pub const JobInfo = struct {
id: ?JobId = null, state: JobState = .pending, name: []const u8, key: []const u8 = "", data: []const u8 = "", scheduled_at: ?i64 = null
}
pub const Stats = struct {
submitted: u64 = 0, claimed: u64 = 0, finished: u64 = 0
}
pub const Queue = struct {
vtable: *const VTable
}
pub const Queue.VTable = struct {
submit: *const fn (*Queue, JobInfo) anyerror!?JobId, claim: *const fn (*Queue, std.mem.Allocator) anyerror!?JobInfo, finish: *const fn (*Queue, JobId) anyerror!bool, clear: *const fn (*Queue) anyerror!void, len: *const fn (*Queue) anyerror!usize, stats: *const fn (*Queue) anyerror!Stats, list: *const fn (*Queue, std.mem.Allocator) anyerror![]JobInfo
}
pub fn Queue.len(self: *Queue) !usize
pub fn Queue.submit(self: *Queue, job: JobInfo) !?JobId
pub fn Queue.claim(self: *Queue, arena: std.mem.Allocator) !?JobInfo
pub fn Queue.finish(self: *Queue, id: JobId) !bool
pub fn Queue.clear(self: *Queue) !void
pub fn Queue.list(self: *Queue, arena: std.mem.Allocator) ![]JobInfo
pub fn Queue.stats(self: *Queue) !Stats
pub const ShmQueueConfig = struct {
name: []const u8 = "tk_queue", capacity: u32 = 100, job_timeout: i64 = 300
}
pub const ShmQueue = struct {
mutex: ShmMutex, shm: Shm, time: *const fn () i64, job_timeout: i64, header: *Header, slots: []Slot, interface: Queue
}

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.

pub fn ShmQueue.init(self: *ShmQueue, config: ShmQueueConfig) !void

Initialize the queue in place. The caller must ensure self is at a stable memory location that won't be moved after this call.

pub fn ShmQueue.deinit(self: *ShmQueue) void

regex.zig

pub const Grep = struct {
reader: *std.io.Reader, regex: *Regex, line: usize = 0
}
pub fn Grep.init(reader: *std.io.Reader, regex: *Regex) Grep
pub fn Grep.next(self: *Grep) !?[]const u8
pub const Regex = struct {
code: []const Op, buf: []u16
}
pub fn Regex.compile(allocator: std.mem.Allocator, regex: []const u8) !Regex
pub fn Regex.deinit(self: *Regex, allocator: std.mem.Allocator) void
pub fn Regex.match(self: *Regex, text: []const u8) bool

resource.zig

pub const Resource = struct {
content: []const u8, content_type: []const u8
}
pub const Loader = struct {
vtable: *const VTable
}
pub const Loader.VTable = struct {
load: *const fn (*Loader, std.mem.Allocator, []const u8) anyerror!?Resource, resolve: *const fn (*Loader, std.mem.Allocator, []const u8) ?[]const u8
}
pub fn Loader.load(self: *Loader, arena: std.mem.Allocator, path: []const u8) !?Resource
pub fn Loader.resolve(self: *Loader, allocator: std.mem.Allocator, path: []const u8) ?[]const u8
pub const FsLoaderOptions = struct {
base_dir: []const u8 = "."
}
pub const FsLoader = struct {
interface: Loader, allocator: std.mem.Allocator, base_dir: []const u8
}
pub fn FsLoader.init(allocator: std.mem.Allocator, options: FsLoaderOptions) !FsLoader
pub fn FsLoader.deinit(self: *FsLoader) void

route.zig

pub const Route = struct {
method: ?httpz.Method = null, prefix: ?[]const u8 = null, path: ?[]const u8 = null, handler: ?*const fn (*Context) anyerror!void = null, children: []const Route = &.{}, metadata: ?*const Metadata = null
}

Defines an HTTP route with method, path, handler, and optional children. Use helper methods like get(), post(), group() to build routes.

pub fn Route.match(self: *const Route, req: *const httpz.Request) ?Params
pub fn Route.provide(comptime fac: anytype, children: []const Route) Route

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.

pub fn Route.send(comptime res: anytype) Route

Returns a route that sends the given, comptime response.

pub fn Route.redirect(comptime url: []const u8) Route

Returns a route that will redirect user somewhere else.

pub fn Route.group(prefix: []const u8, children: []const Route) Route

Groups the given routes under a common prefix. The prefix is removed from the request path before the children are called.

pub fn Route.get(comptime path: []const u8, comptime handler: anytype) Route

Creates a GET route with the given path and handler.

pub fn Route.post(comptime path: []const u8, comptime handler: anytype) Route

Creates a POST route with the given path and handler. The handler will receive the request body in the last argument.

pub fn Route.post0(comptime path: []const u8, comptime handler: anytype) Route

Creates a POST route with the given path and handler but without a body.

pub fn Route.put(comptime path: []const u8, comptime handler: anytype) Route

Creates a PUT route with the given path and handler. The handler will receive the request body in the last argument.

pub fn Route.put0(comptime path: []const u8, comptime handler: anytype) Route

Creates a PUT route with the given path and handler but without a body.

pub fn Route.patch(comptime path: []const u8, comptime handler: anytype) Route

Creates a PATCH route with the given path and handler. The handler will receive the request body in the last argument.

pub fn Route.patch0(comptime path: []const u8, comptime handler: anytype) Route

Creates a PATCH route with the given path and handler but without a body.

pub fn Route.delete(comptime path: []const u8, comptime handler: anytype) Route

Creates a DELETE route with the given path and handler.

pub fn Route.router(comptime T: type) Route

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.

pub const Params = struct {
matches: [16][]const u8 = undefined, len: usize = 0
}

Path parameters extracted from a route match (e.g., :id segments).

pub fn Params.match(pattern: []const u8, path: []const u8) ?Params

Match a pattern against a path, extracting parameters. Returns null if no match.

pub fn Params.get(self: *const Params, index: usize) ?[]const u8

sax.zig

pub const Event = union(enum) {
open: []const u8, attr: struct { name: []const u8, value: []const u8 }, close: []const u8, text: []const u8
}

A SAX event.

pub const Event.Attr = @FieldType(Event, "attr");
pub fn Event.format(self: Event, writer: anytype) !void
pub const Parser = struct {
reader: ?*std.io.Reader = null, is_eof: bool = false, scanner: Scanner = .{ .input = &.{} }
}

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.

pub fn Parser.initStreaming(reader: *std.io.Reader) Parser

Create a parser for streaming input.

pub fn Parser.initCompleteInput(input: []const u8) Parser

Create a parser for a complete input.

pub fn Parser.next(self: *Parser) !?Event

Returns next event or null if we reached the end of the input.

schema.zig

pub fn fmt(comptime T: type) std.json.Formatter(Schema)

Returns a formatter which will print a JSON-schema for the given type.

pub const Schema = union(enum) {
null, boolean, integer, number, string, object: []const Property, array: *const Schema, oneOf: []const Schema, tuple: []const Schema
}
pub fn Schema.forType(comptime T: type) Schema
pub fn Schema.jsonStringify(self: Schema, w: anytype) !void
pub const Property = struct {
name: []const u8, schema: *const Schema
}

selector.zig

pub const Selector = struct {
parts: []const Part
}
pub fn Selector.deinit(self: *Selector, allocator: std.mem.Allocator) void
pub fn Selector.parse(allocator: std.mem.Allocator, selector: []const u8) !Selector
pub fn Selector.format(self: Selector, writer: anytype) !void
pub fn Selector.match(self: *Selector, element: anytype) bool
pub fn QuerySelectorIterator(comptime E: type) type

sendmail.zig

pub const Config = struct {
path: []const u8 = "/usr/sbin/sendmail", args: []const []const u8 = &.{}, default_from: ?[]const u8 = null
}
pub const Message = struct {
from: ?[]const u8 = null, to: []const u8, subject: []const u8, text: []const u8
}
pub const Sendmail = struct {
config: Config = .{}
}
pub fn Sendmail.sendMail(self: *Sendmail, allocator: std.mem.Allocator, message: Message) !void

server.zig

pub const InitOptions = struct {
listen: ListenOptions = .{}, injector: ?*Injector = null, workers: httpz.Config.Worker = .{}, request: httpz.Config.Request = .{}, response: httpz.Config.Response = .{}, timeout: httpz.Config.Timeout = .{}, thread_pool: httpz.Config.ThreadPool = .{}, websocket: httpz.Config.Websocket = .{}
}

Configuration for Server.init(). Most options are passed through to httpz.

pub const ListenOptions = struct {
hostname: []const u8 = "127.0.0.1", port: u16 = 8080
}

Address and port to listen on.

pub const Server = struct {
allocator: std.mem.Allocator, routes: []const Route, injector: ?*Injector, http: httpz.Server(Adapter)
}

A simple HTTP server with dependency injection.

pub fn Server.init(allocator: std.mem.Allocator, routes: []const Route, options: InitOptions) !Server

Initialize a new server.

pub fn Server.deinit(self: *Server) void

Deinitialize the server.

pub fn Server.start(self: *Server) !void

Start listening for incoming connections.

pub fn Server.stop(self: *Server) void

Stop the server.

ssr.zig

pub const Engine = struct {
vtable: *const VTable
}
pub const Engine.VTable = struct {
render: *const fn (*Engine, []const u8, std.mem.Allocator, vm.Value) anyerror![]const u8
}
pub fn Engine.render(self: *Engine, name: []const u8, arena: std.mem.Allocator, data: anytype) ![]const u8
pub const DefaultEngine = struct {
loader: *resource.Loader, components: ComponentRegistry, interface: Engine = .{ .vtable = &.{ .render = &render }, }
}
pub fn DefaultEngine.init(loader: *resource.Loader, gpa: std.mem.Allocator) DefaultEngine
pub fn DefaultEngine.deinit(self: *DefaultEngine) void
pub fn DefaultEngine.defineComponent(self: *DefaultEngine, comptime name: []const u8, comptime T: type) !void
pub fn DefaultEngine.renderTemplate(self: *DefaultEngine, tpl: Template, arena: std.mem.Allocator, data: anytype) ![]const u8
pub const Template = struct {
root: []Node, arena: std.mem.Allocator
}
pub fn Template.parse(arena: std.mem.Allocator, input: []const u8) !Template
pub const RenderContext = struct {
writer: *std.io.Writer, js: js.Context, components: *ComponentRegistry, injector: Injector
}
pub fn RenderContext.setData(self: *RenderContext, data: vm.Value) !void
pub fn RenderContext.evalBool(self: *RenderContext, expr: []const u8) bool
pub fn RenderContext.raw(self: *RenderContext, bytes: []const u8) !void
pub fn RenderContext.text(self: *RenderContext, bytes: []const u8) !void
pub fn RenderContext.print(self: *RenderContext, comptime format: []const u8, args: anytype) !void
pub fn RenderContext.open(self: *RenderContext, tag: []const u8, attrs: []const [2][]const u8) !void
pub fn RenderContext.close(self: *RenderContext, tag: []const u8) !void
pub fn RenderContext.writeExpr(self: *RenderContext, expr: []const u8) !void

testing.zig

pub const allocator = std.testing.allocator;
pub const time = struct {
}
pub fn time.get() i64
pub fn time.getTime() @import("time.zig").Time
pub const expect = std.testing.expect;
pub fn expectError(res: anytype, expected: anyerror) !void

Like std.testing.expectError() but with flipped args.

pub fn expectEqual(res: anytype, expected: meta.Const(@TypeOf(res))) !void

Like std.testing.expectEqual() but with flipped args and support for strings and optionals.

pub fn expectFmt(arg: anytype, expected: []const u8) !void

Attempts to print arg into a buf and then compare those strings.

pub fn expectTable(items: anytype, comptime expected: []const u8) !void
pub fn httpClient() !struct

Shorthand for MockClient.init() + &mock.interface

time.zig

pub const TimeUnit = enum {
second, minute, hour, day, month, year
}

Units for Time operations (includes time-of-day components).

pub const DateUnit = enum {
day, month, year
}

Units for Date operations (calendar components only).

pub fn isLeapYear(year: i32) bool

Returns true if the given year is a leap year in the Gregorian calendar.

pub const Date = struct {
year: i32, month: u8, day: u8
}

Calendar date (year, month, day) without time-of-day or timezone. Uses Rata Die algorithm internally for efficient date arithmetic.

pub const Date.MIN = Date.ymd(-1467999, 1, 1);
pub const Date.MAX = Date.ymd(1471744, 12, 31);
pub fn Date.cmp(a: Date, b: Date) std.math.Order
pub fn Date.parse(str: []const u8) !Date
pub fn Date.ymd(year: i32, month: u8, day: u8) Date

Create a date from year, month (1-12), and day (1-31).

pub fn Date.today() Date
pub fn Date.yesterday() Date
pub fn Date.tomorrow() Date
pub fn Date.startOf(unit: DateUnit) Date
pub fn Date.endOf(unit: DateUnit) Date
pub fn Date.setStartOf(self: Date, unit: DateUnit) Date
pub fn Date.setEndOf(self: Date, unit: DateUnit) Date
pub fn Date.add(self: Date, part: DateUnit, amount: i64) Date
pub fn Date.dayOfWeek(self: Date) u8

Returns day of week (0 = Sunday, 1 = Monday, ..., 6 = Saturday).

pub fn Date.format(self: Date, writer: anytype) !void
pub const Time = struct {
epoch: i64
}

UTC timestamp with second precision, stored as Unix epoch. Provides fluent API for time manipulation: Time.now().setHour(10).add(.days, 1).

pub fn Time.unix(epoch: i64) Time

Create a Time from a Unix timestamp (seconds since 1970-01-01 00:00:00 UTC).

pub fn Time.now() Time

Get the current time.

pub fn Time.today() Time
pub fn Time.tomorrow() Time
pub fn Time.startOf(unit: TimeUnit) Time
pub fn Time.endOf(unit: TimeUnit) Time
pub fn Time.second(self: Time) u32
pub fn Time.setSecond(self: Time, sec: u32) Time
pub fn Time.minute(self: Time) u32
pub fn Time.setMinute(self: Time, min: u32) Time
pub fn Time.hour(self: Time) u32
pub fn Time.setHour(self: Time, hr: u32) Time
pub fn Time.date(self: Time) Date
pub fn Time.setDate(self: Time, dat: Date) Time
pub fn Time.setStartOf(self: Time, unit: TimeUnit) Time
pub fn Time.next(self: Time, unit: enum { second, minute, hour, day }) Time
pub fn Time.setEndOf(self: Time, unit: TimeUnit) Time
pub fn Time.add(self: Time, part: enum { seconds, minutes, hours, days, months, years }, amount: i64) Time
pub fn Time.format(self: Time, writer: anytype) !void

tpl.zig

pub fn raw(allocator: std.mem.Allocator, comptime template: []const u8, data: anytype) ![]const u8
pub const Template = struct {
tokens: []const Token
}
pub fn Template.parse(allocator: std.mem.Allocator, input: []const u8) !Template
pub fn Template.parseComptime(comptime input: []const u8) Template
pub fn Template.deinit(self: *Template, allocator: std.mem.Allocator) void
pub fn Template.render(self: *const Template, data: anytype, writer: *std.io.Writer) !void
pub fn Template.renderAlloc(self: *const Template, allocator: std.mem.Allocator, data: anytype) ![]const u8
pub const Value = union(enum) {
null, bool: bool, int: i64, float: f64, string: []const u8, @"struct": struct { *const anyopaque, *const fn (ptr: *const anyopaque, name: []const u8) Value }, indexable: struct { *const anyopaque, usize, *const fn (ptr: *const anyopaque, index: usize) Value }
}

tui.zig

pub const Key = union(enum) {
char: u8, up, down, left, right, home, end, page_up, page_down, tab, enter, backspace, delete, escape, ctrl_c, ctrl_d, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12
}
pub const Context = struct {
allocator: std.mem.Allocator, in: *std.io.Reader, out: *std.io.Writer, in_reader: std.fs.File.Reader, out_writer: std.fs.File.Writer, original_termios: std.posix.termios
}
pub fn Context.init(allocator: std.mem.Allocator) !*Context
pub fn Context.deinit(self: *Context) void
pub fn Context.clear(self: *Context) !void
pub fn Context.flush(self: *Context) !void
pub fn Context.readLine(self: *Context, buf: []u8) !?[]const u8
pub fn Context.readKey(self: *Context) !Key
pub fn Context.print(self: *Context, comptime fmt: []const u8, args: anytype) !void
pub fn Context.println(self: *Context, comptime fmt: []const u8, args: anytype) !void

util.zig

pub const Buf = @import("util/buf.zig").Buf;
pub const Shm = @import("util/shm.zig").Shm;
pub const ShmMutex = @import("util/shm.zig").Mutex;
pub const SlotMap = @import("util/slotmap.zig").SlotMap;
pub const SmolStr = @import("util/smolstr.zig").SmolStr;
pub const Smol128 = @import("util/smolstr.zig").Smol128;
pub const Smol192 = @import("util/smolstr.zig").Smol192;
pub const Smol256 = @import("util/smolstr.zig").Smol256;
pub const Sparse = @import("util/sparse.zig").Sparse;
pub const whitespace = std.ascii.whitespace;
pub fn trim(slice: []const u8) []const u8
pub fn truncateEnd(text: []const u8, width: usize) []const u8
pub fn truncateStart(text: []const u8, width: usize) []const u8
pub fn countScalar(comptime T: type, slice: []const T, value: T) usize
pub fn Cmp(comptime T: type) type
pub fn cmp(a: anytype, b: @TypeOf(a)) std.math.Order
pub fn lt(a: anytype, b: @TypeOf(a)) bool
pub fn eq(a: anytype, b: @TypeOf(a)) bool
pub fn gt(a: anytype, b: @TypeOf(a)) bool

util/bptree.zig

pub fn BPTree(comptime K: type, comptime V: type, comptime cmp: fn (K, K) std.math.Order) type

util/buf.zig

pub fn Buf(comptime T: type) type

util/shm.zig

pub const Mutex = struct {
fd: std.fs.File, thread_mutex: std.Thread.Mutex = .{}
}

Cross-process mutex which works reliably on Linux/macOS even after crash. Also thread-safe within a single process via std.Thread.Mutex.

pub fn Mutex.init(name: [:0]const u8) !Mutex
pub fn Mutex.deinit(self: *Mutex) void
pub fn Mutex.lock(self: *Mutex) void
pub fn Mutex.unlock(self: *Mutex) void
pub const Shm = struct {
fd: std.fs.File, data: []align(std.heap.page_size_min) u8, created: bool
}
pub fn Shm.open(name: [:0]const u8, size: usize) !Shm

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.

pub fn Shm.deinit(self: *Shm) void

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.

pub fn Shm.unlink(name: [:0]const u8) void

util/slotmap.zig

pub fn SlotMap(comptime T: type) type

util/smolstr.zig

pub const Smol128 = SmolStr(u128);
pub const Smol192 = SmolStr(u192);
pub const Smol256 = SmolStr(u256);
pub fn SmolStr(comptime B: type) type

util/sparse.zig

pub fn Sparse(comptime S: type, comptime D: type) type

visit.zig

pub const Edge = union(enum) {
void, null, bool: bool, int: i64, float: f64, string: []const u8, begin_struct: usize, field: []const u8, end_struct, begin_array: usize, end_array
}
pub fn visit(val: anytype, cx: anytype, handler: *const fn (@TypeOf(cx), Edge) anyerror!void) anyerror!void

vm.zig

pub const Error = error{ TypeError, StackUnderflow, OutOfMemory, UnexpectedError, };
pub const Value = union(enum) {
undefined, null, bool: bool, number: f64, string: []const u8, array: std.ArrayList(Value), object: std.StringHashMapUnmanaged(Value), fun: Fun, err: anyerror
}
pub fn Value.expect(self: *const Value, comptime kind: std.meta.Tag(Value)) !@FieldType(Value, @tagName(kind))
pub fn Value.into(self: *const Value, comptime T: type) Error!T
pub fn Value.format(self: Value, writer: anytype) !void
pub fn Value.isTruthy(self: Value) bool
pub const Fun = union(enum) {
native: *const fn (*Context) Error!void, compiled: struct { arity: u8, code: []const Op, }
}
pub const Op = union(enum) {
push: Value, store: []const u8, load: []const u8, call, dup, get
}
pub const Context = struct {
arena: std.mem.Allocator, stack: std.ArrayList(Value), env: std.StringHashMapUnmanaged(Value), intern_pool: std.StringHashMapUnmanaged(void)
}
pub fn Context.init(arena: std.mem.Allocator) Context
pub fn Context.intern(self: *Context, str: []const u8) ![]const u8
pub fn Context.ident(self: *Context, str: []const u8) ![]const u8
pub fn Context.value(self: *Context, input: anytype) Error!Value
pub fn Context.define(self: *Context, name: []const u8, val: anytype) Error!void
pub fn Context.get(self: *Context, name: []const u8) Value
pub fn Context.eval(self: *Context, code: []const Op) Error!Value

yaml.zig

pub const Writer = struct {
writer: *std.io.Writer, indent: usize = 0, after_dash: bool = false
}
pub fn Writer.init(writer: *std.io.Writer) Writer
pub fn Writer.writeValue(self: *Writer, value: anytype) !void
pub fn Writer.writeString(self: *Writer, value: []const u8) !void
pub fn Writer.writeSlice(self: *Writer, items: anytype) !void
pub fn Writer.writeStruct(self: *Writer, value: anytype) !void