Skip to content

armgit / forma

Public Imported from GitHub
0

A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server

feat: edge/Workers/browser WASM loader, static-release LTO, and offline sandbox kit

wrong-nebula91863ccc7a83
diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml
index ba5b0dd..ddb1e30 100644
--- a/.github/workflows/npm-publish.yml
+++ b/.github/workflows/npm-publish.yml
@@ -20,8 +20,10 @@ jobs:
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with:
targets: wasm32-unknown-unknown
- - name: Build wasm/forma.wasm from source
- run: npm run build:wasm
+ - name: Install Binaryen (wasm-opt)
+ run: sudo apt-get update && sudo apt-get install -y binaryen
+ - name: Build and optimize wasm/forma.wasm from source
+ run: npm run build:wasm && ls -lh wasm/forma.wasm
- run: npm test
- run: npm publish --access public
env:
diff --git a/.github/workflows/server-release.yml b/.github/workflows/server-release.yml
index cbd3d1d..e1fd1e4 100644
--- a/.github/workflows/server-release.yml
+++ b/.github/workflows/server-release.yml
@@ -1,30 +1,90 @@
-name: Release Optional forma-server
+name: Release Static Linux Binaries & Sandbox Kit
on:
+ release:
+ types: [published]
push:
tags:
- "server-v*"
workflow_dispatch:
jobs:
- build-server:
+ build-static:
runs-on: ubuntu-latest
permissions:
contents: write
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - target: x86_64-unknown-linux-musl
+ arch: x86_64
+ extra_rustflags: ""
+ - target: aarch64-unknown-linux-musl
+ arch: aarch64
+ extra_rustflags: "-C linker=rust-lld -C linker-flavor=ld.lld -C link-self-contained=yes"
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
- targets: x86_64-unknown-linux-musl
- - run: sudo apt-get update && sudo apt-get install -y musl-tools
- - name: Build standalone static forma-server
+ targets: ${{ matrix.target }}
+ - name: Install musl & zip tools
+ run: sudo apt-get update && sudo apt-get install -y musl-tools zip
+
+ - name: Build static forma CLI & forma-server (${{ matrix.target }})
+ env:
+ RUSTFLAGS: "--remap-path-prefix=/home/runner=/home -C target-feature=+crt-static ${{ matrix.extra_rustflags }}"
+ run: |
+ cargo build --locked --profile static-release --target ${{ matrix.target }} -p forma-cli -p forma-server
+ out="target/${{ matrix.target }}/static-release"
+ ls -lh "$out/forma" "$out/forma-server"
+ file "$out/forma" "$out/forma-server"
+
+ tar -czf "forma-linux-${{ matrix.arch }}-musl.tar.gz" -C "$out" forma
+ tar -czf "forma-server-linux-${{ matrix.arch }}-musl.tar.gz" -C "$out" forma-server
+
+ # Single-file offline sandbox kit (ChatGPT VM, AWS Lambda Python, air-gapped containers)
+ mkdir -p dist/sandbox
+ cp "$out/forma" dist/sandbox/forma
+ cp sandbox/forma.py dist/sandbox/forma.py
+ cp SKILL.md dist/sandbox/SKILL.md
+ chmod +x dist/sandbox/forma
+ (cd dist/sandbox && zip -9 "../../forma-sandbox-linux-${{ matrix.arch }}.zip" forma forma.py SKILL.md)
+
+ - name: Smoke test x86_64 static binary & offline sandbox kit
+ if: matrix.arch == 'x86_64'
run: |
- RUSTFLAGS="--remap-path-prefix=$HOME=/home -C target-feature=+crt-static" \
- cargo build --release --target x86_64-unknown-linux-musl -p forma-server
- strip target/x86_64-unknown-linux-musl/release/forma-server
- tar -czf forma-server-linux-x86_64-musl.tar.gz -C target/x86_64-unknown-linux-musl/release forma-server
- - name: Upload Release Asset (on server-v* tags)
- if: startsWith(github.ref, 'refs/tags/server-v')
+ out="target/${{ matrix.target }}/static-release"
+ ldd "$out/forma" 2>&1 | grep -qiE "not a dynamic executable|statically linked"
+ ldd "$out/forma-server" 2>&1 | grep -qiE "not a dynamic executable|statically linked"
+ printf 'flange = box(4,2,0.4) | cut(cyl(0.5,1))\n' | "$out/forma" eval --strict --out /tmp/ci_flange.glb --render /tmp/ci_flange.png
+ python3 - <<'PY'
+ import sys, zipfile
+ zipfile.ZipFile("forma-sandbox-linux-x86_64.zip").extractall("/tmp/ci_sandbox")
+ sys.path.insert(0, "/tmp/ci_sandbox")
+ import forma
+ obs = forma.eval_pipe("flange = box(4,2,0.4) | cut(cyl(0.5,1))", strict=True)
+ assert "WT=ok" in obs and "NM=0" in obs, obs
+ assert len(forma.export_mesh("a = box(1,1,1)", "glb")) > 200
+ assert forma.render_png("a = box(1,1,1)", 128)[:2] == b"\x89P"
+ assert "<svg" in forma.draw_svg("a = box(1,1,1)")
+ print("OK sandbox zip verified")
+ PY
+
+ - name: Upload workflow artifacts
+ uses: actions/upload-artifact@v4
+ with:
+ name: forma-static-linux-${{ matrix.arch }}
+ path: |
+ forma-linux-${{ matrix.arch }}-musl.tar.gz
+ forma-server-linux-${{ matrix.arch }}-musl.tar.gz
+ forma-sandbox-linux-*.zip
+
+ - name: Attach static binaries to GitHub Release
+ if: github.event_name == 'release' || startsWith(github.ref, 'refs/tags/server-v')
uses: softprops/action-gh-release@v2
with:
- files: forma-server-linux-x86_64-musl.tar.gz
+ files: |
+ forma-linux-${{ matrix.arch }}-musl.tar.gz
+ forma-server-linux-${{ matrix.arch }}-musl.tar.gz
+ forma-sandbox-linux-*.zip
diff --git a/Cargo.toml b/Cargo.toml
index 66e254c..584b1e0 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -26,3 +26,9 @@ opt-level = "z"
lto = true
codegen-units = 1
strip = true
+
+[profile.static-release]
+inherits = "release"
+lto = true
+codegen-units = 1
+strip = "symbols"
diff --git a/Dockerfile b/Dockerfile
index 8e76eba..73e145d 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -5,12 +5,11 @@ WORKDIR /src
COPY Cargo.toml Cargo.lock ./
COPY crates ./crates
RUN RUSTFLAGS="--remap-path-prefix=/root=/home -C target-feature=+crt-static" \
- cargo build --release -p forma-server -p forma-cli && \
- strip target/release/forma-server target/release/forma
+ cargo build --locked --profile static-release -p forma-server -p forma-cli
FROM scratch
-COPY --from=builder /src/target/release/forma-server /forma-server
-COPY --from=builder /src/target/release/forma /forma
+COPY --from=builder /src/target/static-release/forma-server /forma-server
+COPY --from=builder /src/target/static-release/forma /forma
ENV FORMA_BIND=0.0.0.0:8080
EXPOSE 8080
ENTRYPOINT ["/forma-server"]
diff --git a/lib/edge.mjs b/lib/edge.mjs
new file mode 100644
index 0000000..31ee12a
--- /dev/null
+++ b/lib/edge.mjs
@@ -0,0 +1,374 @@
+/**
+ * forma-3d/edge — Zero-dependency, pure Web-standard WebAssembly API for Forma.
+ *
+ * Works in Cloudflare Workers, Vercel Edge, Netlify Edge, Fastly Compute,
+ * Deno Deploy, Supabase Edge Functions, browsers, Web Workers, Bun, and Node.js.
+ * Contains zero Node.js built-in imports.
+ */
+
+const encoder = new TextEncoder();
+const decoder = new TextDecoder("utf-8");
+
+let defaultEnginePromise = null;
+let defaultFileLoader = null;
+let defaultWasmModule = null;
+const moduleEngineCache = new WeakMap();
+
+/** @internal Registered by lib/index.mjs for Node.js/Bun/Deno local file loading. */
+export function _setDefaultFileLoader(fn) {
+ defaultFileLoader = fn;
+}
+
+/** @internal Registered by lib/workerd.mjs for zero-boilerplate Cloudflare Workers. */
+export function _setDefaultWasmModule(mod) {
+ defaultWasmModule = mod;
+}
+
+function evictEngine(engine) {
+ if (engine._evict) {
+ engine._evict();
+ }
+}
+
+export class FormaEngine {
+ constructor(instance, onTrap = null) {
+ this.exports = instance.exports;
+ this.memory = instance.exports.memory;
+ this._evict = onTrap;
+ }
+
+ _run(fn) {
+ try {
+ return fn();
+ } catch (err) {
+ // Rust wasm32-unknown-unknown aborts on trap/OOM, which can leave RefCell
+ // state poisoned. Evict this cached instance so the next request recovers cleanly.
+ if (typeof WebAssembly !== "undefined" && err instanceof WebAssembly.RuntimeError) {
+ evictEngine(this);
+ }
+ throw err;
+ }
+ }
+
+ _withUtf8(str, fn) {
+ return this._run(() => {
+ const bytes = encoder.encode(str ?? "");
+ const ptr = this.exports.forma_alloc(bytes.length);
+ try {
+ if (bytes.length > 0) {
+ new Uint8Array(this.memory.buffer, ptr, bytes.length).set(bytes);
+ }
+ return fn(ptr, bytes.length);
+ } finally {
+ this.exports.forma_dealloc(ptr, bytes.length);
+ }
+ });
+ }
+
+ _readResultBytes() {
+ return this._run(() => {
+ const ptr = this.exports.forma_result_ptr();
+ const len = this.exports.forma_result_len();
+ const isErr = this.exports.forma_result_is_err() !== 0;
+ const copy = new Uint8Array(this.memory.buffer, ptr, len).slice();
+ if (isErr) {
+ throw new Error(decoder.decode(copy));
+ }
+ return copy;
+ });
+ }
+
+ _readResultString() {
+ return decoder.decode(this._readResultBytes());
+ }
+
+ /** Return the compact language reference (~355 tokens) or formal GBNF grammar. */
+ spec({ dialect = "pipe", gbnf = false } = {}) {
+ return this._run(() => {
+ const d = dialect === "compact" ? 1 : 0;
+ this.exports.forma_spec(d, gbnf ? 1 : 0);
+ return this._readResultString();
+ });
+ }
+
+ /** Return progressive on-demand domain spec (`deform|curves|uv|remesh|scene`). */
+ specTopic(topic) {
+ return this._withUtf8(topic, (ptr, len) => {
+ this.exports.forma_spec_topic(ptr, len);
+ return this._readResultString();
+ });
+ }
+
+ /** Create a stateful transactional 3D modeling session. */
+ createSession() {
+ const id = this._run(() => this.exports.forma_session_new());
+ return new FormaSession(this, id);
+ }
+}
+
+export class FormaSession {
+ constructor(engine, id) {
+ this._engine = engine;
+ this._id = id;
+ this._freed = false;
+ }
+
+ _checkOpen() {
+ if (this._freed) {
+ throw new Error("FormaSession has been freed");
+ }
+ }
+
+ /** Evaluate Forma-Pipe (or compact) code transactionally; returns parsed Observation. */
+ eval(code, { dialect = "pipe", strict = true } = {}) {
+ this._checkOpen();
+ const d = dialect === "compact" ? 1 : 0;
+ this._engine._withUtf8(code, (ptr, len) => {
+ this._engine.exports.forma_session_eval(this._id, ptr, len, d, strict ? 1 : 0);
+ });
+ return JSON.parse(this._engine._readResultString());
+ }
+
+ /** Inspect current scene state without mutating it. */
+ inspect() {
+ this._checkOpen();
+ this._engine._run(() => this._engine.exports.forma_session_inspect(this._id));
+ return JSON.parse(this._engine._readResultString());
+ }
+
+ /** Copy-on-write state control: checkpoint | rollback | undo | reset. */
+ tx(action, tag = "default") {
+ this._checkOpen();
+ return this._engine._withUtf8(action, (ap, al) =>
+ this._engine._withUtf8(tag, (tp, tl) => {
+ this._engine.exports.forma_session_tx(this._id, ap, al, tp, tl);
+ return this._engine._readResultString();
+ })
+ );
+ }
+
+ /** Export bytes for .glb, .step, .3mf, .stl, .obj, .svg, or 4-view .png. */
+ exportBytes(format, { part = "", size = 512 } = {}) {
+ this._checkOpen();
+ return this._engine._withUtf8(format, (ep, el) =>
+ this._engine._withUtf8(part || "", (pp, pl) => {
+ this._engine.exports.forma_session_export(this._id, ep, el, pp, pl, size >>> 0);
+ return this._engine._readResultBytes();
+ })
+ );
+ }
+
+ /** Export all named scene parts as a multi-node glTF 2.0 (.glb) scene graph. */
+ exportSceneBytes() {
+ this._checkOpen();
+ this._engine._run(() => this._engine.exports.forma_session_export_scene(this._id));
+ return this._engine._readResultBytes();
+ }
+
+ /** Compute MeshInvariants JSON for the current or named part. */
+ invariants(part = "") {
+ this._checkOpen();
+ this._engine._withUtf8(part || "", (pp, pl) => {
+ this._engine.exports.forma_session_invariants(this._id, pp, pl);
+ });
+ return JSON.parse(this._engine._readResultString());
+ }
+
+ /** Free session memory in the WASM heap. */
+ free() {
+ if (!this._freed) {
+ this._freed = true;
+ this._engine._run(() => this._engine.exports.forma_session_free(this._id));
+ }
+ }
+}
+
+function isWebUrl(source) {
+ if (source instanceof URL) {
+ return source.protocol !== "file:";
+ }
+ if (typeof source === "string") {
+ return /^(?:https?|blob|data):/i.test(source);
+ }
+ return false;
+}
+
+async function instantiateFromResponse(res) {
+ if (!res.ok) {
+ throw new Error(`Failed to fetch Forma WASM (${res.status} ${res.statusText})`);
+ }
+ const contentType = (res.headers?.get("content-type") || "").toLowerCase();
+ if (
+ typeof WebAssembly.instantiateStreaming === "function" &&
+ contentType.includes("application/wasm")
+ ) {
+ const { instance } = await WebAssembly.instantiateStreaming(res, {});
+ return new FormaEngine(instance);
+ }
+ const bytes = await res.arrayBuffer();
+ const { instance } = await WebAssembly.instantiate(bytes, {});
+ return new FormaEngine(instance);
+}
+
+async function instantiateSource(rawSource) {
+ const source = await rawSource;
+
+ if (source instanceof FormaEngine) {
+ return source;
+ }
+ if (source instanceof WebAssembly.Instance) {
+ return new FormaEngine(source);
+ }
+ if (source instanceof WebAssembly.Module) {
+ // Pre-compiled WebAssembly.Module path (Cloudflare Workers, Vercel Edge, Fastly, etc.)
+ const instance = await WebAssembly.instantiate(source, {});
+ return new FormaEngine(instance);
+ }
+ if (source instanceof ArrayBuffer || ArrayBuffer.isView(source)) {
+ const { instance } = await WebAssembly.instantiate(source, {});
+ return new FormaEngine(instance);
+ }
+ if (typeof Response !== "undefined" && source instanceof Response) {
+ return instantiateFromResponse(source);
+ }
+
+ // String / URL / omitted default
+ if (source != null) {
+ if (!isWebUrl(source) && defaultFileLoader) {
+ const bytes = await defaultFileLoader(source);
+ if (bytes) {
+ const { instance } = await WebAssembly.instantiate(bytes, {});
+ return new FormaEngine(instance);
+ }
+ }
+ if (typeof fetch === "function") {
+ return instantiateFromResponse(await fetch(source));
+ }
+ throw new Error(
+ `Cannot load Forma WASM from "${source}" in this runtime. Pass a WebAssembly.Module, Uint8Array, ArrayBuffer, or Response.`
+ );
+ }
+
+ // Default source (no argument passed)
+ if (defaultFileLoader) {
+ const bytes = await defaultFileLoader(undefined);
+ if (bytes) {
+ const { instance } = await WebAssembly.instantiate(bytes, {});
+ return new FormaEngine(instance);
+ }
+ }
+ if (typeof fetch === "function") {
+ try {
+ const defaultUrl = new URL("../wasm/forma.wasm", import.meta.url);
+ return await instantiateFromResponse(await fetch(defaultUrl));
+ } catch (err) {
+ throw new Error(
+ `Forma WASM could not be auto-loaded in this runtime (${err instanceof Error ? err.message : String(err)}). ` +
+ `Pass a pre-compiled WebAssembly.Module (e.g. \`import wasm from "forma-3d/wasm"; await loadForma(wasm)\`), Uint8Array, Response, or URL.`
+ );
+ }
+ }
+ throw new Error(
+ `Forma WASM could not be auto-loaded in this runtime. ` +
+ `Pass a WebAssembly.Module (e.g. \`import wasm from "forma-3d/wasm"; await loadForma(wasm)\`), Uint8Array, ArrayBuffer, or Response.`
+ );
+}
+
+/**
+ * Load and instantiate the Forma WASM engine (cached by default).
+ *
+ * Accepts a pre-compiled `WebAssembly.Module` (Cloudflare Workers / Edge),
+ * `WebAssembly.Instance`, `Uint8Array` / `ArrayBuffer`, `Response` (or `fetch()` Promise),
+ * `URL` / path string, or omitted to auto-load bundled `wasm/forma.wasm`.
+ */
+export async function loadForma(wasmSource, { fresh = false } = {}) {
+ const effectiveSource = wasmSource ?? defaultWasmModule;
+
+ if (!fresh) {
+ if (wasmSource == null && defaultEnginePromise) {
+ return defaultEnginePromise;
+ }
+ if (effectiveSource instanceof WebAssembly.Module) {
+ const cached = moduleEngineCache.get(effectiveSource);
+ if (cached) return cached;
+ }
+ }
+
+ let loader;
+ const evict = () => {
+ if (defaultEnginePromise === loader) defaultEnginePromise = null;
+ if (
+ effectiveSource instanceof WebAssembly.Module &&
+ moduleEngineCache.get(effectiveSource) === loader
+ ) {
+ moduleEngineCache.delete(effectiveSource);
+ }
+ };
+
+ loader = instantiateSource(effectiveSource).then((engine) => {
+ if (!fresh) {
+ engine._evict = evict;
+ }
+ return engine;
+ });
+
+ if (!fresh) {
+ if (effectiveSource instanceof WebAssembly.Module) {
+ moduleEngineCache.set(effectiveSource, loader);
+ if (!defaultEnginePromise) {
+ defaultEnginePromise = loader;
+ }
+ } else if (wasmSource == null || !defaultEnginePromise) {
+ defaultEnginePromise = loader;
+ }
+ loader.catch(evict);
+ }
+
+ return loader;
+}
+
+/** One-shot helper: evaluate Forma-Pipe script and return Observation. */
+export async function evalPipe(code, opts = {}) {
+ const engine = await loadForma(opts.wasm);
+ const s = engine.createSession();
+ try {
+ return s.eval(code, opts);
+ } finally {
+ s.free();
+ }
+}
+
+/** One-shot helper: evaluate script and export binary bytes (.glb/.step/.3mf/.stl/.obj/.svg/.png). */
+export async function exportMesh(code, format = "glb", opts = {}) {
+ const engine = await loadForma(opts.wasm);
+ const s = engine.createSession();
+ try {
+ s.eval(code, opts);
+ return s.exportBytes(format, opts);
+ } finally {
+ s.free();
+ }
+}
+
+/** One-shot helper: evaluate script and render a 4-view studio PNG (Uint8Array). */
+export async function renderPng(code, size = 512, opts = {}) {
+ return exportMesh(code, "png", { ...opts, size });
+}
+
+/** One-shot helper: evaluate script and render a 1200x900 engineering SVG blueprint string. */
+export async function drawSvg(code, opts = {}) {
+ const bytes = await exportMesh(code, "svg", opts);
+ return decoder.decode(bytes);
+}
+
+/** Return the compact language reference or formal GBNF grammar. */
+export async function getSpec(opts = {}) {
+ const engine = await loadForma(opts.wasm);
+ return engine.spec(opts);
+}
+
+/** Return progressive on-demand domain spec (`deform|curves|uv|remesh|scene`). */
+export async function getSpecTopic(topic, opts = {}) {
+ const engine = await loadForma(opts.wasm);
+ return engine.specTopic(topic);
+}
diff --git a/lib/index.d.ts b/lib/index.d.ts
index 344d888..096b34a 100644
--- a/lib/index.d.ts
+++ b/lib/index.d.ts
@@ -1,3 +1,23 @@
+export type WasmSource =
+ | WebAssembly.Module
+ | WebAssembly.Instance
+ | FormaEngine
+ | ArrayBuffer
+ | ArrayBufferView
+ | Response
+ | URL
+ | string
+ | Promise<
+ | WebAssembly.Module
+ | WebAssembly.Instance
+ | FormaEngine
+ | ArrayBuffer
+ | ArrayBufferView
+ | Response
+ | URL
+ | string
+ >;
+
export interface FormaObservation {
ok: boolean;
elapsed_ms: number;
@@ -15,9 +35,16 @@ export interface FormaInvariants {
volume: number;
}
+export interface LoadFormaOptions {
+ /** Create a fresh WebAssembly.Instance instead of reusing the cached engine. */
+ fresh?: boolean;
+}
+
export interface EvalOptions {
dialect?: "pipe" | "compact";
strict?: boolean;
+ /** Optional WASM module/bytes/Response/URL for edge & browser runtimes. */
+ wasm?: WasmSource;
}
export interface ExportOptions extends EvalOptions {
@@ -28,6 +55,13 @@ export interface ExportOptions extends EvalOptions {
export interface SpecOptions {
dialect?: "pipe" | "compact";
gbnf?: boolean;
+ /** Optional WASM module/bytes/Response/URL for edge & browser runtimes. */
+ wasm?: WasmSource;
+}
+
+export interface TopicOptions {
+ /** Optional WASM module/bytes/Response/URL for edge & browser runtimes. */
+ wasm?: WasmSource;
}
export class FormaSession {
@@ -43,13 +77,14 @@ export class FormaSession {
free(): void;
}
-export interface FormaEngine {
+export class FormaEngine {
+ constructor(instance: WebAssembly.Instance);
spec(opts?: SpecOptions): string;
specTopic(topic: string): string;
createSession(): FormaSession;
}
-export function loadForma(wasmSource?: string | URL | Uint8Array | ArrayBuffer): Promise<FormaEngine>;
+export function loadForma(wasmSource?: WasmSource, opts?: LoadFormaOptions): Promise<FormaEngine>;
export function evalPipe(code: string, opts?: EvalOptions): Promise<FormaObservation>;
export function exportMesh(
code: string,
@@ -59,4 +94,4 @@ export function exportMesh(
export function renderPng(code: string, size?: number, opts?: EvalOptions): Promise<Uint8Array>;
export function drawSvg(code: string, opts?: EvalOptions): Promise<string>;
export function getSpec(opts?: SpecOptions): Promise<string>;
-export function getSpecTopic(topic: string): Promise<string>;
+export function getSpecTopic(topic: string, opts?: TopicOptions): Promise<string>;
diff --git a/lib/index.mjs b/lib/index.mjs
index 818d936..ef42283 100644
--- a/lib/index.mjs
+++ b/lib/index.mjs
@@ -1,214 +1,40 @@
/**
- * forma-3d — Zero-dependency pure-WASM JavaScript/Node.js API for Forma
- * (a 1.2 MB pure-Rust rewrite of headless Blender built for AI agents).
+ * forma-3d — Zero-dependency universal WebAssembly API for Forma
+ * (Node.js, Bun, Deno, Cloudflare Workers, Vercel/Netlify Edge, Fastly, and browsers).
+ *
+ * Contains zero top-level Node.js built-in imports so it can also be loaded in
+ * edge/browser runtimes by passing a WebAssembly.Module, Response, Uint8Array, or URL.
*/
-import { readFile } from "node:fs/promises";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
+import { _setDefaultFileLoader } from "./edge.mjs";
-const __dirname = dirname(fileURLToPath(import.meta.url));
-const DEFAULT_WASM_PATH = join(__dirname, "..", "wasm", "forma.wasm");
+export {
+ FormaEngine,
+ FormaSession,
+ loadForma,
+ evalPipe,
+ exportMesh,
+ renderPng,
+ drawSvg,
+ getSpec,
+ getSpecTopic,
+} from "./edge.mjs";
-const encoder = new TextEncoder();
-const decoder = new TextDecoder("utf-8");
-
-let cachedEnginePromise = null;
-
-class FormaEngine {
- constructor(instance) {
- this.exports = instance.exports;
- this.memory = instance.exports.memory;
- }
-
- _withUtf8(str, fn) {
- const bytes = encoder.encode(str ?? "");
- const ptr = this.exports.forma_alloc(bytes.length);
- try {
- if (bytes.length > 0) {
- new Uint8Array(this.memory.buffer, ptr, bytes.length).set(bytes);
- }
- return fn(ptr, bytes.length);
- } finally {
- this.exports.forma_dealloc(ptr, bytes.length);
- }
- }
-
- _readResultBytes() {
- const ptr = this.exports.forma_result_ptr();
- const len = this.exports.forma_result_len();
- const isErr = this.exports.forma_result_is_err() !== 0;
- const copy = new Uint8Array(this.memory.buffer, ptr, len).slice();
- if (isErr) {
- throw new Error(decoder.decode(copy));
- }
- return copy;
- }
-
- _readResultString() {
- return decoder.decode(this._readResultBytes());
- }
-
- /** Return the compact language reference (~355 tokens) or formal GBNF grammar. */
- spec({ dialect = "pipe", gbnf = false } = {}) {
- const d = dialect === "compact" ? 1 : 0;
- this.exports.forma_spec(d, gbnf ? 1 : 0);
- return this._readResultString();
- }
-
- /** Return progressive on-demand domain spec (`deform|curves|uv|remesh|scene`). */
- specTopic(topic) {
- return this._withUtf8(topic, (ptr, len) => {
- this.exports.forma_spec_topic(ptr, len);
- return this._readResultString();
- });
- }
-
- /** Create a stateful transactional 3D modeling session. */
- createSession() {
- const id = this.exports.forma_session_new();
- return new FormaSession(this, id);
- }
-}
-
-export class FormaSession {
- constructor(engine, id) {
- this._engine = engine;
- this._id = id;
- this._freed = false;
- }
-
- _checkOpen() {
- if (this._freed) {
- throw new Error("FormaSession has been freed");
- }
- }
-
- /** Evaluate Forma-Pipe (or compact) code transactionally; returns parsed Observation. */
- eval(code, { dialect = "pipe", strict = true } = {}) {
- this._checkOpen();
- const d = dialect === "compact" ? 1 : 0;
- this._engine._withUtf8(code, (ptr, len) => {
- this._engine.exports.forma_session_eval(this._id, ptr, len, d, strict ? 1 : 0);
- });
- return JSON.parse(this._engine._readResultString());
- }
-
- /** Inspect current scene state without mutating it. */
- inspect() {
- this._checkOpen();
- this._engine.exports.forma_session_inspect(this._id);
- return JSON.parse(this._engine._readResultString());
- }
-
- /** Copy-on-write state control: checkpoint | rollback | undo | reset. */
- tx(action, tag = "default") {
- this._checkOpen();
- return this._engine._withUtf8(action, (ap, al) =>
- this._engine._withUtf8(tag, (tp, tl) => {
- this._engine.exports.forma_session_tx(this._id, ap, al, tp, tl);
- return this._engine._readResultString();
- })
- );
- }
-
- /** Export bytes for .glb, .step, .3mf, .stl, .obj, .svg, or 4-view .png. */
- exportBytes(format, { part = "", size = 512 } = {}) {
- this._checkOpen();
- return this._engine._withUtf8(format, (ep, el) =>
- this._engine._withUtf8(part || "", (pp, pl) => {
- this._engine.exports.forma_session_export(this._id, ep, el, pp, pl, size >>> 0);
- return this._engine._readResultBytes();
- })
- );
- }
-
- /** Export all named scene parts as a multi-node glTF 2.0 (.glb) scene graph. */
- exportSceneBytes() {
- this._checkOpen();
- this._engine.exports.forma_session_export_scene(this._id);
- return this._engine._readResultBytes();
- }
-
- /** Compute MeshInvariants JSON for the current or named part. */
- invariants(part = "") {
- this._checkOpen();
- this._engine._withUtf8(part || "", (pp, pl) => {
- this._engine.exports.forma_session_invariants(this._id, pp, pl);
- });
- return JSON.parse(this._engine._readResultString());
- }
-
- /** Free session memory in the WASM heap. */
- free() {
- if (!this._freed) {
- this._freed = true;
- this._engine.exports.forma_session_free(this._id);
- }
- }
-}
-
-/** Load and instantiate the Forma WASM engine (cached after first call). */
-export async function loadForma(wasmSource = DEFAULT_WASM_PATH) {
- if (wasmSource === DEFAULT_WASM_PATH && cachedEnginePromise) {
- return cachedEnginePromise;
+async function readLocalWasm(source) {
+ const target = source ?? new URL("../wasm/forma.wasm", import.meta.url);
+ if (typeof Bun !== "undefined" && typeof Bun.file === "function") {
+ return new Uint8Array(await Bun.file(target).arrayBuffer());
}
- const loader = (async () => {
- const bytes =
- wasmSource instanceof Uint8Array || wasmSource instanceof ArrayBuffer
- ? wasmSource
- : await readFile(wasmSource);
- const { instance } = await WebAssembly.instantiate(bytes, {});
- return new FormaEngine(instance);
- })();
- if (wasmSource === DEFAULT_WASM_PATH) {
- cachedEnginePromise = loader;
+ if (typeof Deno !== "undefined" && typeof Deno.readFile === "function") {
+ return Deno.readFile(target);
}
- return loader;
-}
-
-/** One-shot helper: evaluate Forma-Pipe script and return Observation. */
-export async function evalPipe(code, opts = {}) {
- const engine = await loadForma();
- const s = engine.createSession();
- try {
- return s.eval(code, opts);
- } finally {
- s.free();
- }
-}
-
-/** One-shot helper: evaluate script and export binary bytes (.glb/.step/.3mf/.stl/.obj/.svg/.png). */
-export async function exportMesh(code, format = "glb", opts = {}) {
- const engine = await loadForma();
- const s = engine.createSession();
- try {
- s.eval(code, opts);
- return s.exportBytes(format, opts);
- } finally {
- s.free();
+ if (typeof process !== "undefined" && process.versions?.node) {
+ // Dynamic specifier avoids static bundler resolution errors on edge/browser targets.
+ const fsModule = "node:" + "fs/promises";
+ const { readFile } = await import(fsModule);
+ return readFile(target);
}
+ return null;
}
-/** One-shot helper: evaluate script and render a 4-view studio PNG (Uint8Array). */
-export async function renderPng(code, size = 512, opts = {}) {
- return exportMesh(code, "png", { ...opts, size });
-}
-
-/** One-shot helper: evaluate script and render a 1200x900 engineering SVG blueprint string. */
-export async function drawSvg(code, opts = {}) {
- const bytes = await exportMesh(code, "svg", opts);
- return decoder.decode(bytes);
-}
-
-/** Return the compact language reference or formal GBNF grammar. */
-export async function getSpec(opts = {}) {
- const engine = await loadForma();
- return engine.spec(opts);
-}
-
-/** Return progressive on-demand domain spec (`deform|curves|uv|remesh|scene`). */
-export async function getSpecTopic(topic) {
- const engine = await loadForma();
- return engine.specTopic(topic);
-}
+_setDefaultFileLoader(readLocalWasm);
diff --git a/lib/wasm.d.ts b/lib/wasm.d.ts
new file mode 100644
index 0000000..0cedfa2
--- /dev/null
+++ b/lib/wasm.d.ts
@@ -0,0 +1,2 @@
+declare const wasmModule: WebAssembly.Module;
+export default wasmModule;
diff --git a/lib/workerd.mjs b/lib/workerd.mjs
new file mode 100644
index 0000000..909383d
--- /dev/null
+++ b/lib/workerd.mjs
@@ -0,0 +1,25 @@
+/**
+ * forma-3d/workerd — Zero-boilerplate Cloudflare Workers entrypoint.
+ *
+ * Selected automatically via the `workerd` export condition in package.json.
+ * Statically imports `../wasm/forma.wasm` (matching Wrangler's default `.wasm`
+ * CompiledWasm bundling rule) so `evalPipe`, `exportMesh`, `renderPng`,
+ * `drawSvg`, `getSpec`, and `loadForma()` work with zero setup.
+ */
+
+import formaWasm from "../wasm/forma.wasm";
+import { _setDefaultWasmModule } from "./edge.mjs";
+
+_setDefaultWasmModule(formaWasm);
+
+export {
+ FormaEngine,
+ FormaSession,
+ loadForma,
+ evalPipe,
+ exportMesh,
+ renderPng,
+ drawSvg,
+ getSpec,
+ getSpecTopic,
+} from "./edge.mjs";
diff --git a/package.json b/package.json
index fcba884..4e4402c 100644
--- a/package.json
+++ b/package.json
@@ -10,8 +10,30 @@
"exports": {
".": {
"types": "./lib/index.d.ts",
- "import": "./lib/index.mjs"
- }
+ "workerd": "./lib/workerd.mjs",
+ "edge-light": "./lib/edge.mjs",
+ "fastly": "./lib/edge.mjs",
+ "browser": "./lib/edge.mjs",
+ "node": "./lib/index.mjs",
+ "default": "./lib/index.mjs"
+ },
+ "./edge": {
+ "types": "./lib/index.d.ts",
+ "import": "./lib/edge.mjs"
+ },
+ "./workerd": {
+ "types": "./lib/index.d.ts",
+ "import": "./lib/workerd.mjs"
+ },
+ "./forma.wasm": {
+ "types": "./lib/wasm.d.ts",
+ "default": "./wasm/forma.wasm"
+ },
+ "./wasm": {
+ "types": "./lib/wasm.d.ts",
+ "default": "./wasm/forma.wasm"
+ },
+ "./wasm/forma.wasm": "./wasm/forma.wasm"
},
"bin": {
"forma": "bin/forma.mjs",
@@ -31,7 +53,7 @@
"LICENSE"
],
"scripts": {
- "build:wasm": "RUSTFLAGS=\"--remap-path-prefix=$HOME=/home\" cargo build --locked --profile wasm-release --target wasm32-unknown-unknown -p forma-wasm && mkdir -p wasm && cp target/wasm32-unknown-unknown/wasm-release/forma_wasm.wasm wasm/forma.wasm",
+ "build:wasm": "RUSTFLAGS=\"--remap-path-prefix=$HOME=/home\" cargo build --locked --profile wasm-release --target wasm32-unknown-unknown -p forma-wasm && mkdir -p wasm && cp target/wasm32-unknown-unknown/wasm-release/forma_wasm.wasm wasm/forma.wasm && (command -v wasm-opt >/dev/null 2>&1 && wasm-opt -Oz --enable-bulk-memory --enable-sign-ext --enable-mutable-globals --enable-nontrapping-float-to-int wasm/forma.wasm -o wasm/forma.wasm || true)",
"test": "node tests/npm_smoke.mjs"
},
"keywords": [
diff --git a/sandbox/forma.py b/sandbox/forma.py
new file mode 100644
index 0000000..549de49
--- /dev/null
+++ b/sandbox/forma.py
@@ -0,0 +1,234 @@
+"""Zero-dependency Python helper for running Forma in air-gapped sandboxes.
+
+Works out of the box in ChatGPT Code Interpreter (Advanced Data Analysis),
+AWS Lambda (Python runtime / Lambda Layers), Google Colab, Modal, E2B, boat.dev,
+and any offline Linux/macOS container where a static `forma` binary is bundled.
+
+Example (ChatGPT VM after uploading `forma-sandbox-linux-x86_64.zip`):
+ import sys, zipfile
+ zipfile.ZipFile("/mnt/data/forma-sandbox-linux-x86_64.zip").extractall("/tmp/forma_kit")
+ sys.path.insert(0, "/tmp/forma_kit")
+ import forma
+
+ obs = forma.eval_pipe(
+ "flange = box(4, 2, 0.4) | cut(cyl(0.5, 1))",
+ out="/mnt/data/flange.glb",
+ render="/mnt/data/flange.png",
+ )
+ print(obs)
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import stat
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+from typing import Any
+
+_CACHED_BIN: str | None = None
+
+
+def _is_runnable(path: Path) -> bool:
+ if not path.is_file():
+ return False
+ try:
+ res = subprocess.run(
+ [str(path), "--version"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ check=False,
+ )
+ return res.returncode == 0
+ except OSError:
+ return False
+
+
+def _ensure_executable(candidate: Path) -> str | None:
+ if not candidate.is_file():
+ return None
+ # Try in place first (chmod +x if permitted).
+ try:
+ mode = candidate.stat().st_mode
+ if not (mode & stat.S_IXUSR):
+ os.chmod(candidate, mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
+ except OSError:
+ pass
+ if _is_runnable(candidate):
+ return str(candidate)
+
+ # Fallback for noexec mounts (e.g. /mnt/data in ChatGPT VM or read-only layers):
+ # copy to a writable temp directory and mark executable.
+ tmp_bin = Path(tempfile.gettempdir()) / "forma"
+ try:
+ if tmp_bin.resolve() != candidate.resolve():
+ shutil.copy2(candidate, tmp_bin)
+ os.chmod(tmp_bin, 0o755)
+ if _is_runnable(tmp_bin):
+ return str(tmp_bin)
+ except OSError:
+ pass
+ return None
+
+
+def find_binary(bin_path: str | os.PathLike[str] | None = None) -> str:
+ """Locate a runnable `forma` binary, copying out of noexec mounts if needed."""
+ global _CACHED_BIN
+ if bin_path is not None:
+ resolved = _ensure_executable(Path(bin_path))
+ if resolved:
+ return resolved
+ raise FileNotFoundError(f"Forma binary at '{bin_path}' could not be executed.")
+
+ if _CACHED_BIN and Path(_CACHED_BIN).is_file():
+ return _CACHED_BIN
+
+ here = Path(__file__).resolve().parent
+ candidates: list[Path] = []
+ if env_bin := os.environ.get("FORMA_BIN"):
+ candidates.append(Path(env_bin))
+ candidates.extend(
+ [
+ here / "forma",
+ Path(tempfile.gettempdir()) / "forma",
+ Path("/opt/bin/forma"), # AWS Lambda Layer default bin path
+ Path("/mnt/data/forma"), # ChatGPT VM uploaded file path
+ ]
+ )
+ if which := shutil.which("forma"):
+ candidates.append(Path(which))
+
+ for cand in candidates:
+ resolved = _ensure_executable(cand)
+ if resolved:
+ _CACHED_BIN = resolved
+ return resolved
+
+ raise FileNotFoundError(
+ "Could not find a runnable `forma` binary. Place `forma` next to forma.py, "
+ "set FORMA_BIN, or pass bin_path=..."
+ )
+
+
+def spec(
+ *,
+ dialect: str = "pipe",
+ gbnf: bool = False,
+ bin_path: str | os.PathLike[str] | None = None,
+) -> str:
+ """Return the compact Forma-Pipe spec (~355 tokens) or formal GBNF grammar."""
+ args = [find_binary(bin_path), "spec", "--dialect", dialect]
+ if gbnf:
+ args.append("--gbnf")
+ res = subprocess.run(args, capture_output=True, text=True, check=False)
+ if res.returncode != 0:
+ raise RuntimeError((res.stderr or res.stdout).strip())
+ return res.stdout
+
+
+def eval_pipe(
+ code: str,
+ *,
+ strict: bool = True,
+ dialect: str = "pipe",
+ unit: str | None = None,
+ scene: bool = False,
+ out: str | os.PathLike[str] | None = None,
+ render: str | os.PathLike[str] | None = None,
+ view: str | None = None,
+ draw: str | os.PathLike[str] | None = None,
+ size: int = 512,
+ as_json: bool = False,
+ bin_path: str | os.PathLike[str] | None = None,
+) -> str | dict[str, Any]:
+ """Evaluate a Forma-Pipe script and optionally export mesh, PNG preview, and SVG."""
+ args = [
+ find_binary(bin_path),
+ "eval",
+ "--dialect",
+ dialect,
+ "--strict" if strict else "--no-strict",
+ ]
+ if unit is not None:
+ args.extend(["--unit", unit])
+ if scene:
+ args.append("--scene")
+ if as_json:
+ args.append("--json")
+ if out is not None:
+ args.extend(["--out", str(out)])
+ if render is not None:
+ args.extend(["--render", str(render), "--size", str(size)])
+ if view is not None:
+ args.extend(["--view", view])
+ if draw is not None:
+ args.extend(["--draw", str(draw)])
+
+ res = subprocess.run(args, input=code, capture_output=True, text=True, check=False)
+ if res.returncode != 0:
+ detail = (res.stderr or res.stdout).strip()
+ raise RuntimeError(f"forma eval failed (exit {res.returncode}): {detail}")
+ return json.loads(res.stdout) if as_json else res.stdout
+
+
+def export_mesh(
+ code: str,
+ fmt: str = "glb",
+ *,
+ strict: bool = True,
+ dialect: str = "pipe",
+ bin_path: str | os.PathLike[str] | None = None,
+) -> bytes:
+ """Evaluate a Forma-Pipe script and return exported bytes (.glb/.step/.3mf/.stl/.obj)."""
+ ext = fmt.lstrip(".").lower()
+ with tempfile.TemporaryDirectory(prefix="forma_") as tmp:
+ out_path = Path(tmp) / f"part.{ext}"
+ eval_pipe(code, strict=strict, dialect=dialect, out=out_path, bin_path=bin_path)
+ return out_path.read_bytes()
+
+
+def render_png(
+ code: str,
+ size: int = 512,
+ *,
+ strict: bool = True,
+ dialect: str = "pipe",
+ bin_path: str | os.PathLike[str] | None = None,
+) -> bytes:
+ """Evaluate a Forma-Pipe script and return a 4-view studio PNG as bytes."""
+ with tempfile.TemporaryDirectory(prefix="forma_") as tmp:
+ png_path = Path(tmp) / "preview.png"
+ eval_pipe(
+ code,
+ strict=strict,
+ dialect=dialect,
+ render=png_path,
+ size=size,
+ bin_path=bin_path,
+ )
+ return png_path.read_bytes()
+
+
+def draw_svg(
+ code: str,
+ *,
+ strict: bool = True,
+ dialect: str = "pipe",
+ bin_path: str | os.PathLike[str] | None = None,
+) -> str:
+ """Evaluate a Forma-Pipe script and return a dimensioned 1200x900 SVG blueprint."""
+ with tempfile.TemporaryDirectory(prefix="forma_") as tmp:
+ svg_path = Path(tmp) / "blueprint.svg"
+ eval_pipe(code, strict=strict, dialect=dialect, draw=svg_path, bin_path=bin_path)
+ return svg_path.read_text(encoding="utf-8")
+
+
+if __name__ == "__main__":
+ binary = find_binary()
+ proc = subprocess.run([binary, *sys.argv[1:]], check=False)
+ sys.exit(proc.returncode)
diff --git a/tests/npm_smoke.mjs b/tests/npm_smoke.mjs
index 87a44f5..912bcd1 100644
--- a/tests/npm_smoke.mjs
+++ b/tests/npm_smoke.mjs
@@ -5,6 +5,15 @@ import { tmpdir } from "node:os";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { loadForma, evalPipe, exportMesh, renderPng, drawSvg, getSpec, getSpecTopic } from "../lib/index.mjs";
+import {
+ loadForma as loadEdgeForma,
+ evalPipe as evalEdgePipe,
+ exportMesh as exportEdgeMesh,
+ renderPng as renderEdgePng,
+ drawSvg as drawEdgeSvg,
+ getSpec as getEdgeSpec,
+ getSpecTopic as getEdgeSpecTopic,
+} from "../lib/edge.mjs";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = join(__dirname, "..");
@@ -49,7 +58,77 @@ section(flange, 0.0)
assert.ok(s.inspect().text.includes("parts=2"));
assert.ok(s.tx("rollback", "v1").includes("parts=1"));
s.free();
- console.log("PASS 1/4: JS/WASM ESM API (GLB/STEP/3MF/STL/OBJ/PNG/SVG + stateful tx)");
+ console.log("PASS 1/5: JS/WASM ESM API (GLB/STEP/3MF/STL/OBJ/PNG/SVG + stateful tx)");
+
+ // 1b. Cloudflare Workers / Edge / Browser compatibility (zero node:* imports + WebAssembly.Module + Response + trap recovery)
+ const edgeSrc = readFileSync(join(ROOT, "lib", "edge.mjs"), "utf-8");
+ const workerdSrc = readFileSync(join(ROOT, "lib", "workerd.mjs"), "utf-8");
+ const indexSrc = readFileSync(join(ROOT, "lib", "index.mjs"), "utf-8");
+ assert.ok(!edgeSrc.includes("node:"), "lib/edge.mjs must contain zero node:* references");
+ assert.ok(!workerdSrc.includes("node:"), "lib/workerd.mjs must contain zero node:* references");
+ assert.ok(
+ workerdSrc.includes("../wasm/forma.wasm"),
+ "lib/workerd.mjs must statically import ../wasm/forma.wasm (ending in .wasm for Wrangler)"
+ );
+ assert.ok(
+ !/^\s*import\s+.*["']node:/m.test(indexSrc),
+ "lib/index.mjs must have zero top-level node:* imports"
+ );
+
+ const wasmBytes = readFileSync(join(ROOT, "wasm", "forma.wasm"));
+ const wasmModule = new WebAssembly.Module(wasmBytes);
+ const edgeEngine1 = await loadEdgeForma(wasmModule);
+ const edgeEngine2 = await loadEdgeForma(wasmModule);
+ assert.equal(edgeEngine1, edgeEngine2, "WebAssembly.Module engine is cached");
+ const edgeFresh = await loadEdgeForma(wasmModule, { fresh: true });
+ assert.notEqual(edgeFresh, edgeEngine1, "{ fresh: true } allocates a distinct WASM instance");
+
+ const edgeObs = await evalEdgePipe(flangeCode, { wasm: wasmModule, strict: true });
+ assert.equal(edgeObs.ok, true);
+ assert.ok(edgeObs.text.includes("WT=ok") && edgeObs.text.includes("NM=0"), edgeObs.text);
+ const edgeGlb = await exportEdgeMesh(flangeCode, "glb", { wasm: wasmModule, strict: true });
+ assert.ok(edgeGlb instanceof Uint8Array && edgeGlb.length > 500, "edge GLB non-empty");
+ const edgePng = await renderEdgePng(flangeCode, 128, { wasm: wasmModule, strict: true });
+ assert.equal(edgePng[0], 0x89);
+ assert.equal(edgePng[1], 0x50);
+ const edgeSvg = await drawEdgeSvg(flangeCode, { wasm: wasmModule, strict: true });
+ assert.ok(edgeSvg.includes("<svg"));
+ assert.ok((await getEdgeSpec({ wasm: wasmModule })).includes("Forma-Pipe"));
+ assert.ok((await getEdgeSpecTopic("deform", { wasm: wasmModule })).includes("solidify"));
+
+ const es = edgeEngine1.createSession();
+ es.eval("a = box(1,1,1)\nb = cyl(0.3, 2, z0=1)", { strict: true });
+ const sceneGlb = es.exportSceneBytes();
+ assert.ok(sceneGlb instanceof Uint8Array && sceneGlb.length > 200, "edge exportSceneBytes non-empty");
+ es.free();
+
+ // Browser Response + WebAssembly.Instance loading paths
+ const fakeRes = new Response(wasmBytes, { headers: { "content-type": "application/wasm" } });
+ const resEngine = await loadEdgeForma(fakeRes, { fresh: true });
+ const rs = resEngine.createSession();
+ assert.equal(rs.eval("a = box(1,1,1)", { strict: true }).ok, true);
+ rs.free();
+
+ const rawInstance = new WebAssembly.Instance(wasmModule, {});
+ const instEngine = await loadForma(rawInstance, { fresh: true });
+ const is = instEngine.createSession();
+ assert.equal(is.eval("a = cyl(0.5, 2)", { strict: true }).ok, true);
+ is.free();
+
+ // Trap recovery: WebAssembly.RuntimeError evicts cached engine cleanly
+ const trapMod = new WebAssembly.Module(wasmBytes);
+ const cachedBeforeTrap = await loadEdgeForma(trapMod);
+ cachedBeforeTrap.exports = {
+ ...cachedBeforeTrap.exports,
+ forma_spec() {
+ throw new WebAssembly.RuntimeError("unreachable");
+ },
+ };
+ assert.throws(() => cachedBeforeTrap.spec(), WebAssembly.RuntimeError);
+ const recoveredEngine = await loadEdgeForma(trapMod);
+ assert.notEqual(recoveredEngine, cachedBeforeTrap, "trapped WASM engine is evicted from cache");
+ assert.ok(recoveredEngine.spec().includes("Forma-Pipe"));
+ console.log("PASS 2/5: Edge / Cloudflare Workers / Browser API (WebAssembly.Module, Response, trap recovery, zero node:*)");
// 2. CLI bin/forma.mjs
const cli = join(ROOT, "bin", "forma.mjs");
@@ -66,7 +145,7 @@ section(flange, 0.0)
);
assert.ok(cliOut.includes("WT=ok") && cliOut.includes("NM=0"), cliOut);
assert.ok(statSync(cliGlb).size > 500 && statSync(cliPng).size > 1000 && statSync(cliSvg).size > 500);
- console.log("PASS 2/4: CLI bin/forma.mjs (eval --strict + .glb/.png/.svg)");
+ console.log("PASS 3/5: CLI bin/forma.mjs (eval --strict + .glb/.png/.svg)");
// 3. Test every recipe inside SKILL.md via npm WASM CLI
const skillMd = readFileSync(join(ROOT, "SKILL.md"), "utf-8");
@@ -79,7 +158,7 @@ section(flange, 0.0)
});
assert.ok(out.includes("WT=ok") && out.includes("NM=0"), `SKILL.md recipe ${i + 1} failed: ${out}`);
}
- console.log(`PASS 3/4: SKILL.md (${recipes.length}/${recipes.length} recipes verified on WASM CLI)`);
+ console.log(`PASS 4/5: SKILL.md (${recipes.length}/${recipes.length} recipes verified on WASM CLI)`);
// 4. MCP stdio server bin/forma-mcp.mjs
const mcpGlb = join(tmp, "mcp.glb");
@@ -119,7 +198,7 @@ section(flange, 0.0)
assert.equal(mcpResponses[3].result.isError, false);
assert.ok(mcpResponses[3].result.content[0].text.includes("solidify"));
assert.ok(statSync(mcpGlb).size > 200 && statSync(mcpSceneGlb).size > 200 && statSync(mcpPng).size > 1000);
- console.log("PASS 4/4: MCP stdio server bin/forma-mcp.mjs (4 tools + inspect(topic) + scene/glb/png export)");
+ console.log("PASS 5/5: MCP stdio server bin/forma-mcp.mjs (4 tools + inspect(topic) + scene/glb/png export)");
} finally {
rmSync(tmp, { recursive: true, force: true });
}