feat(wasm): finish route C — bridge package, smoke, site embed L1
Canonical marqdo-bridge.js ships with wasm build, Node ABI smoke covers boot/call, and ext/web gains client_embed for head/static mounting. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
04890e0c73
commit
2445c290c9
11 files changed
+459
-38
No files matched your search
@@ -8,6 +8,7 @@
|
||||
- **C2/C3**:`marqdo wasm build`;会话 `mq_boot`/`mq_call`;GFM wire 表 + `set_text` DOM 回写;[interact.html](examples/browser-hello/interact.html) 计数器示例。
|
||||
- **C4**:[ADR 0003](doc/adr/0003-browser-async-effects.md) 效应表(`fetch` / `after`)+ bridge 续体;[fetch.html](examples/browser-hello/fetch.html)。
|
||||
- **C5**:`release-wasm` 体积配置;`marqdo wasm build` 报告 KiB 并可选 `wasm-opt`;`run_source` bytecode 单测;会话仍为 tree。
|
||||
- **WASM 收口**:规范 `crates/marqdo-wasm/js/marqdo-bridge.js`;`wasm build` 同时拷贝 bridge;Node 冒烟 `tests/wasm`;`web.client_embed` / `网页.客户端挂载`;路线图标 Completed。
|
||||
|
||||
### Fixed
|
||||
- **Admin UI**:主区取消 `max-width:56rem` 限制,表格外包可横向滚动的 `.table-wrap`,单元格完整展示并自动换行;表单加宽且 textarea 可随内容增高。
|
||||
|
||||
@@ -117,7 +117,7 @@ marqdo catalog public -o .marqdo
|
||||
- **原生插件 ABI**:[`include/marqdo_abi.h`](include/marqdo_abi.h) · [ext-abi.md](doc/design/ext-abi.md);`plugins/{demo,agent,web,quantum}`
|
||||
- **用户静态站**:`public/` → `view output` → CI 发布 [gh-pages](https://cflmy.github.io/marqdo/)
|
||||
- **VS Code 扩展**:分支 **`vscode-extension`**(`main` 不跟踪源码;见 [vscode-extension-commit.md](doc/design/vscode-extension-commit.md));Release 附带 `.vsix`
|
||||
- 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md) · [ADR 0002 — 浏览器 WASM 解释器](doc/adr/0002-browser-marqdo-wasm.md)(路线 C,实现中见 [roadmap/browser-wasm.md](doc/roadmap/browser-wasm.md))
|
||||
- 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md) · [ADR 0002 — 浏览器 WASM](doc/adr/0002-browser-marqdo-wasm.md)(C0–C5 完结,见 [roadmap/browser-wasm.md](doc/roadmap/browser-wasm.md))· [ADR 0003 — 异步效应](doc/adr/0003-browser-async-effects.md)
|
||||
|
||||
### 如何使用最新 Marqdo(v0.3.1)
|
||||
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
/**
|
||||
* Canonical Marqdo browser bridge (route C). Host glue only — not app logic.
|
||||
* Copied to site dirs by `marqdo wasm build`.
|
||||
*
|
||||
* ABI: mq_alloc, mq_dealloc, mq_run, mq_boot, mq_call, mq_version
|
||||
* Packed results: u32le length + UTF-8 JSON { ok, stdout, error, value }
|
||||
*
|
||||
* Effects (ADR 0003): set_text, fetch, after
|
||||
*/
|
||||
|
||||
export function readCString(memory, ptr) {
|
||||
const bytes = new Uint8Array(memory.buffer);
|
||||
let end = ptr;
|
||||
while (bytes[end] !== 0) end += 1;
|
||||
return new TextDecoder().decode(bytes.subarray(ptr, end));
|
||||
}
|
||||
|
||||
function decodePacked(exports, outPtr) {
|
||||
if (!outPtr) throw new Error("null wasm result pointer");
|
||||
const view = new DataView(exports.memory.buffer);
|
||||
const jsonLen = view.getUint32(outPtr, true);
|
||||
const jsonBytes = new Uint8Array(exports.memory.buffer, outPtr + 4, jsonLen);
|
||||
const text = new TextDecoder().decode(jsonBytes);
|
||||
exports.mq_dealloc(outPtr, 4 + jsonLen);
|
||||
return JSON.parse(text);
|
||||
}
|
||||
|
||||
function writeUtf8(exports, text) {
|
||||
const encoded = new TextEncoder().encode(text);
|
||||
const ptr = exports.mq_alloc(encoded.length || 1);
|
||||
if (!ptr) throw new Error("mq_alloc failed");
|
||||
new Uint8Array(exports.memory.buffer, ptr, encoded.length).set(encoded);
|
||||
return { ptr, len: encoded.length };
|
||||
}
|
||||
|
||||
export function runSource(exports, source) {
|
||||
const { ptr, len } = writeUtf8(exports, source);
|
||||
const outPtr = exports.mq_run(ptr, len);
|
||||
exports.mq_dealloc(ptr, len || 1);
|
||||
return decodePacked(exports, outPtr);
|
||||
}
|
||||
|
||||
export function boot(exports, source) {
|
||||
const { ptr, len } = writeUtf8(exports, source);
|
||||
const outPtr = exports.mq_boot(ptr, len);
|
||||
exports.mq_dealloc(ptr, len || 1);
|
||||
return decodePacked(exports, outPtr);
|
||||
}
|
||||
|
||||
export function call(exports, name, argsObj = {}) {
|
||||
const n = writeUtf8(exports, name);
|
||||
const a = writeUtf8(exports, JSON.stringify(argsObj ?? {}));
|
||||
const outPtr = exports.mq_call(n.ptr, n.len, a.ptr, a.len);
|
||||
exports.mq_dealloc(n.ptr, n.len || 1);
|
||||
exports.mq_dealloc(a.ptr, a.len || 1);
|
||||
return decodePacked(exports, outPtr);
|
||||
}
|
||||
|
||||
export async function loadWasm(url = "./marqdo_wasm.wasm") {
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) {
|
||||
throw new Error(
|
||||
`failed to fetch ${url} (${res.status}). Build with: marqdo wasm build -o .`,
|
||||
);
|
||||
}
|
||||
const { instance } = await WebAssembly.instantiateStreaming(res, {});
|
||||
return instance.exports;
|
||||
}
|
||||
|
||||
/** Apply C3/C4 return effects: set_text, fetch, after */
|
||||
export function applyDomPatch(value) {
|
||||
if (!value || typeof value !== "object") return;
|
||||
const setText = value.set_text || value.setText;
|
||||
if (setText && typeof setText === "object") {
|
||||
for (const [sel, text] of Object.entries(setText)) {
|
||||
const el = document.querySelector(sel);
|
||||
if (el) el.textContent = String(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run sync DOM patches then schedule async effects (ADR 0003).
|
||||
*/
|
||||
export function applyEffects(exports, value, { onError } = {}) {
|
||||
applyDomPatch(value);
|
||||
if (!value || typeof value !== "object") return Promise.resolve();
|
||||
|
||||
const tasks = [];
|
||||
|
||||
const fetchSpec = value.fetch;
|
||||
if (fetchSpec && typeof fetchSpec === "object" && fetchSpec.url && fetchSpec.then) {
|
||||
tasks.push(runFetchEffect(exports, fetchSpec, onError));
|
||||
}
|
||||
|
||||
const afterSpec = value.after;
|
||||
if (afterSpec && typeof afterSpec === "object" && afterSpec.then) {
|
||||
tasks.push(runAfterEffect(exports, afterSpec, onError));
|
||||
}
|
||||
|
||||
return Promise.all(tasks);
|
||||
}
|
||||
|
||||
async function runFetchEffect(exports, spec, onError) {
|
||||
const thenFn = spec.then;
|
||||
const method = (spec.method || "GET").toUpperCase();
|
||||
const init = { method };
|
||||
if (spec.headers && typeof spec.headers === "object") {
|
||||
init.headers = spec.headers;
|
||||
}
|
||||
if (spec.body != null && method !== "GET" && method !== "HEAD") {
|
||||
init.body = typeof spec.body === "string" ? spec.body : JSON.stringify(spec.body);
|
||||
}
|
||||
try {
|
||||
const res = await fetch(String(spec.url), init);
|
||||
const body = await res.text();
|
||||
const result = call(exports, thenFn, {
|
||||
ok: res.ok,
|
||||
status: res.status,
|
||||
body,
|
||||
});
|
||||
if (!result.ok) {
|
||||
if (onError) onError(result.error);
|
||||
else console.error(result.error);
|
||||
return;
|
||||
}
|
||||
await applyEffects(exports, result.value, { onError });
|
||||
if (result.stdout) console.log(result.stdout);
|
||||
} catch (e) {
|
||||
try {
|
||||
const result = call(exports, thenFn, {
|
||||
ok: false,
|
||||
status: 0,
|
||||
body: "",
|
||||
error: String(e),
|
||||
});
|
||||
if (result.ok) await applyEffects(exports, result.value, { onError });
|
||||
else if (onError) onError(result.error);
|
||||
} catch (e2) {
|
||||
if (onError) onError(String(e2));
|
||||
else console.error(e2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function runAfterEffect(exports, spec, onError) {
|
||||
const ms = Math.max(0, Number(spec.ms) || 0);
|
||||
const thenFn = spec.then;
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
try {
|
||||
const result = call(exports, thenFn, { ok: true });
|
||||
if (!result.ok) {
|
||||
if (onError) onError(result.error);
|
||||
else console.error(result.error);
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
Promise.resolve(applyEffects(exports, result.value, { onError })).then(resolve);
|
||||
if (result.stdout) console.log(result.stdout);
|
||||
} catch (e) {
|
||||
if (onError) onError(String(e));
|
||||
else console.error(e);
|
||||
resolve();
|
||||
}
|
||||
}, ms);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire events from `# main` return value.
|
||||
* Accepts a list of row maps, or `{ wire: [...] }`.
|
||||
*/
|
||||
export function wireEvents(exports, bootValue, { onError } = {}) {
|
||||
let rows = [];
|
||||
if (Array.isArray(bootValue)) rows = bootValue;
|
||||
else if (bootValue && Array.isArray(bootValue.wire)) rows = bootValue.wire;
|
||||
|
||||
for (const row of rows) {
|
||||
const sel = row["选择器"] || row.selector || row.sel;
|
||||
const ev = row["事件"] || row.event || "click";
|
||||
const fn = row["调用"] || row.call || row.fn;
|
||||
if (!sel || !fn) continue;
|
||||
const nodes = document.querySelectorAll(sel);
|
||||
nodes.forEach((node) => {
|
||||
node.addEventListener(ev, () => {
|
||||
try {
|
||||
const result = call(exports, fn, { event: ev });
|
||||
if (!result.ok) {
|
||||
if (onError) onError(result.error);
|
||||
else console.error(result.error);
|
||||
return;
|
||||
}
|
||||
applyEffects(exports, result.value, { onError });
|
||||
if (result.stdout) console.log(result.stdout);
|
||||
} catch (e) {
|
||||
if (onError) onError(String(e));
|
||||
else console.error(e);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
return rows.length;
|
||||
}
|
||||
@@ -122,7 +122,7 @@ source: &str (+ optional import map)
|
||||
| 路径 | 角色 |
|
||||
|------|------|
|
||||
| `marqdo`(根) | 核心;feature-gate |
|
||||
| `crates/marqdo-wasm` | `cdylib`:`mq_alloc` / `mq_dealloc` / `mq_run` / `mq_version`(长度前缀 JSON;**无** wasm-bindgen CLI) |
|
||||
| `crates/marqdo-wasm` | `cdylib`:`mq_*` ABI + `js/marqdo-bridge.js` |
|
||||
| `ext/web` 或 `web/browser` | L1:`浏览器.运行` / `交互装配`(C3+) |
|
||||
| `examples/browser-hello/` | 静态页 + wasm 冒烟 |
|
||||
| `tests/browser/` 或金样脚本 | Node/wasmtime 跑 `run_source` 对齐 |
|
||||
@@ -229,11 +229,28 @@ Bridge:`applyEffects(exports, value)` — 先 DOM,再调度异步;**不**
|
||||
| 层 | 负责 |
|
||||
|----|------|
|
||||
| 服务端 `plugins/web` | 路由、DB、会话、SSR HTML、样式/头/图装配 |
|
||||
| 页面壳 | 输出时可选嵌入 `<script type="module" src="marqdo-loader.js">` + wasm |
|
||||
| 浏览器 L1 | `运行` / `交互装配` /(后)`请求` |
|
||||
| 核心 | 可移植 VM + `run_source` + browser `HostFn` 子集 |
|
||||
| 页面壳 | `头装配` 挂 `module` → `marqdo-bridge.js`;`static` 提供 `.wasm` |
|
||||
| 浏览器 L1 | `客户端挂载` / `client_embed`;效应约定见 ADR 0003 |
|
||||
| 核心 / crate | `run_source`、`BrowserSession`、`marqdo-wasm` ABI |
|
||||
|
||||
W8 资源表可增加「挂 wasm / module」行(既有 `page.head` / `头装配`),属 C2/C3 集成,不阻塞 C1。
|
||||
挂载示例:
|
||||
|
||||
```markdown
|
||||
`头` =
|
||||
|
||||
| 关系 | 地址 |
|
||||
|------|------|
|
||||
| module | /static/marqdo-bridge.js |
|
||||
|
||||
*p = > page.头装配 表=头*
|
||||
```
|
||||
|
||||
```bash
|
||||
marqdo wasm build -o static # marqdo_wasm.wasm + marqdo-bridge.js
|
||||
# app.static dir=static
|
||||
```
|
||||
|
||||
业务页再 `boot` 自己的 `.mq.md`(见 `examples/browser-hello/`)。
|
||||
|
||||
---
|
||||
|
||||
@@ -268,16 +285,17 @@ W8 资源表可增加「挂 wasm / module」行(既有 `page.head` / `头装
|
||||
|
||||
---
|
||||
|
||||
## 14. C5 硬化(已落地子集)
|
||||
## 14. C5 硬化(已落地)
|
||||
|
||||
| 项 | 状态 |
|
||||
|----|------|
|
||||
| `profile.release-wasm` + `marqdo wasm build` 体积报告 | done |
|
||||
| 可选 `wasm-opt` | done(Binaryen 在 PATH 时) |
|
||||
| `run_source` bytecode 金样 | done(单元测) |
|
||||
| 会话 bytecode / view 断点复用同一 wasm | **后续** |
|
||||
|
||||
预算:`release-wasm` 实测约 **0.9 MiB** 未压缩(嵌入 `lib/` 后);gzip/CDN 另计。目标维持 **≤ ~1.2 MiB**。
|
||||
| `profile.release-wasm` + `marqdo wasm build` 体积报告 | done(~0.9 MiB) |
|
||||
| 可选 `wasm-opt` | done |
|
||||
| `run_source` bytecode 金样 | done |
|
||||
| 规范 bridge + 构建拷贝 | done(`crates/marqdo-wasm/js/`) |
|
||||
| Node ABI 冒烟 | done(`tests/wasm`) |
|
||||
| 站点 `头装配` / L1 `client_embed` | done |
|
||||
| 会话 bytecode / view 断点复用 | **非本版目标** |
|
||||
|
||||
---
|
||||
|
||||
|
||||
+18
-12
@@ -2,7 +2,7 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **C0–C5 首轮完结**(会话 bytecode / view 复用仍可加深) |
|
||||
| 状态 | **Completed**(路线 C 首版功能完备) |
|
||||
| 日期 | 2026-09-01 |
|
||||
| ADR | [0002](../adr/0002-browser-marqdo-wasm.md) · [0003](../adr/0003-browser-async-effects.md) |
|
||||
| 设计 | [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) |
|
||||
@@ -11,24 +11,30 @@
|
||||
|------|------|------|
|
||||
| **C0** | feature 门控;`wasm32` check | **done** |
|
||||
| **C1** | `run_source` + `mq_run` | **done** |
|
||||
| **C2** | loader + `marqdo wasm build` | **done** |
|
||||
| **C2** | loader + `marqdo wasm build`(含 bridge 拷贝) | **done** |
|
||||
| **C3** | session wire + `set_text` | **done** |
|
||||
| **C4** | `fetch` / `after` 效应 | **done** |
|
||||
| **C5** | `release-wasm` 体积;`wasm-opt`;`run_source` bytecode 测 | **done**(会话仍 tree) |
|
||||
| **C5** | `release-wasm` 体积;冒烟;站点挂载文档 / L1 | **done** |
|
||||
|
||||
## C5
|
||||
## 交付物
|
||||
|
||||
```bash
|
||||
marqdo wasm build -o examples/browser-hello # prints KiB; wasm-opt if installed
|
||||
```
|
||||
| 产物 | 路径 |
|
||||
|------|------|
|
||||
| ABI crate | `crates/marqdo-wasm` |
|
||||
| 官方 bridge | `crates/marqdo-wasm/js/marqdo-bridge.js` |
|
||||
| CLI | `marqdo wasm build -o DIR` |
|
||||
| 示例 | `examples/browser-hello/` |
|
||||
| 冒烟 | `tests/wasm/smoke.mjs` · `tests/wasm_smoke.rs` |
|
||||
| L1 | `web.client_embed` / `网页.客户端挂载` |
|
||||
|
||||
- Profile:`release-wasm`(`opt-level=z`, LTO, strip)
|
||||
- `BrowserSession` 明确拒绝 bytecode(待 VM entry-env)
|
||||
- 一发 `run_source(..., backend=bytecode)` 单测绿
|
||||
## 明确非目标(本版不做)
|
||||
|
||||
- 浏览器会话 bytecode(缺 entry-env invoke;一发 `run_source` 已支持 bytecode)
|
||||
- 把 axum / SQLite 服务端搬进 WASM
|
||||
- 业务手写 JS 框架
|
||||
|
||||
## 进度
|
||||
|
||||
| 日期 | 记录 |
|
||||
|------|------|
|
||||
| 2026-09-01 | C0–C4 |
|
||||
| 2026-09-01 | C5 体积 profile + 文档 |
|
||||
| 2026-09-01 | C0–C5 完结并 push;收口 bridge 规范路径 + 冒烟 + 挂载 L1 |
|
||||
@@ -1,8 +1,11 @@
|
||||
/**
|
||||
* Official Marqdo browser bridge (route C). Host glue only — not app logic.
|
||||
* Canonical Marqdo browser bridge (route C). Host glue only — not app logic.
|
||||
* Copied to site dirs by `marqdo wasm build`.
|
||||
*
|
||||
* ABI: mq_alloc, mq_dealloc, mq_run, mq_boot, mq_call, mq_version
|
||||
* Packed results: u32le length + UTF-8 JSON { ok, stdout, error, value }
|
||||
*
|
||||
* Effects (ADR 0003): set_text, fetch, after
|
||||
*/
|
||||
|
||||
export function readCString(memory, ptr) {
|
||||
@@ -78,8 +81,6 @@ export function applyDomPatch(value) {
|
||||
|
||||
/**
|
||||
* Run sync DOM patches then schedule async effects (ADR 0003).
|
||||
* Returns a Promise that settles when immediate scheduling is done
|
||||
* (not when fetch/after callbacks finish).
|
||||
*/
|
||||
export function applyEffects(exports, value, { onError } = {}) {
|
||||
applyDomPatch(value);
|
||||
@@ -169,7 +170,6 @@ function runAfterEffect(exports, spec, onError) {
|
||||
/**
|
||||
* Wire events from `# main` return value.
|
||||
* Accepts a list of row maps, or `{ wire: [...] }`.
|
||||
* Row keys: 选择器|selector, 事件|event, 调用|call
|
||||
*/
|
||||
export function wireEvents(exports, bootValue, { onError } = {}) {
|
||||
let rows = [];
|
||||
|
||||
@@ -127,6 +127,15 @@ Assemble `<head>` resources from a GFM table (`|rel|href|type|sizes|media|as|cro
|
||||
|
||||
**> web_page_head page=`self` table=`table`**
|
||||
|
||||
## client_embed
|
||||
+ `bridge`="/static/marqdo-bridge.js"
|
||||
|
||||
Return an HTML snippet that loads the official browser Marqdo bridge (`marqdo-bridge.js`, route C).
|
||||
Run `marqdo wasm build -o static` first, and prefer a `head` table row with `rel=module`.
|
||||
Author `.mq.md` wire/`fetch` effects: [browser-marqdo-wasm.md](../../doc/design/browser-marqdo-wasm.md).
|
||||
|
||||
**"<script type=\"module\" src=\"" + bridge + "\"></script>"**
|
||||
|
||||
## images
|
||||
+ `table`
|
||||
|
||||
|
||||
@@ -116,6 +116,15 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
|
||||
|
||||
**> web_page_head page=`self` table=`表`**
|
||||
|
||||
## 客户端挂载
|
||||
+ `桥`="/static/marqdo-bridge.js"
|
||||
|
||||
返回一段用于挂载浏览器 Marqdo(路线 C)的 HTML:加载官方 `marqdo-bridge.js` 模块。
|
||||
请先 `marqdo wasm build -o static`(或站点静态目录),并用 `头装配` 挂 `关系=module` 行;
|
||||
业务 `.mq.md` 与 `wire`/`fetch` 效应见 [browser-marqdo-wasm.md](../../doc/design/browser-marqdo-wasm.md)。
|
||||
|
||||
**"<script type=\"module\" src=\"" + 桥 + "\"></script>"**
|
||||
|
||||
## 图片装配
|
||||
+ `表`
|
||||
|
||||
|
||||
+49
-9
@@ -1,11 +1,13 @@
|
||||
//! `marqdo wasm build` — compile `marqdo-wasm` and copy the `.wasm` artifact.
|
||||
//! `marqdo wasm build` — compile `marqdo-wasm` and copy artifacts for the browser host.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
|
||||
/// Build size-optimized wasm32 artifact and copy `marqdo_wasm.wasm` into `out_dir`.
|
||||
/// Build size-optimized wasm32 artifact and copy into `out_dir`:
|
||||
/// - `marqdo_wasm.wasm`
|
||||
/// - `marqdo-bridge.js` (canonical host glue)
|
||||
pub fn build_wasm(out_dir: &Path) -> Result<()> {
|
||||
let status = Command::new("cargo")
|
||||
.args([
|
||||
@@ -26,31 +28,70 @@ pub fn build_wasm(out_dir: &Path) -> Result<()> {
|
||||
let mut artifact = find_wasm_artifact()?;
|
||||
std::fs::create_dir_all(out_dir)
|
||||
.with_context(|| format!("create {}", out_dir.display()))?;
|
||||
let dest = out_dir.join("marqdo_wasm.wasm");
|
||||
|
||||
if let Some(optimized) = try_wasm_opt(&artifact)? {
|
||||
artifact = optimized;
|
||||
}
|
||||
|
||||
std::fs::copy(&artifact, &dest).with_context(|| {
|
||||
let dest_wasm = out_dir.join("marqdo_wasm.wasm");
|
||||
std::fs::copy(&artifact, &dest_wasm).with_context(|| {
|
||||
format!(
|
||||
"copy {} → {}",
|
||||
artifact.display(),
|
||||
dest.display()
|
||||
dest_wasm.display()
|
||||
)
|
||||
})?;
|
||||
let bytes = std::fs::metadata(&dest)
|
||||
let bytes = std::fs::metadata(&dest_wasm)
|
||||
.map(|m| m.len())
|
||||
.unwrap_or(0);
|
||||
println!(
|
||||
"wrote {} ({:.1} KiB)",
|
||||
dest.display(),
|
||||
dest_wasm.display(),
|
||||
bytes as f64 / 1024.0
|
||||
);
|
||||
|
||||
let bridge_src = find_bridge_js()?;
|
||||
let dest_bridge = out_dir.join("marqdo-bridge.js");
|
||||
std::fs::copy(&bridge_src, &dest_bridge).with_context(|| {
|
||||
format!(
|
||||
"copy {} → {}",
|
||||
bridge_src.display(),
|
||||
dest_bridge.display()
|
||||
)
|
||||
})?;
|
||||
println!("wrote {}", dest_bridge.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run `wasm-opt -Oz` when Binaryen is installed; returns path to optimized file.
|
||||
fn find_bridge_js() -> Result<PathBuf> {
|
||||
let mut candidates = Vec::new();
|
||||
if let Ok(manifest) = std::env::var("CARGO_MANIFEST_DIR") {
|
||||
candidates.push(
|
||||
PathBuf::from(manifest).join("crates/marqdo-wasm/js/marqdo-bridge.js"),
|
||||
);
|
||||
}
|
||||
candidates.push(PathBuf::from("crates/marqdo-wasm/js/marqdo-bridge.js"));
|
||||
// When running from installed binary, try next to current_exe ../../…
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
if let Some(root) = exe.parent().and_then(|p| p.parent()).and_then(|p| p.parent()) {
|
||||
candidates.push(root.join("crates/marqdo-wasm/js/marqdo-bridge.js"));
|
||||
}
|
||||
}
|
||||
for c in &candidates {
|
||||
if c.is_file() {
|
||||
return Ok(c.clone());
|
||||
}
|
||||
}
|
||||
bail!(
|
||||
"marqdo-bridge.js not found; tried: {}",
|
||||
candidates
|
||||
.iter()
|
||||
.map(|p| p.display().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
)
|
||||
}
|
||||
|
||||
fn try_wasm_opt(input: &Path) -> Result<Option<PathBuf>> {
|
||||
let which = Command::new("wasm-opt").arg("--version").output();
|
||||
let Ok(out) = which else {
|
||||
@@ -68,7 +109,6 @@ fn try_wasm_opt(input: &Path) -> Result<Option<PathBuf>> {
|
||||
.status()
|
||||
.context("wasm-opt spawn failed")?;
|
||||
if !status.success() {
|
||||
// Retry without bulk-memory flag for older binaryen.
|
||||
let status2 = Command::new("wasm-opt")
|
||||
.args(["-Oz"])
|
||||
.arg(input)
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* WASM ABI smoke (C1/C3): boot counter.mq.md, call bump twice.
|
||||
* Usage: node tests/wasm/smoke.mjs [path/to/marqdo_wasm.wasm]
|
||||
*/
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const root = path.resolve(__dirname, "../..");
|
||||
|
||||
const wasmPath =
|
||||
process.argv[2] ||
|
||||
path.join(root, "examples/browser-hello/marqdo_wasm.wasm");
|
||||
const srcPath = path.join(root, "examples/browser-hello/counter.mq.md");
|
||||
|
||||
if (!fs.existsSync(wasmPath)) {
|
||||
console.error("missing wasm:", wasmPath);
|
||||
console.error("build: marqdo wasm build -o examples/browser-hello");
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const buf = fs.readFileSync(wasmPath);
|
||||
const { instance } = await WebAssembly.instantiate(buf, {});
|
||||
const e = instance.exports;
|
||||
const enc = new TextEncoder();
|
||||
const dec = new TextDecoder();
|
||||
|
||||
function pack(ptr) {
|
||||
const len = new DataView(e.memory.buffer).getUint32(ptr, true);
|
||||
const j = JSON.parse(dec.decode(new Uint8Array(e.memory.buffer, ptr + 4, len)));
|
||||
e.mq_dealloc(ptr, 4 + len);
|
||||
return j;
|
||||
}
|
||||
|
||||
function write(s) {
|
||||
const b = enc.encode(s);
|
||||
const p = e.mq_alloc(b.length || 1);
|
||||
new Uint8Array(e.memory.buffer, p, b.length).set(b);
|
||||
return { p, n: b.length };
|
||||
}
|
||||
|
||||
function boot(source) {
|
||||
const { p, n } = write(source);
|
||||
const o = e.mq_boot(p, n);
|
||||
e.mq_dealloc(p, n || 1);
|
||||
return pack(o);
|
||||
}
|
||||
|
||||
function call(name, args) {
|
||||
const a = write(name);
|
||||
const b = write(JSON.stringify(args || {}));
|
||||
const o = e.mq_call(a.p, a.n, b.p, b.n);
|
||||
e.mq_dealloc(a.p, a.n || 1);
|
||||
e.mq_dealloc(b.p, b.n || 1);
|
||||
return pack(o);
|
||||
}
|
||||
|
||||
const source = fs.readFileSync(srcPath, "utf8");
|
||||
const b = boot(source);
|
||||
if (!b.ok) {
|
||||
console.error("boot failed", b.error);
|
||||
process.exit(1);
|
||||
}
|
||||
if (!Array.isArray(b.value) || b.value.length < 1) {
|
||||
console.error("expected wire list", b.value);
|
||||
process.exit(1);
|
||||
}
|
||||
const c1 = call("bump", {});
|
||||
const c2 = call("bump", {});
|
||||
if (!c1.ok || !c2.ok) {
|
||||
console.error("call failed", c1, c2);
|
||||
process.exit(1);
|
||||
}
|
||||
if (c2.value?.set_text?.["#count"] !== "2") {
|
||||
console.error("expected count 2, got", c2.value);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log("wasm smoke ok");
|
||||
@@ -0,0 +1,54 @@
|
||||
//! Browser WASM integration smoke (Node + wasm artifact).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
fn wasm_artifact() -> Option<PathBuf> {
|
||||
let mut cands = Vec::new();
|
||||
if let Ok(td) = std::env::var("CARGO_TARGET_DIR") {
|
||||
cands.push(PathBuf::from(td).join("wasm32-unknown-unknown/release-wasm/marqdo_wasm.wasm"));
|
||||
}
|
||||
cands.push(PathBuf::from(
|
||||
"target/wasm32-unknown-unknown/release-wasm/marqdo_wasm.wasm",
|
||||
));
|
||||
cands.push(PathBuf::from("examples/browser-hello/marqdo_wasm.wasm"));
|
||||
cands.into_iter().find(|p| p.is_file())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wasm_node_abi_smoke() {
|
||||
if Command::new("node").arg("--version").output().is_err() {
|
||||
eprintln!("skip: node not installed");
|
||||
return;
|
||||
}
|
||||
let wasm = match wasm_artifact() {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
if std::env::var("MARQDO_WASM_SMOKE").ok().as_deref() != Some("1") {
|
||||
eprintln!("skip: no wasm artifact (run `marqdo wasm build` or set MARQDO_WASM_SMOKE=1)");
|
||||
return;
|
||||
}
|
||||
let status = Command::new(env!("CARGO_BIN_EXE_marqdo"))
|
||||
.args(["wasm", "build", "-o", "examples/browser-hello"])
|
||||
.status()
|
||||
.expect("marqdo wasm build");
|
||||
assert!(status.success(), "marqdo wasm build failed");
|
||||
PathBuf::from("examples/browser-hello/marqdo_wasm.wasm")
|
||||
}
|
||||
};
|
||||
assert!(wasm.is_file(), "missing {}", wasm.display());
|
||||
let out = Command::new("node")
|
||||
.args(["tests/wasm/smoke.mjs", wasm.to_str().unwrap()])
|
||||
.output()
|
||||
.expect("node smoke");
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"smoke failed: status={} stdout={} stderr={}",
|
||||
out.status,
|
||||
stdout,
|
||||
stderr
|
||||
);
|
||||
assert!(stdout.contains("wasm smoke ok"), "stdout={stdout}");
|
||||
}
|
||||
Reference in new issue
Block a user