use std::collections::{BTreeMap, HashMap, VecDeque};
use std::sync::Arc;
use wasm_bindgen::prelude::*;
use crate::measure::{MeasureClient, MeasureFormat, MeasureItem, fnv1a64, fnv1a64_update};
use crate::{CompileRequest, Engine};
fn error(message: impl std::fmt::Display) -> JsValue {
JsValue::from_str(&message.to_string())
}
fn parse_map(raw: &str) -> Result<BTreeMap<String, String>, JsValue> {
let value: serde_json::Value = serde_json::from_str(raw)
.map_err(|fault| error(format!("inputs are not JSON: {fault}")))?;
let object = value
.as_object()
.ok_or_else(|| error("inputs must be a JSON object"))?;
object
.iter()
.map(|(key, value)| {
value
.as_str()
.map(|text| (key.clone(), text.to_owned()))
.ok_or_else(|| error("input values must be strings"))
})
.collect()
}
#[wasm_bindgen]
pub struct Ctypst {
engine: Arc<Engine>,
overlays: Vec<(String, Overlay)>,
measure: MeasureClient,
raw_hits: HashMap<u64, String>,
raw_order: VecDeque<u64>,
}
const RAW_CACHE_MAX: usize = 64;
enum Overlay {
Source(String),
Binary(Vec<u8>),
}
#[wasm_bindgen]
impl Ctypst {
#[wasm_bindgen(constructor)]
pub fn open() -> Result<Ctypst, JsValue> {
let engine = Arc::new(
Engine::builder()
.fonts(crate::fonts::documents())
.build()
.map_err(|fault| error(format!("cannot open ctypst: {fault}")))?,
);
let measure = MeasureClient::new(crate::fonts::documents())
.map_err(|fault| error(format!("cannot open measurement: {fault}")))?;
Ok(Self {
engine,
overlays: Vec::new(),
measure,
raw_hits: HashMap::new(),
raw_order: VecDeque::new(),
})
}
#[must_use]
pub fn versions() -> String {
serde_json::json!({
"ctypst": env!("CARGO_PKG_VERSION"),
"protocol": crate::measure::PROTOCOL_VERSION,
})
.to_string()
}
pub fn add_source(&mut self, path: String, content: String) {
self.replace_overlay(path, Overlay::Source(content));
}
pub fn add_binary(&mut self, path: String, content: Vec<u8>) {
self.replace_overlay(path, Overlay::Binary(content));
}
fn replace_overlay(&mut self, path: String, overlay: Overlay) {
if let Some(slot) = self.overlays.iter_mut().find(|(pinned, _)| *pinned == path) {
slot.1 = overlay;
} else {
self.overlays.push((path, overlay));
}
}
pub fn measure_all(&mut self, format_json: &str, items_json: &str) -> Result<String, JsValue> {
let key = fnv1a64_update(fnv1a64(format_json.as_bytes()), items_json.as_bytes());
if let Some(hit) = self.raw_hits.get(&key) {
return Ok(hit.clone());
}
let format: MeasureFormat = serde_json::from_str(format_json)
.map_err(|fault| error(format!("format is not a measure format: {fault}")))?;
let items: Vec<MeasureItem> = serde_json::from_str(items_json)
.map_err(|fault| error(format!("items are not measure items: {fault}")))?;
let results = self
.measure
.measure_all(&format, &items)
.map_err(|fault| error(format!("measurement failed: {fault}")))?;
let calibration = self.measure.calibration();
let encoded = serde_json::to_string(&serde_json::json!({
"results": results,
"calibration": calibration,
}))
.map_err(|fault| error(format!("cannot encode results: {fault}")))?;
if self.raw_hits.len() >= RAW_CACHE_MAX
&& let Some(old) = self.raw_order.pop_front()
{
self.raw_hits.remove(&old);
}
self.raw_order.push_back(key);
self.raw_hits.insert(key, encoded.clone());
Ok(encoded)
}
pub fn compile(&self, source: &str, inputs_json: &str) -> Result<CompiledDoc, JsValue> {
let inputs = parse_map(inputs_json)?;
let mut request =
CompileRequest::new("main.typ".to_owned()).source_file("main.typ", source.to_owned());
for (path, overlay) in &self.overlays {
request = match overlay {
Overlay::Source(content) => request.source_file(path.clone(), content.clone()),
Overlay::Binary(bytes) => request.binary_file(path.clone(), bytes.clone()),
};
}
request = request.inputs(inputs);
let document = self
.engine
.compile(request)
.map(|output| output.document)
.map_err(|fault| error(format!("compilation failed: {fault}")))?;
Ok(CompiledDoc {
engine: Arc::clone(&self.engine),
document,
})
}
}
#[wasm_bindgen]
pub struct CompiledDoc {
engine: Arc<Engine>,
document: crate::Document,
}
#[wasm_bindgen]
impl CompiledDoc {
#[must_use]
pub fn page_count(&self) -> usize {
self.document.pages().len()
}
pub fn svg_page(&self, page: usize) -> Result<String, JsValue> {
self.engine
.svg_page(&self.document, page)
.map_err(|fault| error(format!("SVG export failed: {fault}")))
}
pub fn svg_merged(&self, gap_pt: f64) -> Result<String, JsValue> {
if !gap_pt.is_finite() || gap_pt < 0.0 {
return Err(error("SVG gap must be finite and non-negative"));
}
Ok(typst_svg::svg_merged(
&self.document,
&typst_svg::SvgOptions {
render_bleed: false,
pretty: false,
},
typst::layout::Abs::pt(gap_pt),
))
}
pub fn pdf(&self) -> Result<Vec<u8>, JsValue> {
self.engine
.pdf(&self.document, 0)
.map_err(|fault| error(format!("PDF export failed: {fault}")))
}
}
#[cfg(test)]
mod tests {
use super::Ctypst;
#[test]
fn repeated_overlays_replace_instead_of_accumulating() {
let mut runtime = Ctypst::open().expect("runtime opens on embedded fonts");
runtime.add_source("/x.typ".to_owned(), "Version one".to_owned());
runtime.add_source("/x.typ".to_owned(), "Version two".to_owned());
runtime.add_binary("/x.bin".to_owned(), vec![1, 2, 3]);
runtime.add_binary("/x.bin".to_owned(), vec![4, 5]);
let document = runtime
.compile("#include \"/x.typ\"", "{}")
.expect("overlay include compiles");
assert_eq!(document.page_count(), 1);
}
}