diff --git a/npm-wasm/README.md b/npm-wasm/README.md new file mode 100644 index 0000000..181ffbb --- /dev/null +++ b/npm-wasm/README.md @@ -0,0 +1,37 @@ +# openvector-wasm + +Trace an encoded PNG, JPEG, BMP, GIF, or TIFF image into an SVG string in a browser. The package uses the OpenVector Rust engine and requires no cross-origin isolation. + +```js +import createTracer from 'openvector-wasm'; + +const tracer = await createTracer(); +const svg = tracer.convert(imageBytes, { layout: 'cutouts' }); +``` + +Pass a `Uint8Array` or `ArrayBuffer`. The loader detects the image format from the bytes and throws an error when tracing fails. The optional SVG layout is `stacked`, `cutouts`, or `grouped-cutouts` (the default). Set `thinStroke: true` to enable the same SVG stroke option as the CLI. + +Use a dedicated module worker for large images so tracing leaves the interface responsive. To cancel a trace, terminate that worker and create a fresh one for the next image. + +```js +// Inside a module worker. Pin the version for CDN imports. +import createTracer from 'https://cdn.jsdelivr.net/npm/openvector-wasm@0.1.0/index.mjs'; + +const tracerReady = createTracer(); +self.onmessage = async ({ data }) => { + try { + const tracer = await tracerReady; + self.postMessage({ svg: tracer.convert(data) }); + } catch (error) { + self.postMessage({ error: error.message }); + } +}; +``` + +## Source and build + +The package includes the AGPLv3 license, third-party notices, and `source.tar.gz` with the matching Rust and JavaScript sources, Cargo lockfile, vendored dependencies, and build script. Dependencies retain their original licenses. The archive's `src/` directory contains the JPEG and TIFF notices. + +To rebuild on a system with Bash and GNU coreutils, install Rust 1.100.0 with `rust-docs` and the `wasm32-unknown-emscripten` target, and activate Emscripten 4.0.22. Extract `source.tar.gz` into an empty directory and run `bash npm-wasm/compile.sh /absolute/path/to/output` from that directory. + +To package a source checkout with those tools, run `bash scripts/wasm-prototype/build.sh /absolute/path/to/output npm`. To exercise a packed release in Chromium, install Python's Pillow and Playwright packages, install Chromium with `python -m playwright install chromium`, and run `python npm-wasm/smoke.py `. Use the CLI from the same OpenVector engine version. diff --git a/npm-wasm/compile.sh b/npm-wasm/compile.sh new file mode 100644 index 0000000..daa8641 --- /dev/null +++ b/npm-wasm/compile.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Build the engine from the staged, vendored Rust workspace. +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +out=$(realpath -m "${1:?pass an output directory}") +mkdir -p "$out" +export CARGO_TARGET_DIR="$(realpath -m "${CARGO_TARGET_DIR:-$out/target}")" +cd "$here/../rust" +cargo rustc --release --locked --offline -p trace-prototype --target wasm32-unknown-emscripten -- \ + -C link-arg=-sMODULARIZE=1 -C link-arg=-sEXPORT_ES6=1 \ + -C link-arg=-sEXPORTED_FUNCTIONS=_convert_image,_main -C link-arg=-sEXPORTED_RUNTIME_METHODS=FS \ + -C link-arg=-sALLOW_MEMORY_GROWTH=1 -C link-arg=-sSTACK_SIZE=4194304 \ + -C link-arg=-sENVIRONMENT=web,worker -C link-arg=-sSINGLE_FILE=1 +cp "$CARGO_TARGET_DIR/wasm32-unknown-emscripten/release/trace-prototype.js" "$out/engine.mjs" +cp "$here/"{package.json,index.mjs,index.d.ts,README.md} "$out/" +cp "$(rustc --print sysroot)/share/doc/rust/COPYRIGHT-library.html" "$out/rust-std-COPYRIGHT-library.html" +cp "$(dirname "$(command -v emcc)")/LICENSE" "$out/emscripten-LICENSE" diff --git a/npm-wasm/index.d.ts b/npm-wasm/index.d.ts new file mode 100644 index 0000000..c9299e7 --- /dev/null +++ b/npm-wasm/index.d.ts @@ -0,0 +1,10 @@ +export interface SvgOptions { + layout?: 'stacked' | 'cutouts' | 'grouped-cutouts'; + thinStroke?: boolean; +} + +export interface Tracer { + convert(imageBytes: Uint8Array | ArrayBuffer, options?: SvgOptions): string; +} + +export default function createTracer(): Promise; diff --git a/npm-wasm/index.mjs b/npm-wasm/index.mjs new file mode 100644 index 0000000..a115684 --- /dev/null +++ b/npm-wasm/index.mjs @@ -0,0 +1,26 @@ +import createEngine from './engine.mjs'; + +export default async function createTracer() { + const { FS, _convert_image: convertImage } = await createEngine(); + + return { + convert(imageBytes, options = {}) { + if (!(imageBytes instanceof Uint8Array || imageBytes instanceof ArrayBuffer)) { + throw new TypeError('Expected encoded image bytes as a Uint8Array or ArrayBuffer.'); + } + const encodedOptions = JSON.stringify(options); + try { + FS.writeFile('input', imageBytes instanceof Uint8Array ? imageBytes : new Uint8Array(imageBytes)); + FS.writeFile('options.json', encodedOptions); + if (convertImage() !== 0) { + throw new Error(FS.readFile('error.txt', { encoding: 'utf8' })); + } + return FS.readFile('output.svg', { encoding: 'utf8' }); + } finally { + for (const file of ['input', 'options.json', 'output.svg', 'error.txt']) { + if (FS.analyzePath(file).exists) FS.unlink(file); + } + } + }, + }; +} diff --git a/npm-wasm/package.json b/npm-wasm/package.json new file mode 100644 index 0000000..408cd74 --- /dev/null +++ b/npm-wasm/package.json @@ -0,0 +1,26 @@ +{ + "name": "openvector-wasm", + "version": "0.1.0", + "description": "Trace images into SVG in a browser or worker with OpenVector.", + "type": "module", + "license": "AGPL-3.0-only", + "main": "./index.mjs", + "types": "./index.d.ts", + "exports": { + ".": { + "types": "./index.d.ts", + "default": "./index.mjs" + } + }, + "files": ["index.mjs", "index.d.ts", "engine.mjs", "source.tar.gz", "*-licenses.txt", "rust-std-COPYRIGHT-library.html", "emscripten-LICENSE"], + "repository": { + "type": "git", + "url": "git+https://github.com/Microck/openvector.git", + "directory": "npm-wasm" + }, + "homepage": "https://openvector.app", + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + } +} diff --git a/npm-wasm/smoke.py b/npm-wasm/smoke.py new file mode 100644 index 0000000..d53823b --- /dev/null +++ b/npm-wasm/smoke.py @@ -0,0 +1,142 @@ +"""Exercise the packaged module in a sandboxed iframe without COOP/COEP.""" +import argparse +import base64 +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +import os +from pathlib import Path +import subprocess +import tarfile +import tempfile +from threading import Thread + +from PIL import Image, ImageDraw +from playwright.sync_api import sync_playwright + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("package", type=Path) + parser.add_argument("cli", type=Path) + parser.add_argument("--module-url", help="Exercise a published CDN module instead of the packaged file.") + args = parser.parse_args() + with tarfile.open(args.package, "r:gz") as archive: + manifest = json.load(archive.extractfile("package/package.json")) + assert manifest["name"] == "openvector-wasm" + assert manifest["license"] == "AGPL-3.0-only" + modules = {name: archive.extractfile(f"package/{name}").read() + for name in ("engine.mjs", "index.mjs")} + with tempfile.TemporaryDirectory() as isolated: + directory = Path(isolated) + image = Image.new("RGB", (32, 32), "white") + ImageDraw.Draw(image).rectangle((7, 7, 25, 25), fill="#a30068") + cases = [] + expected = [] + for fmt in ("png", "jpeg", "bmp", "gif", "tiff", "png"): + path = directory / f"example.{fmt}" + image.save(path) + layout = len(expected) == 5 + options = {"layout": "stacked", "thinStroke": True} if layout else {} + flags = ["--layout", "stacked", "--thin-stroke"] if layout else [] + cases.append([base64.b64encode(path.read_bytes()).decode(), options]) + expected.append(subprocess.check_output( + [str(args.cli.resolve()), "vectorize", str(path), "--format", "svg", *flags], + cwd=directory, timeout=60, + ).decode('utf-8')) + class FixtureServer(BaseHTTPRequestHandler): + def do_GET(self): + if self.path == "/": + payload, content_type = b"Worker package smoke", "text/html" + elif self.path == "/favicon.ico": + self.send_response(204) + self.end_headers() + return + elif self.path[1:] in modules: + payload, content_type = modules[self.path[1:]], "text/javascript" + else: + self.send_error(404) + return + self.send_response(200) + self.send_header("Content-Type", content_type) + self.send_header("Access-Control-Allow-Origin", "*") + self.end_headers() + self.wfile.write(payload) + + with ThreadingHTTPServer(("127.0.0.1", 0), FixtureServer) as server: + server_thread = Thread(target=server.serve_forever) + server_thread.start() + origin = f"http://127.0.0.1:{server.server_port}" + try: + result = run_worker(origin, args.module_url or f"{origin}/index.mjs", cases) + finally: + server.shutdown() + server_thread.join() + assert "failure" not in result, result + assert result["isolated"] is False + assert result["svg"] == expected + assert result["retry"] == expected[0] + assert result["reuse"] == expected[0] + assert len(result["errors"]) == 2, result["errors"] + assert "Unsupported image format" in result["errors"][0] + assert "valid layout" in result["errors"][1] + print(f"{len(cases)} conversions matched the CLI in a non-isolated iframe module worker; errors and reuse passed.") + + +def run_worker(origin, module_url, cases): + worker = "import createTracer from " + json.dumps(module_url) + ";\n" + ''' + const tracerReady = createTracer(); + const bytes = string => Uint8Array.from(atob(string), character => character.charCodeAt(0)); + self.onmessage = async ({ data }) => { + try { + const tracer = await tracerReady; + const svg = data.map(([encoded, options], index) => { + const image = bytes(encoded); + return tracer.convert(index === 1 ? image.buffer : image, options); + }); + const errors = []; + for (const [image, options] of [[bytes('AAAA'), {}], [bytes(data[0][0]), { layout: 'invalid' }]]) { + try { tracer.convert(image, options); } + catch (error) { errors.push(error.message); } + } + const retry = tracer.convert(bytes(data[0][0]), { + toJSON() { + const nested = tracer.convert(bytes(data[1][0])); + return nested === svg[1] ? {} : { layout: 'stacked' }; + }, + }); + postMessage({ svg, errors, isolated: self.crossOriginIsolated, + retry, reuse: tracer.convert(bytes(data[0][0])) }); + } catch (error) { postMessage({ failure: error.message }); } + }; + ''' + iframe = f""" + + """ + with sync_playwright() as playwright: + browser = playwright.chromium.launch(executable_path=os.environ.get("CHROMIUM")) + page = browser.new_page() + page.goto(origin) + result = page.evaluate("""html => new Promise((resolve, reject) => { + const deadline = setTimeout(() => reject(new Error('Worker timed out')), 60_000); + const iframe = document.createElement('iframe'); + iframe.sandbox = 'allow-scripts allow-same-origin'; + iframe.srcdoc = html; + window.addEventListener('message', message => { + if (message.source !== iframe.contentWindow) return; + clearTimeout(deadline); + resolve(message.data); + }); + document.body.append(iframe); + })""", iframe) + browser.close() + return result + + +if __name__ == "__main__": + main() diff --git a/scripts/wasm-prototype/build.sh b/scripts/wasm-prototype/build.sh index 7dac9cd..778a2e4 100755 --- a/scripts/wasm-prototype/build.sh +++ b/scripts/wasm-prototype/build.sh @@ -5,7 +5,12 @@ here=$(cd "$(dirname "$0")" && pwd) root=$(cd "$here/../.." && pwd) out=$(realpath -m "${1:?pass an output directory}") mkdir -p "$out" -export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$out/target}" +mode=${2:-benchmark} +case "$mode" in + benchmark|npm) ;; + *) echo "Choose benchmark or npm." >&2; exit 2 ;; +esac +export CARGO_TARGET_DIR="$(realpath -m "${CARGO_TARGET_DIR:-$out/target}")" stage=$(mktemp -d) trap 'rm -r "$stage"' EXIT cd "$stage" @@ -33,6 +38,21 @@ openvector = { path = "../openvector" } serde_json = "1" TOML cd rust +if [ "$mode" = npm ]; then + cargo metadata --format-version 1 > /dev/null + mkdir -p .cargo + cargo vendor --locked --versioned-dirs vendor > .cargo/config.toml + mkdir -p "$stage/npm-wasm" + cp "$root/npm-wasm/"{README.md,compile.sh,index.d.ts,index.mjs,package.json,smoke.py} "$stage/npm-wasm/" + cp "$root/LICENSE" "$stage/LICENSE" + cp "$root/src/"{jpeg,tiff}-licenses.txt "$stage/src/" + bash "$stage/npm-wasm/compile.sh" "$out" + cp "$stage/LICENSE" "$out/" + cp "$stage/src/"{jpeg,tiff}-licenses.txt "$out/" + tar -czf "$out/source.tar.gz" -C "$stage" LICENSE npm-wasm rust src + npm pack --ignore-scripts --pack-destination "$out" "$out" + exit +fi cargo build --release -p trace-prototype cp "$CARGO_TARGET_DIR"/release/trace-prototype "$out/native-trace" cargo rustc --release -p trace-prototype --target wasm32-unknown-emscripten -- \ diff --git a/scripts/wasm-prototype/editor.rs b/scripts/wasm-prototype/editor.rs index a83adb1..55bb276 100644 --- a/scripts/wasm-prototype/editor.rs +++ b/scripts/wasm-prototype/editor.rs @@ -117,12 +117,12 @@ fn dispatch() -> Result<(), String> { if command["action"] == "open" { let (document, settings, image) = open( &fs::read("input").map_err(|e| e.to_string())?, - command["filename"].as_str().ok_or("Missing filename.")?, + Some(command["filename"].as_str().ok_or("Missing filename.")?), command["shrink"].as_bool().unwrap_or(false), )?; let mut candidate = Editor { document, - settings, + settings: Value::Object(settings.to_json()), options: ExportOptions::default(), }; let mut reply = candidate.command(&command)?; diff --git a/scripts/wasm-prototype/trace.rs b/scripts/wasm-prototype/trace.rs index ec09b41..c3e502a 100644 --- a/scripts/wasm-prototype/trace.rs +++ b/scripts/wasm-prototype/trace.rs @@ -1,24 +1,30 @@ use openvector::{ - export_options::ExportOptions, image_document::ImageDocument, image_input, + document_controls::DocumentSettings, export_options::ExportOptions, image_document::ImageDocument, + image_input, palette::CoreSession, svg::export_svg, vector_output::VectorOutputInput, }; +#[cfg(target_os = "emscripten")] +use openvector::export_options::ExportOptionsError; use serde_json::json; use std::fs; fn open( bytes: &[u8], - filename: &str, + filename: Option<&str>, shrink: bool, ) -> Result< ( ImageDocument, - serde_json::Value, + DocumentSettings, openvector::pixel_input::DecodedImage, ), String, > { - let meta = image_input::resolve_image_filename(filename); let mut image = image_input::decode_image(bytes).map_err(|e| e.to_string())?; + let meta = filename.map_or_else( + || image_input::resolve_image_filename(&format!(".{}", image.format)), + image_input::resolve_image_filename, + ); let (width, height) = (image.width, image.height); let mut document = ImageDocument::new(CoreSession::default()); document.set_source( @@ -44,11 +50,7 @@ fn open( } } let trace = document.run_automatic(&json!({"extension": meta.extension}))?; - Ok(( - document, - serde_json::Value::Object(trace.settings.to_json()), - image, - )) + Ok((document, trace.settings, image)) } fn render(document: &ImageDocument, options: ExportOptions) -> Result { @@ -75,7 +77,7 @@ fn render(document: &ImageDocument, options: ExportOptions) -> Result Result { let bytes = fs::read(input).map_err(|e| e.to_string())?; let start = std::time::Instant::now(); - let (document, _, _) = open(&bytes, input, false)?; + let (document, _, _) = open(&bytes, Some(input), false)?; let svg = render(&document, ExportOptions::default())?; let ms = start.elapsed().as_secs_f64() * 1000.0; fs::write(output, svg).map_err(|e| e.to_string())?; @@ -91,6 +93,40 @@ pub extern "C" fn convert_png() -> f64 { }) } +#[cfg(target_os = "emscripten")] +#[unsafe(no_mangle)] +pub extern "C" fn convert_image() -> i32 { + fn convert() -> Result<(), String> { + let options: serde_json::Value = + serde_json::from_slice(&fs::read("options.json").map_err(|e| e.to_string())?) + .map_err(|e| e.to_string())?; + if options.as_object().is_some_and(|fields| { + fields.keys().any(|key| !matches!(key.as_str(), "layout" | "thinStroke")) + }) { + return Err("SVG options are layout and thinStroke.".into()); + } + let options = openvector::export_options::read_export_options( + &options, + ExportOptions::default(), + ) + .map_err(|error| match error { + ExportOptionsError::Invalid => "Choose a valid layout and a boolean thinStroke.".into(), + other => other.to_string(), + })?; + let bytes = fs::read("input").map_err(|e| e.to_string())?; + let (document, _, _) = open(&bytes, None, false)?; + fs::write("output.svg", render(&document, options)?).map_err(|e| e.to_string()) + } + + match convert() { + Ok(()) => 0, + Err(error) => { + fs::write("error.txt", error).expect("Could not write the tracing error"); + 1 + } + } +} + #[cfg(target_os = "emscripten")] fn main() {} diff --git a/tools/check-source.sh b/tools/check-source.sh index cb55507..7158831 100755 --- a/tools/check-source.sh +++ b/tools/check-source.sh @@ -4,5 +4,5 @@ set -euo pipefail cd "$(dirname "$0")/.." npm ci --ignore-scripts npm run test:smoke -find npm bin src tools test -type f -name '*.mjs' -print0 | xargs -0 -n1 node --check +find npm npm-wasm bin src tools test -type f -name '*.mjs' -print0 | xargs -0 -n1 node --check npm pack --ignore-scripts --dry-run