Skip to main content

rust_pptx_wasm/
lib.rs

1use rust_pptx::{
2    detect_format, parse_presentation_with_options as parse_core_presentation, ParseLimits,
3};
4use serde::Serialize;
5use serde_wasm_bindgen::Serializer;
6use wasm_bindgen::prelude::*;
7
8#[wasm_bindgen]
9pub fn detect_presentation_format(bytes: &[u8]) -> Result<String, JsValue> {
10    detect_format(bytes)
11        .map(|format| {
12            match format {
13                rust_pptx::PresentationFormat::Pptx => "pptx",
14                rust_pptx::PresentationFormat::Ppt => "ppt",
15            }
16            .into()
17        })
18        .map_err(|error| JsValue::from_str(&error.to_string()))
19}
20
21#[wasm_bindgen]
22pub fn parse_presentation(bytes: &[u8], options: Option<JsValue>) -> Result<JsValue, JsValue> {
23    let options = match options.filter(|value| !value.is_null() && !value.is_undefined()) {
24        Some(value) => serde_wasm_bindgen::from_value(value)
25            .map_err(|error| JsValue::from_str(&format!("Invalid parser options: {error}")))?,
26        None => rust_pptx::ParseOptions::default(),
27    };
28    let document = parse_core_presentation(bytes, &ParseLimits::default(), &options)
29        .map_err(|error| JsValue::from_str(&error.to_string()))?;
30
31    // The TypeScript model exposes keyed collections as `Record<string, T>` rather than
32    // `Map<string, T>`. Keep byte buffers as Uint8Array and optional values as undefined,
33    // while making every Rust map cross the Wasm boundary as a plain JavaScript object.
34    document
35        .serialize(&Serializer::new().serialize_maps_as_objects(true))
36        .map_err(|error| JsValue::from_str(&error.to_string()))
37}