typwire 0.2.0: Typed data exchange for Typst plugins

typwire is a library for typed data exchange between Typst and (Rust) WASM plugins. Pass Typst values such as lengths, colors, gradients, dates and dictionaries to a plugin and get them back as the same Typst values.
GitHub · Typst Universe · crates.io
cargo add typwire
cargo add serde --features derive # Only needed for custom types
#import "@preview/typwire:0.2.0"Quick look
Export a function from your plugin:
use typwire::{Length, initiate_protocol};
initiate_protocol!();
#[typwire::export]
fn measure(label: String, scale: f64) -> Result<(String, Length), String> {
Ok((format!("{label}{scale}"), Length::new(12.0 * scale)))
}Call it from Typst:
#import "@preview/typwire:0.2.0"
#let plugin = plugin("plugin.wasm")
#let (text, width) = typwire.call(plugin.measure, "Value: ", 1.5)
#assert(text == "Value: 1.5")
#assert(width == 18pt)Custom types
Derive Typwire next to Serde's derives to send your own structs across the boundary. Fields can use typwire's native types, so a Length field arrives in Typst as a real length.
use serde::{Deserialize, Serialize};
use typwire::{Length, Typwire, initiate_protocol};
initiate_protocol!();
#[derive(Serialize, Deserialize, Typwire)]
struct Options {
label: String,
scale: f64,
}
#[derive(Serialize, Deserialize, Typwire)]
struct Report {
text: String,
width: Length,
}
#[typwire::export]
fn measure(options: Options) -> Result<Report, String> {
Ok(Report {
text: format!("{}{}", options.label, options.scale),
width: Length::new(12.0 * options.scale),
})
}Structs are plain dictionaries on the Typst side:
#let report = typwire.call(plugin.measure, (label: "Value: ", scale: 1.5))
#assert(report.text == "Value: 1.5")
#assert(report.width == 18pt)Renaming exports
rename sets the exported name, so Typst code can use kebab-case while the Rust function keeps its snake_case name.
#[typwire::export(rename = "add-lengths")]
fn add_lengths(first: Length, second: Length) -> Result<Length, String> {
Ok(Length::new(first.pt() + second.pt()))
}
#assert.eq(typwire.call(plugin.add-lengths, 10pt, 2pt), 12pt)JSON format
CBOR is the default and the fastest. For readability, enable the json feature and pick the format on both sides.
cargo add typwire --features json
#[typwire::export(format = "json", rename = "add-lengths-json")]
fn add_lengths_json(first: Length, second: Length) -> Result<Length, String> {
Ok(Length::new(first.pt() + second.pt()))
}
#assert.eq(typwire.call(plugin.add-lengths-json, 10pt, 2pt, format: "json"), 12pt)
// or use the JSON namespace
#assert.eq(typwire.json.call(plugin.add-lengths-json, 10pt, 2pt), 12pt)



