Zig
Zig makes small, fast modules (the summary is 95 KB: about 30 ms for its first call, which compiles it, and 1.2 ms for later ones) and needs nothing but Zig: WASI is one of its targets. Its standard library has JSON, so a module reads and writes JSON with no packages.
Set up
brew install zig # Zig 0.17
Zig's standard library changes between versions. The example is written for Zig 0.17, where I/O goes through std.Io and main takes std.process.Init.
The module
pub fn main(init: std.process.Init) !void {
const io = init.io;
const allocator = init.arena.allocator();
var out_buf: [4096]u8 = undefined;
var stdout = std.Io.File.stdout().writerStreaming(io, &out_buf);
const out = &stdout.interface;
const args = try init.minimal.args.toSlice(allocator);
const function: []const u8 = if (args.len > 1) args[1] else "";
if (std.mem.eql(u8, function, "--describe")) {
try out.writeAll(@embedFile("manifest.json"));
return out.flush();
}
if (!std.mem.eql(u8, function, "run")) fail(io, "no_such_function", function);
var in_buf: [4096]u8 = undefined;
var stdin = std.Io.File.stdin().readerStreaming(io, &in_buf);
const input = try stdin.interface.allocRemaining(allocator, .unlimited);
const post = std.json.parseFromSliceLeaky(Post, allocator, input, .{ .ignore_unknown_fields = true }) catch
fail(io, "bad_input", "the input isn't a post");
// ... the summary
try std.json.Stringify.value(.{ .text = text.items, .words = words.items.len }, .{}, out);
try out.flush();
}
Flush the writer before returning: output still in its buffer is lost when the program exits.
Build
In build.zig, target WASI, make the manifest importable, and set the stack:
const target = b.standardTargetOptions(.{
.default_target = .{ .os_tag = .wasi, .cpu_arch = .wasm32 },
});
// ...
mod.addAnonymousImport("manifest.json", .{ .root_source_file = b.path("manifest.json") });
const exe = b.addExecutable(.{ .name = "summary", .root_module = mod });
exe.stack_size = 1 << 20; // Zig's default stack is 16 MB: every call would start with 16 MB of memory
zig build -Doptimize=ReleaseSmall
cp zig-out/bin/summary.wasm pb_hooks/summary.pb.wasm
A Zig module never says it's Zig, so the manifest says "language": "Zig".
Call it
const { title, body } = ctx.req.body()
const out = await $wasm.run.async<{ text: string }>("summary", { title, body })
C libraries
Zig compiles C as well: add C files to the module with mod.addCSourceFiles(...) and link libc (mod.link_libc = true), and a Zig module can use a C library directly. For C alone, see C and C++.
Questions and comments
Comments are a GitHub Discussions thread; sign in with GitHub to post.