Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions npm-wasm/README.md
Original file line number Diff line number Diff line change
@@ -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 <package.tgz> <openvector-cli>`. Use the CLI from the same OpenVector engine version.
17 changes: 17 additions & 0 deletions npm-wasm/compile.sh
Original file line number Diff line number Diff line change
@@ -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"
10 changes: 10 additions & 0 deletions npm-wasm/index.d.ts
Original file line number Diff line number Diff line change
@@ -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<Tracer>;
26 changes: 26 additions & 0 deletions npm-wasm/index.mjs
Original file line number Diff line number Diff line change
@@ -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);
}
}
},
};
}
26 changes: 26 additions & 0 deletions npm-wasm/package.json
Original file line number Diff line number Diff line change
@@ -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/"
}
}
142 changes: 142 additions & 0 deletions npm-wasm/smoke.py
Original file line number Diff line number Diff line change
@@ -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"<title>Worker package smoke</title>", "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"""
<script>
const worker = new Worker(URL.createObjectURL(new Blob([{json.dumps(worker)}],
{{ type: 'text/javascript' }})), {{ type: 'module' }});
worker.onmessage = ({{ data }}) => parent.postMessage(data, '*');
worker.onerror = (error) => parent.postMessage({{ failure: error.message }}, '*');
worker.postMessage({json.dumps(cases)});
</script>
"""
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()
22 changes: 21 additions & 1 deletion scripts/wasm-prototype/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 -- \
Expand Down
4 changes: 2 additions & 2 deletions scripts/wasm-prototype/editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)?;
Expand Down
Loading
Loading